From b3d4898d9e8452ea0b8d848c048e712d43b8d9a3 Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 11 Jun 2017 14:22:02 +0300 Subject: [SDC-29] rebase continue work to align source Change-Id: I218f1c5ee23fb2c8314f1c70921d3ad8682c10f4 Signed-off-by: Michael Lando --- asdc-tests/pom.xml | 2 +- .../java/org/openecomp/sdc/ci/tests/api/Urls.java | 2 +- .../attribute/ComponentInstanceAttributeTest.java | 8 +- .../execute/devCI/ValidateConformanceLevel.java | 29 +- .../FilteredDataByParamsComponentServletTest.java | 124 + .../execute/imports/ImportCsarResourceTest.java | 21 +- .../execute/imports/ImportNewResourceCITest.java | 7 +- .../execute/imports/ImportToscaResourceTest.java | 15 +- .../product/ChangeServiceInstanceVersionTest.java | 1478 -------- .../ci/tests/execute/product/ProductBaseTest.java | 200 -- .../tests/execute/product/ProductCheckinTest.java | 199 -- .../tests/execute/product/ProductCheckoutTest.java | 147 - .../product/ProductComponentInstanceCRUDTest.java | 1175 ------- .../product/ProductCreateWithValidationsTest.java | 1711 ---------- .../ci/tests/execute/product/ProductCrudTest.java | 2203 ------------ .../execute/product/ProductGetFollowedTest.java | 164 - .../execute/product/ProductLifecycleTest.java | 55 - .../ci/tests/execute/product/ProductTestBase.java | 148 - .../product/ProductToscaYamlGenerationTest.java | 83 - .../execute/product/ProductUndoCheckoutTest.java | 216 -- .../sdc/ci/tests/utils/rest/ResourceRestUtils.java | 46 + .../main/resources/ci/conf/attsdc-packages.yaml | 3 +- .../src/main/resources/ci/testSuites/ciFull.xml | 49 +- .../src/main/resources/ci/testSuites/product.xml | 14 - .../src/main/resources/ci/testSuites/resource.xml | 40 - .../src/main/resources/ci/testSuites/sanity.xml | 47 - .../normativeTypes/network/images/network.png | Bin 159707 -> 4214 bytes .../webApplication/images/network.png | Bin 159707 -> 4214 bytes .../CI/csars/vmmc_relate_by_cap_name.csar | Bin 35467 -> 35471 bytes asdctool/pom.xml | 22 + .../impl/EsToCassandraDataMigrationConfig.java | 7 +- .../sdc/asdctool/impl/TitanGraphInitializer.java | 268 +- .../sdc/asdctool/impl/migration/Migration.java | 17 - .../asdctool/impl/migration/Migration1707Task.java | 21 + .../asdctool/impl/migration/v1604/AppConfig.java | 57 +- .../impl/migration/v1702/Migration1702.java | 2 - .../migration/v1707/DistributionStatusUpdate.java | 140 + .../impl/migration/v1707/Migration1707.java | 15 +- .../impl/migration/v1707/Migration1707Config.java | 101 +- .../migration/v1707/Migration1707RelationsFix.java | 131 + .../impl/migration/v1707/Migration1707VnfFix.java | 100 + .../migration/v1707/RenameGraphPropertyKeys.java | 6 +- .../impl/migration/v1707/ToscaNamesUpdate.java | 4 +- .../migration/v1707/ToscaTemplateRegeneration.java | 66 +- .../migration/v1707/VfModulesPropertiesAdding.java | 108 +- .../v1707/jsonmodel/ComponentMigration.java | 39 +- .../v1707/jsonmodel/ConsumersMigration.java | 47 + .../v1707/jsonmodel/InvariantUUIDResolver.java | 41 + .../v1707/jsonmodel/JsonModelMigration.java | 20 +- .../v1707/jsonmodel/NormativesMigration.java | 34 +- .../jsonmodel/ResourcesCategoriesMigration.java | 33 +- .../jsonmodel/ServiceCategoriesMigration.java | 11 +- .../v1707/jsonmodel/ServicesMigration.java | 121 +- .../v1707/jsonmodel/UserStatesMigration.java | 16 +- .../migration/v1707/jsonmodel/UsersMigration.java | 12 +- .../v1707/jsonmodel/VFResourcesMigration.java | 2 +- .../v1707/jsonmodel/VersionMigration.java | 40 +- .../openecomp/sdc/asdctool/main/MigrationMenu.java | 76 +- .../sdc/asdctool/main/SdcSchemaFileImport.java | 84 + .../src/main/resources/config/configuration.yaml | 4 +- asdctool/src/main/resources/config/groupTypes.yml | 15 +- asdctool/src/main/resources/config/logback.xml | 28 +- .../main/resources/scripts/dataMigration1707.sh | 2 +- .../scripts/distributionStatusUpdate1707.sh | 35 + .../resources/scripts/migration1707RelationsFix.sh | 33 + .../main/resources/scripts/retrieve_schema_file.sh | 20 + .../src/main/resources/scripts/vfmoduleFix1707.sh | 35 + catalog-be/pom.xml | 4 +- .../sdc/be/components/ArtifactsResolver.java | 27 + .../engine/JsonContainerResourceInstance.java | 7 + .../distribution/engine/NotificationDataImpl.java | 4 +- .../engine/VfModuleArtifactPayload.java | 2 + .../be/components/impl/ArtifactResolverImpl.java | 62 + .../be/components/impl/ArtifactsBusinessLogic.java | 109 +- .../be/components/impl/AttributeBusinessLogic.java | 32 +- .../be/components/impl/ComponentBusinessLogic.java | 93 +- .../impl/ComponentInstanceBusinessLogic.java | 42 +- .../be/components/impl/CsarValidationUtils.java | 2 +- .../be/components/impl/ElementBusinessLogic.java | 6 +- .../sdc/be/components/impl/GroupBusinessLogic.java | 1860 +++++------ .../sdc/be/components/impl/ImportUtils.java | 27 +- .../be/components/impl/InputsBusinessLogic.java | 21 +- .../be/components/impl/ResourceBusinessLogic.java | 85 +- .../be/components/impl/ResourceImportManager.java | 33 +- .../be/components/impl/ServiceBusinessLogic.java | 31 +- .../components/lifecycle/CheckoutTransition.java | 12 +- .../datamodel/utils/UiComponentDataConverter.java | 17 + .../org/openecomp/sdc/be/ecomp/EcompIntImpl.java | 27 +- .../ecomp/converters/AssetMetadataConverter.java | 391 +++ .../servlet/AssetMetadataConverter.java | 392 --- .../be/externalapi/servlet/AssetsDataServlet.java | 1 + .../org/openecomp/sdc/be/impl/ComponentsUtils.java | 27 + .../sdc/be/listen/BEAppContextListener.java | 34 +- .../be/servlets/AbstractValidationsServlet.java | 2 +- .../sdc/be/servlets/AttributeServlet.java | 22 +- .../sdc/be/servlets/BeGenericServlet.java | 2 +- .../sdc/be/servlets/ComponentInstanceServlet.java | 8 +- .../sdc/be/servlets/ComponentServlet.java | 6 +- .../sdc/be/servlets/LifecycleServlet.java | 5 +- .../sdc/be/servlets/UserAdminServlet.java | 38 - .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 154 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 7 +- .../openecomp/sdc/be/user/IUserBusinessLogic.java | 4 - .../openecomp/sdc/be/user/UserBusinessLogic.java | 108 +- .../src/main/resources/application-context.xml | 2 +- catalog-be/src/main/resources/config/SDC.zip | Bin 29236 -> 30057 bytes .../main/resources/config/error-configuration.yaml | 10 +- catalog-be/src/main/resources/config/logback.xml | 4 +- .../import/tosca/data-types/dataTypes.yml | 13 + .../import/tosca/data-types/dataTypes.zip | Bin 5243 -> 5277 bytes .../components/impl/ArtifactBusinessLogicTest.java | 4 +- .../be/components/impl/ArtifactResolverTest.java | 91 + .../sdc/be/components/impl/ImportUtilsTest.java | 7 +- .../externalapi/servlet/AssetsDataServletTest.java | 1 + .../org/openecomp/sdc/be/dao/api/ActionStatus.java | 2 +- .../be/dao/cassandra/SdcSchemaFilesAccessor.java | 4 +- .../dao/cassandra/SdcSchemaFilesCassandraDao.java | 36 +- .../sdc/be/dao/jsongraph/types/VertexTypeEnum.java | 4 +- .../be/dao/neo4j/GraphPropertiesDictionary.java | 1 + .../sdc/be/resources/data/AttributeData.java | 12 +- .../be/resources/data/ComponentMetadataData.java | 2 + .../be/resources/data/ESSdcSchemaFilesData.java | 102 - .../sdc/be/resources/data/SdcSchemaFilesData.java | 114 + catalog-fe/pom.xml | 2 +- .../openecomp/sdc/fe/servlets/PortalServlet.java | 24 +- catalog-fe/src/main/resources/config/logback.xml | 4 +- .../CI/originalResources/images/network.png | Bin 159707 -> 4214 bytes .../sdc/be/model/AttributeDefinition.java | 71 - .../java/org/openecomp/sdc/be/model/Component.java | 6 +- .../sdc/be/model/ComponentInstanceAttribute.java | 78 - .../sdc/be/model/ComponentInstanceInput.java | 18 +- .../sdc/be/model/ComponentInstanceProperty.java | 8 + .../openecomp/sdc/be/model/PropertyDefinition.java | 30 +- .../java/org/openecomp/sdc/be/model/Resource.java | 6 +- .../sdc/be/model/jsontitan/datamodel/NodeType.java | 8 +- .../jsontitan/datamodel/TopologyTemplate.java | 9 +- .../jsontitan/operations/ArtifactsOperations.java | 16 +- .../model/jsontitan/operations/BaseOperation.java | 50 +- .../operations/NodeTemplateOperation.java | 67 +- .../jsontitan/operations/NodeTypeOperation.java | 135 +- .../operations/TopologyTemplateOperation.java | 40 +- .../operations/ToscaElementLifecycleOperation.java | 906 +++-- .../operations/ToscaElementOperation.java | 204 +- .../jsontitan/operations/ToscaOperationFacade.java | 217 +- .../be/model/jsontitan/utils/ModelConverter.java | 28 +- .../model/operations/api/IAttributeOperation.java | 26 +- .../api/IComponentInstanceOperation.java | 7 +- .../model/operations/api/IConsumerOperation.java | 8 + .../model/operations/api/IResourceOperation.java | 5 - .../model/operations/api/IUserAdminOperation.java | 2 +- .../model/operations/impl/AttributeOperation.java | 96 +- .../impl/ComponentInstanceOperation.java | 41 +- .../model/operations/impl/ConsumerOperation.java | 16 +- .../model/operations/impl/ResourceOperation.java | 124 +- .../model/operations/impl/UserAdminOperation.java | 14 +- .../migration/MigrationErrorInformer.java | 39 - .../migration/MigrationMalformedDataLogger.java | 44 + .../sdc/be/model/tosca/ToscaPropertyType.java | 2 + .../tosca/converters/ToscaMapValueConverter.java | 2 +- .../sdc/be/ui/model/UiComponentDataTransfer.java | 10 +- .../sdc/be/ui/model/UiComponentMetadata.java | 1 + .../sdc/be/ui/model/UiResourceDataTransfer.java | 9 +- .../sdc/be/ui/model/UiResourceMetadata.java | 3 + .../composition-graph.directive.ts | 3 +- .../property-types/type-map/type-map-directive.ts | 10 +- catalog-ui/src/app/models.ts | 3 + catalog-ui/src/app/models/components/component.ts | 16 +- .../app/models/graph/graph-links/links-factory.ts | 27 +- .../properties-inputs/derived-fe-property.ts | 75 +- .../app/models/properties-inputs/input-be-model.ts | 49 + .../app/models/properties-inputs/input-fe-model.ts | 24 +- .../models/properties-inputs/property-be-model.ts | 25 +- .../models/properties-inputs/property-fe-model.ts | 115 +- .../properties-inputs/simple-flat-property.ts | 15 + catalog-ui/src/app/models/property-fe-model.ts | 78 - catalog-ui/src/app/modules/view-model-module.ts | 2 +- catalog-ui/src/app/ng2/app.module.ts | 4 +- .../dynamic-element/dynamic-element.component.ts | 21 +- .../dynamic-element/dynamic-element.module.ts | 4 +- .../checkbox/ui-element-checkbox.component.html | 2 +- .../dropdown/ui-element-dropdown.component.html | 2 +- .../dropdown/ui-element-dropdown.component.ts | 3 +- .../input/ui-element-input.component.html | 2 + .../input/ui-element-input.component.ts | 3 +- .../ui-element-integer-input.component.html | 15 + .../ui-element-integer-input.component.less | 17 + .../ui-element-integer-input.component.ts | 21 + .../ui-element-popover-input.component.html | 4 +- .../ui-element-popover-input.component.ts | 3 +- .../elements-ui/ui-element-base.component.ts | 1 + .../filter-properties-assignment.component.less | 10 +- .../confirmation-delete-input.component.html | 3 + .../confirmation-delete-input.component.ts | 38 + .../inputs-table/inputs-table.component.html | 51 +- .../inputs-table/inputs-table.component.less | 178 + .../inputs-table/inputs-table.component.ts | 22 +- .../ng2/components/loader/loader.component.html | 5 + .../ng2/components/loader/loader.component.less | 75 + .../app/ng2/components/loader/loader.component.ts | 92 + .../app/ng2/components/modal/modal.component.html | 18 + .../app/ng2/components/modal/modal.component.less | 115 + .../app/ng2/components/modal/modal.component.ts | 46 + .../derived-property.component.html | 24 - .../derived-property.component.less | 35 - .../derived-property/derived-property.component.ts | 46 - .../dynamic-property.component.html | 73 +- .../dynamic-property.component.less | 46 +- .../dynamic-property/dynamic-property.component.ts | 164 +- .../list-property/list-property.component.html | 33 - .../list-property/list-property.component.less | 3 - .../list-property/list-property.component.ts | 85 - .../map-property/map-property.component.html | 38 - .../map-property/map-property.component.ts | 121 - .../properties-table.component.html | 121 +- .../properties-table.component.less | 127 +- .../properties-table/properties-table.component.ts | 16 +- .../properties-value-inner-table.component.html | 41 - .../properties-value-inner-table.component.less | 71 - .../properties-value-inner-table.component.ts | 37 - .../properties-assignment.module.ts | 22 +- .../properties-assignment.page.component.html | 51 +- .../properties-assignment.page.component.less | 6 + .../properties-assignment.page.component.ts | 345 +- .../properties-assignment/properties.utils.ts | 168 +- catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts | 5 +- .../src/app/ng2/services/component-mode.service.ts | 29 + .../services/component-services/service.service.ts | 2 +- .../src/app/ng2/services/data-type.service.ts | 12 +- .../src/app/ng2/services/hierarchy-nav.service.ts | 63 + .../src/app/ng2/services/properties.service.ts | 199 +- .../src/app/ng2/shared/tabs/tabs.component.less | 3 +- .../src/app/ng2/utils/ng1-upgraded-provider.ts | 22 + .../app/services/components/component-service.ts | 9 +- catalog-ui/src/app/utils/component-factory.ts | 1 + catalog-ui/src/app/utils/constants.ts | 5 +- catalog-ui/src/app/utils/modals-handler.ts | 2 +- .../forms/attribute-form/attribute-form-view.html | 4 +- .../property-form-view-model.ts | 2 +- .../conformance-level-modal-view-model.ts | 29 + .../conformance-level-modal-view.html | 22 + .../conformance-level-modal.less | 3 + .../onboarding-modal/onboarding-modal-view.html | 12 +- .../conformance-level-modal-view-model.ts | 29 - .../conformance-level-modal-view.html | 22 - .../conformance-level-modal.less | 3 - .../tabs/composition/composition-view-model.ts | 4 + .../tabs/artifacts/artifacts-view-model.ts | 2 +- .../composition/tabs/artifacts/artifacts-view.html | 2 +- .../composition/tabs/details/details-view-model.ts | 5 +- .../properties-view-model.ts | 4 +- .../deployment-artifacts-view.html | 2 +- .../view-models/workspace/workspace-view-model.ts | 17 +- .../org/openecomp/sdc/be/config/Configuration.java | 9 + .../ComponentMetadataDataDefinition.java | 8 + .../elements/AttributeDataDefinition.java | 209 -- .../elements/ListCapabilityDataDefinition.java | 6 - .../be/datatypes/elements/ListDataDefinition.java | 18 +- .../elements/ListRequirementDataDefinition.java | 10 +- .../elements/MapAttributesDataDefinition.java | 45 - .../datatypes/elements/PropertyDataDefinition.java | 56 +- .../be/datatypes/enums/JsonPresentationFields.java | 33 +- .../be/datatypes/tosca/ToscaDataDefinition.java | 41 + .../dependency-reduced-pom.xml | 67 - .../sdc/generator/aai/AaiArtifactGenerator.java | 1 + .../generator/ArtifactGenerationServiceTest.java | 2 +- .../main/resources/globalTypes/openecomp/nodes.yml | 18 +- .../sdcrests/vsp/rest/VendorSoftwareProducts.java | 2 +- .../rest/services/VendorSoftwareProductsImpl.java | 280 +- .../impl/VendorLicenseManagerImpl.java | 27 +- .../VSPPackage.zip | Bin 33617 -> 0 bytes ...trationTemplateCandidateManagerFactoryImpl.java | 8 + .../OrchestrationTemplateCandidateManagerImpl.java | 166 +- .../impl/VendorSoftwareProductManagerImpl.java | 15 +- .../org/openecomp/sdc/common/errors/Messages.java | 2 +- .../openecomp-zusammen-api/pom.xml | 2 +- .../openecomp-zusammen-core/pom.xml | 8 +- .../openecomp-zusammen-plugin/pom.xml | 8 +- .../sdc/healing/healers/CompositionDataHealer.java | 4 +- .../artifact/ExternalArtifactEnricher.java | 6 +- .../external/artifact/ProcessArtifactEnricher.java | 5 +- .../tosca/AbstractSubstituteToscaEnricher.java | 1 + .../artifact/ProcessArtifactEnricherTest.java | 19 +- .../datatypes/heattotosca/TranslationContext.java | 27 + .../services/heattotosca/ConfigConstants.java | 3 + .../heattotosca/ConsolidationDataUtil.java | 27 +- .../heattotosca/UnifiedCompositionService.java | 240 +- .../FunctionTranslationGetAttrImpl.java | 2 +- .../main/resources/config-heatToToscaMapping.json | 2 +- .../resources/config-mandatory-unifiedModel.json | 11 + ...fiedCompositionNestedSingleComputeFullTest.java | 13 + .../OCS-fw2_service_instance1ServiceTemplate.yaml | 22 +- .../OCS-fw2_service_instance3ServiceTemplate.yaml | 22 +- .../OCS-fw3_service_instance4ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance1ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance2ServiceTemplate.yaml | 22 +- .../expectedoutputfiles/MainServiceTemplate.yaml | 76 +- .../OCS-fw2_service_instance1ServiceTemplate.yaml | 22 +- .../OCS-fw2_service_instance3ServiceTemplate.yaml | 22 +- .../OCS-fw3_service_instance4ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance1ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance2ServiceTemplate.yaml | 22 +- .../inputfiles/addOn.yml | 2 +- .../inputfiles/base.yml | 2 +- .../OCS-fw_service_instance_1ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance_2ServiceTemplate.yaml | 22 +- ....oam-fw_si_service_instanceServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance_1ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instance_2ServiceTemplate.yaml | 22 +- .../OCS-fw_service_instanceServiceTemplate.yaml | 22 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 174 +- .../out/MainServiceTemplate.yaml | 48 +- .../out/Nested_pd_server_0ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_1ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_2ServiceTemplate.yaml | 76 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 168 +- .../out/MainServiceTemplate.yaml | 64 +- .../out/Nested_pd_server_0ServiceTemplate.yaml | 69 +- .../out/Nested_pd_server_1ServiceTemplate.yaml | 69 +- .../out/Nested_pd_server_2ServiceTemplate.yaml | 69 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 174 +- .../out/MainServiceTemplate.yaml | 48 +- .../out/Nested_pd_server_0ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_1ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_2ServiceTemplate.yaml | 76 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 674 +++- .../out/MainServiceTemplate.yaml | 196 +- ...ested_1c1_scalling_instanceServiceTemplate.yaml | 141 +- ...sted_1c2_catalog_instance_0ServiceTemplate.yaml | 121 +- ...sted_1c2_catalog_instance_1ServiceTemplate.yaml | 119 +- .../out/Nested_a_single_1aServiceTemplate.yaml | 127 +- .../out/Nested_b_single_1b_0ServiceTemplate.yaml | 126 +- .../out/Nested_b_single_1b_1ServiceTemplate.yaml | 119 +- .../out/nested-pcm_v0.1ServiceTemplate.yaml | 150 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 632 +++- .../out/MainServiceTemplate.yaml | 182 +- ...ested_1c1_scalling_instanceServiceTemplate.yaml | 139 +- ...sted_1c2_catalog_instance_0ServiceTemplate.yaml | 119 +- ...sted_1c2_catalog_instance_1ServiceTemplate.yaml | 119 +- .../out/Nested_a_single_1aServiceTemplate.yaml | 127 +- .../out/Nested_b_single_1b_0ServiceTemplate.yaml | 130 +- .../out/Nested_b_single_1b_1ServiceTemplate.yaml | 119 +- .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 632 +++- .../out/MainServiceTemplate.yaml | 182 +- ...ested_1c1_scalling_instanceServiceTemplate.yaml | 139 +- ...sted_1c2_catalog_instance_0ServiceTemplate.yaml | 119 +- ...sted_1c2_catalog_instance_1ServiceTemplate.yaml | 119 +- .../out/Nested_a_single_1aServiceTemplate.yaml | 127 +- .../out/Nested_b_single_1b_0ServiceTemplate.yaml | 130 +- .../out/Nested_b_single_1b_1ServiceTemplate.yaml | 119 +- .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 1120 ++++++- .../out/MainServiceTemplate.yaml | 280 +- ...sted_1c11_scalling_instanceServiceTemplate.yaml | 76 +- ...sted_1c12_scalling_instanceServiceTemplate.yaml | 72 +- ...sted_1c2_catalog_instance_0ServiceTemplate.yaml | 121 +- ...sted_1c2_catalog_instance_1ServiceTemplate.yaml | 119 +- ...sted_1c2_catalog_instance_2ServiceTemplate.yaml | 119 +- ...sted_1c2_catalog_instance_3ServiceTemplate.yaml | 119 +- .../out/Nested_a_single_1aServiceTemplate.yaml | 127 +- .../out/Nested_a_single_2aServiceTemplate.yaml | 74 +- .../out/Nested_b_single_1b_0ServiceTemplate.yaml | 119 +- .../out/Nested_b_single_1b_1ServiceTemplate.yaml | 126 +- .../out/Nested_b_single_2b_0ServiceTemplate.yaml | 123 +- .../out/Nested_b_single_2b_1ServiceTemplate.yaml | 136 +- .../out/nested-pcm_v0.1ServiceTemplate.yaml | 150 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 120 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.2ServiceTemplate.yaml | 90 + .../out/Nested_jsaServiceTemplate.yaml | 171 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 188 +- .../out/nested-oam_v0.1ServiceTemplate.yaml | 138 +- .../out/nested-pcm_v0.1ServiceTemplate.yaml | 138 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 152 +- .../out/nested-oam_v0.1ServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 138 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 152 +- .../out/nested-oam_v0.1ServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 138 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../in/MANIFEST.json | 21 + .../in/hot-nimbus-pcm_v0.4.env | 14 + .../in/hot-nimbus-pcm_v0.4.yaml | 103 + .../in/nested-pcm_v0.1.yaml | 101 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 855 +++++ .../out/MainServiceTemplate.yaml | 243 ++ .../out/Nested_computeServiceTemplate.yaml | 203 ++ .../out/nested-pcm_v0.1ServiceTemplate.yaml | 470 +++ .../in/hot-nimbus-pcm_v0.4.yaml | 4 +- .../in/nested-pcm_v0.1.yaml | 8 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 328 +- .../out/MainServiceTemplate.yaml | 54 +- .../out/nested-pcm_v0.1ServiceTemplate.yaml | 516 +-- .../GlobalSubstitutionTypesServiceTemplate.yaml | 180 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.2ServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.3ServiceTemplate.yaml | 92 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 120 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.2ServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 +- .../out/MainServiceTemplate.yaml | 30 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 +- .../out/MainServiceTemplate.yaml | 30 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 +- .../out/MainServiceTemplate.yaml | 34 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 58 +- .../out/MainServiceTemplate.yaml | 24 +- .../out/Nested_pd_serverServiceTemplate.yaml | 76 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 66 +- .../out/MainServiceTemplate.yaml | 36 +- .../out/Nested_pd_serverServiceTemplate.yaml | 82 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 +- .../out/MainServiceTemplate.yaml | 30 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 64 +- .../out/MainServiceTemplate.yaml | 36 +- .../out/Nested_pd_serverServiceTemplate.yaml | 82 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 +- .../out/MainServiceTemplate.yaml | 30 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 106 +- .../out/MainServiceTemplate.yaml | 38 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../out/Nested_ps_serverServiceTemplate.yaml | 64 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 106 +- .../out/MainServiceTemplate.yaml | 38 +- .../out/Nested_pd_serverServiceTemplate.yaml | 78 +- .../out/Nested_ps_serverServiceTemplate.yaml | 64 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 58 +- .../out/MainServiceTemplate.yaml | 20 +- .../out/Nested_smpServiceTemplate.yaml | 74 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 102 +- .../out/MainServiceTemplate.yaml | 14 +- .../out/Nested_pd_serverServiceTemplate.yaml | 128 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 104 +- .../out/MainServiceTemplate.yaml | 10 +- .../out/Nested_pd_serverServiceTemplate.yaml | 136 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 98 +- .../out/MainServiceTemplate.yaml | 26 +- .../out/Nested_pd_serverServiceTemplate.yaml | 124 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 98 +- .../out/MainServiceTemplate.yaml | 22 +- .../out/Nested_pd_serverServiceTemplate.yaml | 132 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 152 +- .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../out/nested-pcm_v0.1ServiceTemplate.yaml | 138 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 1376 ++++++-- .../generalVf/out/MainServiceTemplate.yaml | 282 +- .../generalVf/out/Nested_FSB1ServiceTemplate.yaml | 181 +- .../generalVf/out/Nested_FSB2ServiceTemplate.yaml | 185 +- .../generalVf/out/Nested_GPB1ServiceTemplate.yaml | 144 +- .../generalVf/out/Nested_GPB2ServiceTemplate.yaml | 124 +- .../generalVf/out/Nested_NCB1ServiceTemplate.yaml | 134 +- .../generalVf/out/Nested_NCB2ServiceTemplate.yaml | 134 +- .../generalVf/out/Nested_VLC1ServiceTemplate.yaml | 361 +- .../generalVf/out/Nested_VLC2ServiceTemplate.yaml | 341 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 66 + .../out/Nested_pd_serverServiceTemplate.yaml | 99 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 66 + .../out/Nested_pd_serverServiceTemplate.yaml | 99 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 60 + .../out/Nested_pd_serverServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 196 +- .../out/MainServiceTemplate.yaml | 60 +- .../out/Nested_oam_serverServiceTemplate.yaml | 67 +- .../out/Nested_pd_serverServiceTemplate.yaml | 79 +- .../out/Nested_ps_serverServiceTemplate.yaml | 90 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 176 +- .../out/MainServiceTemplate.yaml | 46 +- .../out/Nested_oam_serverServiceTemplate.yaml | 63 +- .../out/Nested_pd_serverServiceTemplate.yaml | 69 +- .../out/Nested_ps_serverServiceTemplate.yaml | 88 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 172 +- .../out/MainServiceTemplate.yaml | 48 +- .../out/Nested_pd_server_0ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_1ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_2ServiceTemplate.yaml | 69 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 174 +- .../out/MainServiceTemplate.yaml | 40 +- .../out/Nested_pd_server_0ServiceTemplate.yaml | 69 +- .../out/Nested_pd_server_1ServiceTemplate.yaml | 76 +- .../out/Nested_pd_server_2ServiceTemplate.yaml | 90 + .../GlobalSubstitutionTypesServiceTemplate.yaml | 98 +- .../out/MainServiceTemplate.yaml | 28 +- .../out/Nested_pd_serverServiceTemplate.yaml | 69 +- .../out/Nested_ps_serverServiceTemplate.yaml | 55 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 98 +- .../twoSetsOfSingle/out/MainServiceTemplate.yaml | 24 +- .../out/Nested_pd_serverServiceTemplate.yaml | 69 +- .../out/Nested_ps_serverServiceTemplate.yaml | 55 +- .../expectedoutputfiles/MainServiceTemplate.yaml | 2 +- .../FEAdd_On_Module_QRouterTemplate.yaml | 8 +- .../inputfiles/FEBase_Module.yaml | 2 +- ...d_On_Module_QRouterTemplateServiceTemplate.yaml | 360 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 218 +- .../out/MainServiceTemplate.yaml | 176 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 212 +- .../out/SubstitutionServiceTemplate.yaml | 306 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 2 +- .../NoPorts/out/SubstitutionServiceTemplate.yaml | 2 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 160 +- .../WithIndex/out/SubstitutionServiceTemplate.yaml | 232 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 108 +- .../out/SubstitutionServiceTemplate.yaml | 154 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 160 +- .../out/SubstitutionServiceTemplate.yaml | 232 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 104 +- .../out/SubstitutionServiceTemplate.yaml | 152 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 158 +- .../out/SubstitutionServiceTemplate.yaml | 230 +- .../out/MainServiceTemplate.yaml | 14 +- .../out/MainServiceTemplate.yaml | 14 +- .../out/MainServiceTemplate.yaml | 18 +- .../noConsolidation/out/MainServiceTemplate.yaml | 6 +- .../consolidation/out/MainServiceTemplate.yaml | 18 +- .../noConsolidation/out/MainServiceTemplate.yaml | 18 +- .../consolidation/out/MainServiceTemplate.yaml | 18 +- .../noConsolidation/out/MainServiceTemplate.yaml | 8 +- .../consolidation/out/MainServiceTemplate.yaml | 18 +- .../noConsolidation/out/MainServiceTemplate.yaml | 14 +- .../consolidation/out/MainServiceTemplate.yaml | 18 +- .../noConsolidation/out/MainServiceTemplate.yaml | 14 +- .../nested_with_inner_vol/inputfiles/main.yml | 2 +- .../nested_with_inner_vol/inputfiles/nested.yml | 4 +- .../GlobalSubstitutionTypesServiceTemplate.yaml | 152 +- .../out/MainServiceTemplate.yaml | 4 +- .../out/nestedServiceTemplate.yaml | 262 +- .../impl/zusammen/FeatureGroupDaoZusammenImpl.java | 15 +- .../zusammen/LicenseAgreementDaoZusammenImpl.java | 9 +- .../sdc/vendorsoftwareproduct/dao/MibDao.java | 2 + .../dao/impl/zusammen/MibDaoZusammenImpl.java | 32 + .../OrchestrationTemplateDaoZusammenImpl.java | 6 +- .../dao/impl/zusammen/ProcessDaoZusammenImpl.java | 3 + .../impl/TxtInformationArtifactGeneratorImpl.java | 2 +- .../sdc/tosca/services/ToscaAnalyzerService.java | 4 + .../services/impl/ToscaAnalyzerServiceImpl.java | 4 +- openecomp-be/sonar-project.properties | 0 .../schemaTemplates/questionnaire/component.ftl | 1 - .../tools/migration/1702_to_1707_zusammen/pom.xml | 2 +- .../openecomp/core/migration/MigrationMain.java | 5 +- .../scss/components/_sequenceDiagram.scss | 17 +- .../resources/scss/modules/_workflows.scss | 16 - .../src/nfvo-components/input/validation/Form.jsx | 14 + .../sdc-app/onboarding/OnboardingActionHelper.js | 8 +- .../featureGroups/FeatureGroupEditorView.jsx | 14 +- .../LicenseAgreementEditorView.jsx | 24 +- .../attachments/SoftwareProductAttachments.js | 4 +- .../attachments/SoftwareProductAttachmentsView.jsx | 2 +- .../SoftwareProductComponentEditorReducer.js | 1 + .../SoftwareProductComponentsActionHelper.js | 10 +- .../dependencies/SoftwareProductDependencies.js | 2 +- pom.xml | 1 + sdc-os-chef/pom.xml | 4 +- .../cookbooks/sdc-catalog-be/attributes/default.rb | 4 +- .../cookbooks/sdc-catalog-be/files/default/user.py | 25 +- .../files/default/titan.properties | 6 - .../templates/default/create_dox_keyspace.sh.erb | 28 +- test-apis-ci/.gitignore | 4 + test-apis-ci/pom.xml | 381 +++ .../org/openecomp/sdc/ci/tests/api/AttSdcTest.java | 200 ++ .../sdc/ci/tests/api/ComponentBaseTest.java | 607 ++++ .../ci/tests/api/ComponentInstanceBaseTest.java | 764 +++++ .../openecomp/sdc/ci/tests/api/ExtentManager.java | 72 + .../sdc/ci/tests/api/ExtentTestManager.java | 56 + .../java/org/openecomp/sdc/ci/tests/api/Urls.java | 368 ++ .../org/openecomp/sdc/ci/tests/config/Config.java | 696 ++++ .../sdc/ci/tests/config/InvokedMethodListener.java | 63 + .../ci/tests/datatypes/ArtifactAssetStructure.java | 135 + .../sdc/ci/tests/datatypes/ArtifactReqDetails.java | 243 ++ .../sdc/ci/tests/datatypes/AssetStructure.java | 122 + .../datatypes/ComponentInstanceReqDetails.java | 121 + .../ci/tests/datatypes/ComponentReqDetails.java | 272 ++ .../sdc/ci/tests/datatypes/CsarArtifacts.java | 59 + .../tests/datatypes/GroupHeatMetaDefinition.java | 86 + .../datatypes/HeatMetaFirstLevelDefinition.java | 76 + .../sdc/ci/tests/datatypes/ImportReqDetails.java | 335 ++ .../sdc/ci/tests/datatypes/ProductReqDetails.java | 88 + .../datatypes/PropertyHeatMetaDefinition.java | 63 + .../sdc/ci/tests/datatypes/PropertyReqDetails.java | 145 + .../ci/tests/datatypes/ResourceAssetStructure.java | 76 + .../datatypes/ResourceDetailedAssetStructure.java | 71 + .../datatypes/ResourceExternalReqDetails.java | 105 + .../datatypes/ResourceInstanceAssetStructure.java | 116 + .../sdc/ci/tests/datatypes/ResourceReqDetails.java | 220 ++ .../ci/tests/datatypes/ResourceRespJavaObject.java | 369 ++ .../ci/tests/datatypes/ServiceAssetStructure.java | 49 + .../datatypes/ServiceDetailedAssetStructure.java | 78 + .../tests/datatypes/ServiceDistributionStatus.java | 80 + .../sdc/ci/tests/datatypes/ServiceReqDetails.java | 91 + .../ci/tests/datatypes/ServiceRespJavaObject.java | 268 ++ .../ci/tests/datatypes/TypeHeatMetaDefinition.java | 57 + .../ci/tests/datatypes/enums/ArtifactTypeEnum.java | 77 + .../sdc/ci/tests/datatypes/enums/AssocType.java | 39 + .../sdc/ci/tests/datatypes/enums/AuditEnum.java | 39 + .../tests/datatypes/enums/AuditJsonKeysEnum.java | 40 + .../ci/tests/datatypes/enums/ComponentType.java | 37 + .../enums/DistributionNotificationStatusEnum.java | 52 + .../sdc/ci/tests/datatypes/enums/ErrorInfo.java | 93 + .../datatypes/enums/EsIndexTypeIdToDelete.java | 64 + .../tests/datatypes/enums/ExceptionEnumType.java | 36 + .../tests/datatypes/enums/ImportTestTypesEnum.java | 95 + .../tests/datatypes/enums/LifeCycleStatesEnum.java | 77 + .../enums/MandatoryResourceArtifactTypeEnum.java | 49 + .../enums/MandatoryServiceArtifactTypeEnum.java | 66 + .../tests/datatypes/enums/NormativeTypesEnum.java | 45 + .../ci/tests/datatypes/enums/OriginTypeEnum.java | 74 + .../ci/tests/datatypes/enums/PropertyTypeEnum.java | 107 + .../datatypes/enums/ResourceCategoryEnum.java | 57 + .../ci/tests/datatypes/enums/RespJsonKeysEnum.java | 40 + .../tests/datatypes/enums/SearchCriteriaEnum.java | 38 + .../datatypes/enums/ServiceApiArtifactEnum.java | 35 + .../datatypes/enums/ServiceCategoriesEnum.java | 37 + .../ci/tests/datatypes/enums/ToscaKeysEnum.java | 46 + .../sdc/ci/tests/datatypes/enums/UserRoleEnum.java | 77 + .../datatypes/expected/ExpectedArtifactAudit.java | 166 + .../expected/ExpectedAuthenticationAudit.java | 90 + .../datatypes/expected/ExpectedCategoryAudit.java | 151 + .../expected/ExpectedDistDownloadAudit.java | 79 + .../expected/ExpectedEcomConsumerAudit.java | 88 + .../datatypes/expected/ExpectedExternalAudit.java | 179 + .../expected/ExpectedGetUserListAudit.java | 88 + .../datatypes/expected/ExpectedGroupingAudit.java | 121 + .../datatypes/expected/ExpectedProductAudit.java | 142 + .../expected/ExpectedResourceAuditJavaObject.java | 311 ++ .../datatypes/expected/ExpectedUserCRUDAudit.java | 98 + .../sdc/ci/tests/datatypes/http/HeaderData.java | 114 + .../sdc/ci/tests/datatypes/http/HeaderValue.java | 38 + .../ci/tests/datatypes/http/HttpHeaderEnum.java | 58 + .../sdc/ci/tests/datatypes/http/HttpRequest.java | 889 +++++ .../sdc/ci/tests/datatypes/http/MustHeaders.java | 53 + .../sdc/ci/tests/datatypes/http/RestResponse.java | 84 + .../execute/TODO/ImportCapabilityTypeCITest.java | 135 + .../execute/artifacts/ArtifactServletTest.java | 658 ++++ .../sdc/ci/tests/execute/artifacts/CrudArt.java | 1799 ++++++++++ .../execute/artifacts/DownloadComponentArt.java | 665 ++++ .../tests/execute/artifacts/HeatEnvArtifact.java | 192 ++ .../execute/artifacts/PlaceHolderValidations.java | 704 ++++ .../execute/artifacts/ValidateArtResponse.java | 632 ++++ .../artifacts/ValidateHeatArtFieldsTypes.java | 177 + .../attribute/ComponentInstanceAttributeTest.java | 94 + .../tests/execute/category/CatalogDataApiTest.java | 236 ++ .../tests/execute/category/CategoriesBaseTest.java | 49 + .../ci/tests/execute/category/CategoriesTests.java | 2303 +++++++++++++ .../ci/tests/execute/category/ElementsApiTest.java | 148 + .../ci/tests/execute/category/GroupingTest.java | 2007 +++++++++++ .../tests/execute/category/SubCategoriesTest.java | 1908 +++++++++++ .../sdc/ci/tests/execute/devCI/AndreyTest.java | 104 + .../ci/tests/execute/devCI/ArtifactFromCsar.java | 301 ++ .../ci/tests/execute/devCI/ImportCsarUpdate.java | 362 ++ .../execute/devCI/ImportCsarValidateArtifacts.java | 108 + .../ci/tests/execute/devCI/ToscaGroupInsideVF.java | 580 ++++ .../sdc/ci/tests/execute/devCI/test1.java | 96 + .../execute/distribution/AuthanticationTests.java | 186 ++ .../DistributionDownloadArtifactTest.java | 537 +++ .../execute/externalapi/DownloadArtifactsTest.java | 385 +++ .../general/BasicHttpAuthenticationTest.java | 442 +++ .../sdc/ci/tests/execute/general/FeProxyTest.java | 53 + .../general/ManageEcompConsumerCredentials.java | 1420 ++++++++ .../sdc/ci/tests/execute/general/UuidTest.java | 104 + .../ci/tests/execute/imports/CsarUtilsTest.java | 460 +++ .../ci/tests/execute/imports/ExportToscaTest.java | 458 +++ .../execute/imports/ImportCsarResourceTest.java | 1751 ++++++++++ .../imports/ImportGenericResourceCITest.java | 600 ++++ .../execute/imports/ImportNewResourceCITest.java | 1529 +++++++++ .../ImportToscaCapabilitiesWithProperties.java | 416 +++ .../execute/imports/ImportToscaResourceTest.java | 2896 ++++++++++++++++ .../imports/ImportUpdateResourseCsarTest.java | 283 ++ .../ci/tests/execute/inputs/InputsApiTests.java | 225 ++ .../ci/tests/execute/lifecycle/LCSbaseTest.java | 274 ++ .../product/ChangeServiceInstanceVersionTest.java | 1478 ++++++++ .../ci/tests/execute/product/ProductBaseTest.java | 200 ++ .../tests/execute/product/ProductCheckinTest.java | 199 ++ .../tests/execute/product/ProductCheckoutTest.java | 147 + .../product/ProductComponentInstanceCRUDTest.java | 1175 +++++++ .../product/ProductCreateWithValidationsTest.java | 1718 ++++++++++ .../ci/tests/execute/product/ProductCrudTest.java | 2551 ++++++++++++++ .../execute/product/ProductGetFollowedTest.java | 164 + .../execute/product/ProductLifecycleTest.java | 55 + .../ci/tests/execute/product/ProductTestBase.java | 148 + .../product/ProductToscaYamlGenerationTest.java | 83 + .../execute/product/ProductUndoCheckoutTest.java | 216 ++ .../property/AdditionalInformationServletTest.java | 2021 +++++++++++ .../property/ComponentInstancePropertyTest.java | 1263 +++++++ .../tests/execute/property/ComponentProperty.java | 1796 ++++++++++ .../tests/execute/property/PropertyApisTest.java | 384 +++ .../tests/execute/resource/CheckGetResource.java | 53 + .../resource/ComponentRelationshipInVfTest.java | 1408 ++++++++ .../execute/resource/CreateResourceApiTest.java | 2222 ++++++++++++ .../execute/resource/GetAllResourceVersions.java | 582 ++++ .../resource/GetResourceNotAbstractApiTest.java | 328 ++ .../ci/tests/execute/resource/ResourceApiTest.java | 372 +++ .../tests/execute/resource/SampleDataProvider.java | 41 + .../execute/resource/SimultaneousApiTest.java | 124 + .../resource/UpdateResourceMetadataTest.java | 2650 +++++++++++++++ .../resource/VFResourceInstanceNameCRUD.java | 481 +++ .../execute/resource/ValidateExtendedVfData.java | 319 ++ .../resource/VfComponentInstanceCRUDTest.java | 1792 ++++++++++ .../ChangeServiceDistributionStatusApiTest.java | 1012 ++++++ .../service/CreateServiceMetadataApiTest.java | 1304 ++++++++ .../execute/service/GetAllServiceVersions.java | 351 ++ .../execute/service/GetComponentAuditApiTest.java | 371 ++ .../service/GetServiceLatestVersionTest.java | 685 ++++ .../execute/service/ReqCapOccurrencesTest.java | 1191 +++++++ .../service/ServiceComponentInstanceCRUDTest.java | 1627 +++++++++ .../execute/service/UpdateServiceMetadataTest.java | 2158 ++++++++++++ .../execute/user/ActivateDeActivateDeleteUser.java | 756 +++++ .../ci/tests/execute/user/CreateUserApiTest.java | 1693 ++++++++++ .../execute/user/GovernorWorkspaceApiTest.java | 319 ++ .../distributionClient/ClientConfiguration.java | 141 + .../preRequisites/ComplexResourceBaseTest.java | 177 + .../preRequisites/DownloadArtifactBaseTest.java | 125 + .../preRequisites/SimpleOneRsrcOneServiceTest.java | 96 + .../sdc/ci/tests/rules/MyTestWatcher.java | 82 + .../org/openecomp/sdc/ci/tests/run/StartTest.java | 279 ++ .../sdc/ci/tests/run/StartTest2backup.java | 408 +++ .../org/openecomp/sdc/ci/tests/sanity/CrudE2E.java | 287 ++ .../ci/tests/sanity/MultipleResourceUpdate.java | 131 + .../tosca/datatypes/ParametersDefinition.java | 105 + .../ToscaCapabilitiesNodeTemplatesDefinition.java | 25 + .../ci/tests/tosca/datatypes/ToscaDefinition.java | 120 + .../datatypes/ToscaGroupsMetadataDefinition.java | 84 + .../ToscaGroupsTopologyTemplateDefinition.java | 126 + .../tosca/datatypes/ToscaImportsDefinition.java | 81 + .../ToscaInputsTopologyTemplateDefinition.java | 45 + ...scaNodeTemplatesTopologyTemplateDefinition.java | 174 + .../tosca/datatypes/ToscaNodeTypesDefinition.java | 141 + .../ToscaOutputsTopologyTemplateDefinition.java | 49 + .../ToscaPoliciesTopologyTemplateDefinition.java | 67 + ...ionshipTemplatesTopologyTemplateDefinition.java | 79 + .../ToscaRequirementsNodeTemplatesDefinition.java | 72 + .../ToscaSubstitutionMappingsDefinition.java | 71 + .../datatypes/ToscaTopologyTemplateDefinition.java | 135 + .../ToscaTopologyTemplateDefinition2.java | 78 + .../ci/tests/users/AddUserAuditMessageInfo.java | 113 + .../sdc/ci/tests/users/UserAuditJavaObject.java | 133 + .../sdc/ci/tests/users/UserHeaderData.java | 59 + .../ci/tests/users/UserResponseMessageEnum.java | 39 + .../sdc/ci/tests/users/WebSealUserDetails.java | 74 + .../sdc/ci/tests/utils/ArtifactUtils.java | 43 + .../sdc/ci/tests/utils/CsarParserUtils.java | 174 + .../org/openecomp/sdc/ci/tests/utils/DbUtils.java | 293 ++ .../org/openecomp/sdc/ci/tests/utils/Decoder.java | 62 + .../sdc/ci/tests/utils/DistributionUtils.java | 144 + .../org/openecomp/sdc/ci/tests/utils/ReqCap.java | 630 ++++ .../sdc/ci/tests/utils/ToscaParserUtils.java | 361 ++ .../org/openecomp/sdc/ci/tests/utils/Utils.java | 689 ++++ .../ci/tests/utils/cassandra/CassandraUtils.java | 220 ++ .../ci/tests/utils/cassandra/CassandraUtils2.java | 166 + .../tests/utils/general/AtomicOperationUtils.java | 732 ++++ .../sdc/ci/tests/utils/general/Convertor.java | 344 ++ .../sdc/ci/tests/utils/general/ElementFactory.java | 997 ++++++ .../sdc/ci/tests/utils/general/FileUtils.java | 137 + .../sdc/ci/tests/utils/general/ImportUtils.java | 63 + .../sdc/ci/tests/utils/rest/ArtifactRestUtils.java | 934 ++++++ .../sdc/ci/tests/utils/rest/AssetRestUtils.java | 626 ++++ .../sdc/ci/tests/utils/rest/AutomationUtils.java | 110 + .../sdc/ci/tests/utils/rest/BaseRestUtils.java | 265 ++ .../sdc/ci/tests/utils/rest/CatalogRestUtils.java | 93 + .../sdc/ci/tests/utils/rest/CategoryRestUtils.java | 309 ++ .../utils/rest/ComponentInstanceRestUtils.java | 276 ++ .../ci/tests/utils/rest/ComponentRestUtils.java | 62 + .../sdc/ci/tests/utils/rest/ConsumerRestUtils.java | 245 ++ .../ci/tests/utils/rest/EcompUserRestUtils.java | 253 ++ .../sdc/ci/tests/utils/rest/GroupRestUtils.java | 61 + .../sdc/ci/tests/utils/rest/ImportRestUtils.java | 408 +++ .../sdc/ci/tests/utils/rest/InputsRestUtils.java | 122 + .../ci/tests/utils/rest/LifecycleRestUtils.java | 451 +++ .../sdc/ci/tests/utils/rest/ProductRestUtils.java | 196 ++ .../sdc/ci/tests/utils/rest/PropertyRestUtils.java | 310 ++ .../sdc/ci/tests/utils/rest/ResourceRestUtils.java | 679 ++++ .../utils/rest/ResourceRestUtilsExternalAPI.java | 64 + .../sdc/ci/tests/utils/rest/ResponseParser.java | 605 ++++ .../sdc/ci/tests/utils/rest/ServiceRestUtils.java | 296 ++ .../sdc/ci/tests/utils/rest/UserRestUtils.java | 299 ++ .../utils/validation/ArtifactValidationUtils.java | 226 ++ .../utils/validation/AuditValidationUtils.java | 1418 ++++++++ .../utils/validation/BaseValidationUtils.java | 117 + .../utils/validation/CategoryValidationUtils.java | 125 + .../utils/validation/CsarValidationUtils.java | 488 +++ .../validation/DistributionValidationUtils.java | 86 + .../utils/validation/ErrorValidationUtils.java | 120 + .../utils/validation/ProductValidationUtils.java | 239 ++ .../utils/validation/ResourceValidationUtils.java | 358 ++ .../utils/validation/ServiceValidationUtils.java | 130 + .../utils/validation/UserValidationUtils.java | 279 ++ .../sdc/ci/tests/webSealAccess/NeoJavaObject.java | 111 + .../openecomp/sdc/externalApis/AssetLifeCycle.java | 1146 +++++++ .../sdc/externalApis/CRUDExternalAPI.java | 3528 ++++++++++++++++++++ .../sdc/externalApis/DeploymentValiditaion.java | 428 +++ .../sdc/externalApis/GetAssetServlet.java | 343 ++ .../openecomp/sdc/externalApis/GetCSARofVF.java | 262 ++ .../sdc/externalApis/GetFilteredAssetServlet.java | 712 ++++ .../GetSpecificAssetMetadataServlet.java | 447 +++ .../SearchFilterCategoryExternalAPI.java | 329 ++ .../org/openecomp/sdc/externalApis/UserAPIs.java | 556 +++ .../sdc/externalApis/VFCMTExternalAPI.java | 396 +++ .../main/java/org/openecomp/sdc/post/Install.java | 70 + .../main/resources/ci/conf/attsdc-packages.yaml | 12 + .../src/main/resources/ci/conf/attsdc.yaml | 93 + .../src/main/resources/ci/conf/extent-config.xml | 51 + .../src/main/resources/ci/conf/log4j.properties | 34 + test-apis-ci/src/main/resources/ci/conf/log4j.xml | 32 + .../src/main/resources/ci/conf/testngLifeCycle.xml | 27 + .../src/main/resources/ci/conf/titan.properties | 8 + test-apis-ci/src/main/resources/ci/conf/truststore | Bin 0 -> 971 bytes .../resources/ci/scripts/addUsersFromList_new.sh | 75 + .../src/main/resources/ci/scripts/copyToStorage.sh | 66 + .../src/main/resources/ci/scripts/sendMail.sh | 46 + .../src/main/resources/ci/scripts/startTest.sh | 153 + .../src/main/resources/ci/scripts/userList.txt | 1 + .../main/resources/ci/testSuites/CRUDArtifacts.xml | 40 + .../resources/ci/testSuites/SearchExternalAPI.xml | 23 + .../src/main/resources/ci/testSuites/artifacts.xml | 19 + .../src/main/resources/ci/testSuites/category.xml | 11 + .../src/main/resources/ci/testSuites/ciFull.xml | 221 ++ .../main/resources/ci/testSuites/externalAPIs.xml | 31 + .../src/main/resources/ci/testSuites/general.xml | 11 + .../src/main/resources/ci/testSuites/imports.xml | 12 + .../src/main/resources/ci/testSuites/product.xml | 14 + .../main/resources/ci/testSuites/productAPIs.xml | 20 + .../src/main/resources/ci/testSuites/property.xml | 11 + .../src/main/resources/ci/testSuites/resource.xml | 360 ++ .../src/main/resources/ci/testSuites/sanity.xml | 394 +++ .../src/main/resources/ci/testSuites/service.xml | 15 + .../resources/ci/testSuites/testngLifeCycle.xml | 27 + .../src/main/resources/ci/testSuites/user.xml | 18 + test-apis-ci/src/main/resources/log4j.properties | 34 + test-apis-ci/src/main/resources/log4j.xml | 32 + test-apis-ci/src/main/resources/logback.xml | 25 + .../resources/CI/ecomp-error-configuration.yaml | 383 +++ .../src/test/resources/CI/error-configuration.yaml | 1778 ++++++++++ .../CI/importTypesTest/categoryTypesTest.yml | 23 + .../CI/importTypesTest/categoryTypesTest.zip | Bin 0 -> 333 bytes .../importTypesTest/myHeatStack1/myHeatStack1.yml | 13 + .../importTypesTest/myHeatStack1/myHeatStack1.zip | Bin 0 -> 400 bytes .../importTypesTest/myHeatStack2/myHeatStack2.yml | 14 + .../importTypesTest/myHeatStack2/myHeatStack2.zip | Bin 0 -> 423 bytes .../src/test/resources/CI/other/mapping.json | 182 + .../addYangXmlArtifactToResource.xml | 32 + .../HeatDeploymentArtifacts/asc_heat 0 2.yaml | 787 +++++ .../tests/HeatDeploymentArtifacts/asc_heat 0 2.zip | Bin 0 -> 2420 bytes .../HeatDeploymentArtifacts/asc_heat_net 0 2.yaml | 787 +++++ .../tests/HeatDeploymentArtifacts/heatEnvfile.env | 787 +++++ .../HeatDeploymentArtifacts/heatInvalidFormat.yaml | 9 + .../tests/HeatDeploymentArtifacts/heat_mini.yaml | 13 + .../tests/HeatDeploymentArtifacts/invalidJson.json | 11 + .../HeatDeploymentArtifacts/invalidYamlFormat.yaml | 787 +++++ .../HeatDeploymentArtifacts/invalidYangXml.xml | 35 + .../HeatDeploymentArtifacts/jsonArtifact.json | 22 + .../CI/tests/HeatDeploymentArtifacts/other.txt | 3 + .../bluePrintSampleArtifact.xml | 3 + .../docSampleArtifact.docx | Bin 0 -> 11307 bytes .../emfSampleArtifact.emf | 2 + .../emfSampleArtifact.xml | 3 + .../eventSampleArtifact.xml | 3 + .../jsonSampleArtifact.json | 3 + .../toscaSampleArtifact.yml | 5 + .../asc_heat 0 2.yaml | 787 +++++ .../org.openstack.Rally.zip | Bin 0 -> 11590 bytes .../images/mysql.png | Bin 0 -> 63119 bytes .../getResourceArtifactFileContentTest/mysql.yml | 85 + .../scripts/install_mysql.sh | 28 + .../scripts/start_mysql.sh | 105 + .../getResourceArtifactListNoContentTest/mysql.yml | 85 + .../getResourceArtifactListTest/images/mysql.png | Bin 0 -> 63119 bytes .../CI/tests/getResourceArtifactListTest/mysql.yml | 85 + .../scripts/install_mysql.sh | 28 + .../scripts/start_mysql.sh | 105 + .../mysql.yml | 85 + .../images/mysql.png | Bin 0 -> 63119 bytes .../getResourceArtifactMetadataTest/mysql.yml | 85 + .../scripts/install_mysql.sh | 28 + .../scripts/start_mysql.sh | 105 + .../mysql.yml | 85 + .../resource1/images/mysql.png | Bin 0 -> 63119 bytes .../resource1/mysql.yml | 85 + .../resource1/scripts/install_mysql.sh | 28 + .../resource1/scripts/start_mysql.sh | 105 + .../resource2/images/mysql.png | Bin 0 -> 63119 bytes .../resource2/mysql.yml | 85 + .../resource2/scripts/install_mysql2.sh | 28 + .../resource2/scripts/start_mysql2.sh | 105 + .../topology.txt | 1 + .../topologyTemplate.txt | 2 + .../resource1/images/mysql.png | Bin 0 -> 63119 bytes .../resource1/mysql.yml | 85 + .../resource2/images/mysql.png | Bin 0 -> 63119 bytes .../resource2/mysql.yml | 85 + .../topology.txt | 1 + .../topologyTemplate.txt | 2 + .../resource1/images/mysql.png | Bin 0 -> 63119 bytes .../getServiceArtifactListTest/resource1/mysql.yml | 85 + .../resource1/scripts/install_mysql.sh | 28 + .../resource1/scripts/start_mysql.sh | 105 + .../resource2/images/mysql.png | Bin 0 -> 63119 bytes .../getServiceArtifactListTest/resource2/mysql.yml | 85 + .../resource2/scripts/install_mysql2.sh | 28 + .../resource2/scripts/start_mysql2.sh | 105 + .../tests/getServiceArtifactListTest/topology.txt | 1 + .../topologyTemplate.txt | 2 + .../Service1/resource1/images/mysql.png | Bin 0 -> 63119 bytes .../Service1/resource1/mysql.yml | 85 + .../Service1/resource1/scripts/install_mysql.sh | 28 + .../Service1/resource1/scripts/start_mysql.sh | 105 + .../Service1/resource2/images/mysql.png | Bin 0 -> 63119 bytes .../Service1/resource2/mysql.yml | 85 + .../Service1/resource2/scripts/install_mysql2.sh | 28 + .../Service1/resource2/scripts/start_mysql2.sh | 105 + .../tests/getServiceListTest/Service1/topology.txt | 1 + .../Service1/topologyTemplate.txt | 2 + .../Service2/resource1/images/mysql.png | Bin 0 -> 63119 bytes .../Service2/resource1/mysql.yml | 85 + .../Service2/resource2/images/mysql.png | Bin 0 -> 63119 bytes .../Service2/resource2/mysql.yml | 85 + .../tests/getServiceListTest/Service2/topology.txt | 1 + .../Service2/topologyTemplate.txt | 2 + .../heatWithParamsMissingDefault.yaml | 603 ++++ .../heatWithParamsMissingDesc.yaml | 603 ++++ .../heatWithParamsMissingType.yaml | 603 ++++ .../heatWithValidParams.yaml | 787 +++++ .../resources/CI/tests/heatEnv/artifact_1.yaml | 144 + .../resources/CI/tests/heatEnv/artifact_2.yaml | 469 +++ .../src/test/resources/CI/tests/heatEnv/yuli.yaml | 144 + .../BindingAsset.yml | 14 + .../CPHasNoReqCap.yml | 9 + .../CPHasNoReqCap_DerivedFromMyCompute1.yml | 9 + .../CPWithAttributes.yml | 56 + .../CaseInsensitiveCapTest_1.yml | 34 + .../CaseInsensitiveCapTest_2.yml | 34 + .../CaseInsensitiveReqTest_1.yml | 34 + .../CaseInsensitiveReqTest_2.yml | 34 + .../DerivedFromCPWithOwnReq.yml | 14 + .../DerivedFromWebApplication_HasNoReqType.yml | 27 + .../DifferentCapFromRoot.yml | 26 + .../DifferentReqAndCap.yml | 34 + .../DifferentReqCapFromCompute1.yml | 22 + .../DifferentReqCapFromCompute2.yml | 25 + .../DifferentReqFromCompute.yml | 32 + .../FatherHasNoReqCap.yml | 9 + .../ListPropertyFalure01.yml | 17 + .../ListPropertyFalure02.yml | 17 + .../ListPropertyFalure03.yml | 17 + .../ListPropertyFalure04.yml | 17 + .../ListPropertyFalure05.yml | 17 + .../ListPropertyFalure06.yml | 17 + .../ListPropertyFalure07.yml | 17 + .../ListPropertyFalure08.yml | 17 + .../ListPropertyFalure09.yml | 17 + .../ListPropertyFalure10.yml | 17 + .../ListPropertyFalure11.yml | 17 + .../ListPropertyFalure12.yml | 17 + .../ListPropertyFalure13.yml | 17 + .../ListPropertyFalure14.yml | 18 + .../ListPropertyFalure15.yml | 19 + .../ListPropertyFalure16.yml | 17 + .../MapPropertyFalure01.yml | 17 + .../MapPropertyFalure02.yml | 17 + .../MapPropertyFalure03.yml | 17 + .../MapPropertyFalure04.yml | 17 + .../MapPropertyFalure05.yml | 17 + .../MapPropertyFalure06.yml | 17 + .../MapPropertyFalure07.yml | 17 + .../MapPropertyFalure08.yml | 17 + .../MapPropertyFalure09.yml | 17 + .../MapPropertyFalure10.yml | 17 + .../MapPropertyFalure11.yml | 17 + .../MapPropertyFalure12.yml | 17 + .../MapPropertyFalure13.yml | 17 + .../MapPropertyFalure14.yml | 18 + .../MapPropertyFalure15.yml | 19 + .../MapPropertyFalure16.yml | 17 + .../MyFatherCompute_NoReqCap.yml | 17 + .../SameCapAsCompute.yml | 26 + .../SameReqAsCompute.yml | 23 + .../SameReqAsCompute_DerivedFromMyCompute1.yml | 23 + .../computeCap11.yml | 35 + .../computeCap1UNBOUNDED.yml | 35 + .../derivedFromMyCompute.yml | 35 + .../derivedFromWebAppDerivedReqCap.yml | 15 + .../importAttributeSuccessFlow.yml | 53 + .../importCapabilityNameExistsOnParent.yml | 35 + .../importDuplicateCapability.yml | 42 + .../importDuplicateRequirements.yml | 40 + .../importListPropertyBadDefault.yml | 17 + .../importListPropertyGoodDefault.yml | 17 + .../importListPropertySuccessFlow.yml | 198 ++ .../importMapPropertySuccessFlow.yml | 452 +++ .../importRequirementNameExistsOnParent.yml | 34 + ...entNameExistsOnParent_DerivedFromMyCompute1.yml | 34 + .../missingCapInCapDefinition.yml | 37 + .../missingCapInReqDefinition.yml | 25 + .../myChildCompute_NoReqCap.yml | 17 + .../myChildWebApp_DerivedFromContainer.yml | 15 + .../importToscaResourceByCreateUrl/myCompute.yml | 35 + .../myComputeDerivedFromNotExists.yml | 35 + .../myComputeIncorrectDefenitionVersionValue.yml | 35 + .../myComputeIncorrectNameSpaceFormat.yml | 35 + .../myComputeNoDefenitionVersion.yml | 34 + .../myComputeOccurencySuccess.yml | 77 + .../myComputeParssingFalure.yml | 35 + .../myComputeReqNameExistsOnDerived.yml | 34 + .../importToscaResourceByCreateUrl/myComputeVF.yml | 35 + .../myComputeWithNodeTypesTwice.yml | 42 + .../myComputeWithTopologyTemplate.yml | 44 + .../myFatherWebApp_derviedFromDocker.yml | 16 + .../importToscaResourceByCreateUrl/myLinkVL.yml | 35 + .../importToscaResourceByCreateUrl/myPortCP.yml | 35 + .../importToscaResourceByCreateUrl/noContent.yml | 0 .../occurencyFalure01.yml | 35 + .../occurencyFalure02.yml | 35 + .../occurencyFalure03.yml | 35 + .../occurencyFalure04.yml | 35 + .../occurencyFalure05.yml | 35 + .../occurencyFalure06.yml | 35 + .../occurencyFalure07.yml | 35 + .../occurencyFalure08.yml | 35 + .../occurencyFalure09.yml | 35 + .../occurencyFalure10.yml | 35 + .../occurencyFalure11.yml | 35 + .../occurencyFalure31.yml | 35 + .../occurencyFalure32.yml | 35 + .../occurencyFalure33.yml | 35 + .../occurencyFalure34.yml | 35 + .../occurencyFalure35.yml | 35 + .../occurencyFalure36.yml | 35 + .../occurencyFalure37.yml | 35 + .../occurencyFalure38.yml | 35 + .../occurencyFalure39.yml | 35 + .../occurencyFalure40.yml | 35 + .../occurencyFalure41.yml | 35 + .../softwareComponentReq11.yml | 17 + .../softwareComponentReq12.yml | 17 + .../resources/CI/tests/testCsarAPI/topology.txt | 1 + .../CI/tests/testCsarAPI/topologyTemplate.txt | 1 + .../tests/tmp/positive_artifact_bool10_false.yaml | 140 + .../tests/tmp/positive_artifact_bool11_false.yaml | 140 + .../tests/tmp/positive_artifact_bool12_false.yaml | 140 + .../CI/tests/tmp/positive_artifact_bool1_true.yaml | 140 + .../CI/tests/tmp/positive_artifact_bool2_true.yaml | 140 + .../CI/tests/tmp/positive_artifact_bool3_true.yaml | 140 + .../CI/tests/tmp/positive_artifact_bool4_true.yaml | 140 + .../CI/tests/tmp/positive_artifact_bool5_true.yaml | 140 + .../CI/tests/tmp/positive_artifact_bool6_true.yaml | 140 + .../tests/tmp/positive_artifact_bool7_false.yaml | 140 + .../tests/tmp/positive_artifact_bool8_false.yaml | 140 + .../tests/tmp/positive_artifact_bool9_false.yaml | 140 + .../CI/tests/tmp/positive_artifact_number1.yaml | 140 + .../CI/tests/tmp/positive_artifact_number2.yaml | 140 + .../CI/tests/uploadComponent/images/mysql.png | Bin 0 -> 63119 bytes .../resources/CI/tests/uploadComponent/mysql.yml | 85 + .../tests/uploadComponent/scripts/install_mysql.sh | 28 + .../tests/uploadComponent/scripts/start_mysql.sh | 105 + .../yamlFieldsValidation/artifact_unsupported.yaml | 140 + .../negative_artifact_bool1.yaml | 140 + .../negative_artifact_bool2.yaml | 140 + .../negative_artifact_number1.yaml | 140 + .../negative_artifact_number2.yaml | 140 + .../negative_artifact_string1.yaml | 140 + test-apis-ci/src/test/resources/config.json | 12 + test-apis-ci/src/test/resources/logback-test.xml | 13 + test-apis-ci/testng.xml | 15 + test-apis-ci/testngLifeCycle.xml | 27 + test-apis-ci/tmpCSAR | Bin 0 -> 1844 bytes ui-ci-dev/.gitignore | 2 + ui-ci-dev/pom.xml | 287 ++ .../sdc/uici/scripts/CreateVfsFromOnboarding.java | 67 + .../sdc/uici/tests/datatypes/CanvasElement.java | 33 + .../sdc/uici/tests/datatypes/CanvasManager.java | 206 ++ .../sdc/uici/tests/datatypes/CleanTypeEnum.java | 28 + .../datatypes/CreateAndImportButtonsEnum.java | 7 + .../tests/datatypes/CreateAndUpdateStepsEnum.java | 25 + .../sdc/uici/tests/datatypes/DataTestIdEnum.java | 477 +++ .../sdc/uici/tests/datatypes/MenuOptionsEnum.java | 17 + .../sdc/uici/tests/datatypes/UserCredentials.java | 29 + .../sdc/uici/tests/execute/base/SetupCDTest.java | 419 +++ .../tests/execute/generalTests/GeneralTests.java | 26 + .../tests/execute/service/ServiceBasicTests.java | 147 + .../tests/execute/service/ServiceInputsTests.java | 124 + .../sdc/uici/tests/execute/vf/VfBasicTests.java | 333 ++ .../sdc/uici/tests/execute/vf/VfCanvasTests.java | 80 + .../uici/tests/execute/vf/VfDeploymentTests.java | 340 ++ .../uici/tests/execute/vf/VfOnboardingTests.java | 63 + .../sdc/uici/tests/execute/vfc/VfcBasicTests.java | 270 ++ .../openecomp/sdc/uici/tests/run/StartTest.java | 252 ++ .../sdc/uici/tests/utilities/ArtifactUIUtils.java | 70 + .../sdc/uici/tests/utilities/FileHandling.java | 30 + .../sdc/uici/tests/utilities/GeneralUIUtils.java | 344 ++ .../tests/utilities/MethodManipulationUtils.java | 15 + .../sdc/uici/tests/utilities/OnboardUtility.java | 477 +++ .../sdc/uici/tests/utilities/ResourceUIUtils.java | 299 ++ .../sdc/uici/tests/utilities/RestCDUtils.java | 167 + .../sdc/uici/tests/utilities/ServiceUIUtils.java | 147 + .../uici/tests/verificator/ServiceVerificator.java | 55 + .../uici/tests/verificator/VerificatorUtil.java | 27 + .../sdc/uici/tests/verificator/VfVerificator.java | 143 + .../main/resources/ci/conf/attsdc-packages.yaml | 2 + ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml | 80 + .../src/main/resources/ci/conf/credentials.yaml | 48 + .../src/main/resources/ci/conf/log4j.properties | 34 + .../src/main/resources/ci/conf/titan.properties | 7 + .../src/main/resources/ci/scripts/startTest.sh | 123 + .../src/main/resources/ci/testSuites/fullTests.xml | 26 + .../src/main/resources/ci/testSuites/sanity.xml | 55 + ui-ci-dev/src/main/resources/images/gizmorambo.jpg | Bin 0 -> 16605 bytes ui-ci-dev/src/test/Completetheform.js | 3 + ui-ci/.gitignore | 2 + ui-ci/hs_err_pid10052.log | 389 +++ ui-ci/pom.xml | 357 ++ .../US/AddComponentInstancesArtifactsInCsar.java | 415 +++ ...portUpdateInformationalDeploymentArtifacts.java | 343 ++ .../java/org/openecomp/sdc/ci/tests/US/Inputs.java | 226 ++ .../sdc/ci/tests/US/LocalGeneralUtilities.java | 99 + .../tests/US/MIBsArtifactsOnResourceInstance.java | 269 ++ .../org/openecomp/sdc/ci/tests/US/MobProxy.java | 144 + .../sdc/ci/tests/US/NewArtifactTypeGuide.java | 123 + .../US/RemoveRestrictionOfDeploymentArtifacts.java | 117 + .../sdc/ci/tests/US/Service_Tests_UI.java | 107 + .../org/openecomp/sdc/ci/tests/US/Testing.java | 125 + .../org/openecomp/sdc/ci/tests/US/VfModule.java | 156 + .../org/openecomp/sdc/ci/tests/US/Vf_Tests_UI.java | 94 + ...ndNode_TemplatePropertiesWithDefaultValues.java | 299 ++ .../tests/businesslogic/ArtifactBusinessLogic.java | 208 ++ .../sdc/ci/tests/datatypes/ArtifactInfo.java | 105 + .../sdc/ci/tests/datatypes/CanvasElement.java | 65 + .../sdc/ci/tests/datatypes/CanvasManager.java | 268 ++ .../tests/datatypes/CatalogFilterTitlesEnum.java | 37 + .../sdc/ci/tests/datatypes/CheckBoxStatusEnum.java | 50 + .../datatypes/CreateAndImportButtonsEnum.java | 27 + .../sdc/ci/tests/datatypes/DataTestIdEnum.java | 835 +++++ .../ci/tests/datatypes/ErrorMessageProperties.java | 53 + .../ci/tests/datatypes/GeneralCanvasItemsEnum.java | 38 + .../tests/datatypes/HeatAndHeatEnvNamesPair.java | 62 + .../datatypes/HeatWithParametersDefinition.java | 102 + .../sdc/ci/tests/datatypes/LifeCycleStateEnum.java | 47 + .../sdc/ci/tests/datatypes/MenuOptionsEnum.java | 37 + .../sdc/ci/tests/datatypes/PropertyInfo.java | 76 + .../datatypes/ResourceCategoriesNameEnum.java | 45 + .../tests/datatypes/ServiceCategoriesNameEnum.java | 36 + .../sdc/ci/tests/datatypes/TopMenuButtonsEnum.java | 38 + .../sdc/ci/tests/datatypes/TypesEnum.java | 36 + .../sdc/ci/tests/datatypes/UserCredentials.java | 58 + .../sdc/ci/tests/datatypes/UserManagementTab.java | 114 + .../sdc/ci/tests/datatypes/VFCArtifact.java | 71 + .../sdc/ci/tests/datatypes/environmentLocal | 10 + .../tests/execute/sanity/AdminUserManagment.java | 289 ++ .../tests/execute/sanity/CatalogLeftPanelTest.java | 236 ++ .../sdc/ci/tests/execute/sanity/Categories.java | 213 ++ .../ci/tests/execute/sanity/CustomizationUUID.java | 383 +++ .../tests/execute/sanity/DeploymentViewTests.java | 286 ++ .../sdc/ci/tests/execute/sanity/ImportDCAE.java | 678 ++++ .../ci/tests/execute/sanity/ImportVFCAsset.java | 353 ++ .../sdc/ci/tests/execute/sanity/Onboard.java | 355 ++ .../ci/tests/execute/sanity/OnboardViaApis.java | 303 ++ .../sdc/ci/tests/execute/sanity/Product.java | 93 + .../sdc/ci/tests/execute/sanity/Service.java | 698 ++++ .../sdc/ci/tests/execute/sanity/VFCArtifacts.java | 402 +++ .../openecomp/sdc/ci/tests/execute/sanity/Vf.java | 687 ++++ .../sdc/ci/tests/execute/sanity/VfArtifacts.java | 380 +++ .../sanity/VfDeploymentInformationalArtifacts.java | 862 +++++ .../execute/setup/ArtifactsCorrelationManager.java | 72 + .../sdc/ci/tests/execute/setup/AttFtpClient.java | 221 ++ .../sdc/ci/tests/execute/setup/DriverFactory.java | 125 + .../sdc/ci/tests/execute/setup/ExtentManager.java | 169 + .../ci/tests/execute/setup/ExtentTestActions.java | 114 + .../ci/tests/execute/setup/ExtentTestManager.java | 60 + .../sdc/ci/tests/execute/setup/MobProxy.java | 103 + .../ci/tests/execute/setup/OnboardCSVReport.java | 63 + .../execute/setup/ReportAfterTestManager.java | 129 + .../sdc/ci/tests/execute/setup/Retry.java | 44 + .../sdc/ci/tests/execute/setup/SetupCDTest.java | 573 ++++ .../sdc/ci/tests/execute/setup/TestFtp.java | 94 + .../ci/tests/execute/setup/WebDriverThread.java | 164 + .../sdc/ci/tests/execute/setup/WindowTest.java | 77 + .../ci/tests/execute/setup/WindowTestManager.java | 52 + .../sdc/ci/tests/pages/AdminGeneralPage.java | 132 + .../sdc/ci/tests/pages/ComponentLeftMenu.java | 25 + .../sdc/ci/tests/pages/CompositionPage.java | 197 ++ .../sdc/ci/tests/pages/DeploymentArtifactPage.java | 277 ++ .../sdc/ci/tests/pages/DeploymentPage.java | 239 ++ .../sdc/ci/tests/pages/GeneralPageElements.java | 160 + .../sdc/ci/tests/pages/GovernorOperationPage.java | 46 + .../org/openecomp/sdc/ci/tests/pages/HomePage.java | 109 + .../org/openecomp/sdc/ci/tests/pages/IconPage.java | 51 + .../ci/tests/pages/InformationalArtifactPage.java | 74 + .../openecomp/sdc/ci/tests/pages/InputsPage.java | 158 + .../sdc/ci/tests/pages/OpsOperationPage.java | 156 + .../sdc/ci/tests/pages/ProductGeneralPage.java | 119 + .../sdc/ci/tests/pages/ProductLeftMenu.java | 48 + .../sdc/ci/tests/pages/PropertiesPage.java | 74 + .../sdc/ci/tests/pages/PropertyPopup.java | 111 + .../sdc/ci/tests/pages/ResourceGeneralPage.java | 177 + .../sdc/ci/tests/pages/ResourceLeftMenu.java | 67 + .../sdc/ci/tests/pages/ServiceGeneralPage.java | 114 + .../sdc/ci/tests/pages/ServiceLeftMenu.java | 32 + .../sdc/ci/tests/pages/TesterOperationPage.java | 101 + .../sdc/ci/tests/pages/ToscaArtifactsPage.java | 54 + .../sdc/ci/tests/pages/UploadArtifactPopup.java | 126 + .../ci/tests/utilities/AdditionalConditions.java | 110 + .../tests/utilities/AdminWorkspaceUIUtilies.java | 57 + .../sdc/ci/tests/utilities/ArtifactUIUtils.java | 638 ++++ .../sdc/ci/tests/utilities/AuditCDUtils.java | 67 + .../sdc/ci/tests/utilities/CanvasElement.java | 54 + .../sdc/ci/tests/utilities/CanvasManager.java | 179 + .../sdc/ci/tests/utilities/CatalogUIUtilitis.java | 232 ++ .../sdc/ci/tests/utilities/DownloadManager.java | 115 + .../sdc/ci/tests/utilities/FileHandling.java | 505 +++ .../sdc/ci/tests/utilities/GeneralUIUtils.java | 790 +++++ .../sdc/ci/tests/utilities/HomeUtils.java | 117 + .../sdc/ci/tests/utilities/ImportAssetUIUtils.java | 57 + .../sdc/ci/tests/utilities/OnboardingUtils.java | 801 +++++ .../sdc/ci/tests/utilities/ProductUIUtils.java | 94 + .../sdc/ci/tests/utilities/PropertiesUIUtils.java | 108 + .../sdc/ci/tests/utilities/ResourceUIUtils.java | 1143 +++++++ .../sdc/ci/tests/utilities/RestCDUtils.java | 344 ++ .../sdc/ci/tests/utilities/ServiceUIUtils.java | 286 ++ .../ci/tests/verificator/CatalogVerificator.java | 168 + .../verificator/CustomizationUUIDVerificator.java | 27 + .../verificator/DeploymentViewVerificator.java | 328 ++ .../verificator/ErrorMessageUIVerificator.java | 64 + .../ci/tests/verificator/ServiceVerificator.java | 335 ++ .../verificator/UserManagementVerificator.java | 152 + .../tests/verificator/VFCArtifactVerificator.java | 347 ++ .../sdc/ci/tests/verificator/VFCverificator.java | 37 + .../ci/tests/verificator/VfModuleVerificator.java | 156 + .../sdc/ci/tests/verificator/VfVerificator.java | 245 ++ ui-ci/src/main/resources/Downloads/CP_WAN.yml | 23 + .../resources/Downloads/Fortigate02_vFW_VFC.yml | 63 + .../main/resources/ci/conf/attsdc-packages.yaml | 2 + ui-ci/src/main/resources/ci/conf/attsdc.yaml | 63 + ui-ci/src/main/resources/ci/conf/credentials.yaml | 48 + .../main/resources/ci/conf/credentials.yaml_prod | 48 + .../resources/ci/conf/credentials.yaml_webtest | 48 + ui-ci/src/main/resources/ci/conf/extent-config.xml | 51 + ui-ci/src/main/resources/ci/conf/log4j.properties | 34 + ui-ci/src/main/resources/ci/conf/titan.properties | 7 + .../src/main/resources/ci/drivers/chromedriver.exe | Bin 0 -> 7442432 bytes .../resources/ci/scripts/addUsersFromList_new.sh | 75 + .../src/main/resources/ci/scripts/copyToStorage.sh | 51 + ui-ci/src/main/resources/ci/scripts/sendMail.sh | 49 + ui-ci/src/main/resources/ci/scripts/startTest.sh | 155 + ui-ci/src/main/resources/ci/scripts/userList.txt | 1 + .../main/resources/ci/testSuites/andreyPara.xml | 10 + .../resources/ci/testSuites/devOnboardSanity.xml | 14 + .../src/main/resources/ci/testSuites/devSanity.xml | 20 + .../resources/ci/testSuites/extendedSanity.xml | 33 + ui-ci/src/main/resources/ci/testSuites/fullCI.xml | 34 + .../resources/ci/testSuites/onboardingVNFs.xml | 15 + ui-ci/src/main/resources/ci/testSuites/sanity.xml | 30 + ui-ci/src/main/resources/images/gizmorambo.jpg | Bin 0 -> 16605 bytes ui-ci/src/test/Completetheform.js | 3 + ui-ci/tarball.xml | 70 + .../org/openecomp/sdc/webseal/simulator/Login.java | 6 +- .../sdc/webseal/simulator/RequestsClient.java | 75 +- .../src/main/resources/webseal.conf | 18 +- 1271 files changed, 181897 insertions(+), 18966 deletions(-) create mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/FilteredDataByParamsComponentServletTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java delete mode 100644 asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java delete mode 100644 asdc-tests/src/main/resources/ci/testSuites/product.xml delete mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java create mode 100644 asdctool/src/main/resources/scripts/distributionStatusUpdate1707.sh create mode 100644 asdctool/src/main/resources/scripts/migration1707RelationsFix.sh create mode 100644 asdctool/src/main/resources/scripts/retrieve_schema_file.sh create mode 100644 asdctool/src/main/resources/scripts/vfmoduleFix1707.sh create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java create mode 100644 catalog-ui/src/app/models/properties-inputs/input-be-model.ts create mode 100644 catalog-ui/src/app/models/properties-inputs/simple-flat-property.ts delete mode 100644 catalog-ui/src/app/models/property-fe-model.ts create mode 100644 catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.html create mode 100644 catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.less create mode 100644 catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts create mode 100644 catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.html create mode 100644 catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.ts create mode 100644 catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.less create mode 100644 catalog-ui/src/app/ng2/components/loader/loader.component.html create mode 100644 catalog-ui/src/app/ng2/components/loader/loader.component.less create mode 100644 catalog-ui/src/app/ng2/components/loader/loader.component.ts create mode 100644 catalog-ui/src/app/ng2/components/modal/modal.component.html create mode 100644 catalog-ui/src/app/ng2/components/modal/modal.component.less create mode 100644 catalog-ui/src/app/ng2/components/modal/modal.component.ts delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less delete mode 100644 catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts create mode 100644 catalog-ui/src/app/ng2/services/component-mode.service.ts create mode 100644 catalog-ui/src/app/ng2/services/hierarchy-nav.service.ts create mode 100644 catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view-model.ts create mode 100644 catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html create mode 100644 catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less delete mode 100644 catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts delete mode 100644 catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html delete mode 100644 catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less delete mode 100644 common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java delete mode 100644 common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java delete mode 100644 common/openecomp-common-configuration-management/openecomp-configuration-management-cli/dependency-reduced-pom.xml delete mode 100644 openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/VSPPackage.zip create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedMultiLevels/out/Nested_jsaServiceTemplate.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/MANIFEST.json create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.env create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/nested-pcm_v0.1.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/MainServiceTemplate.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/Nested_computeServiceTemplate.yaml create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/nested-pcm_v0.1ServiceTemplate.yaml delete mode 100644 openecomp-be/sonar-project.properties delete mode 100644 sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties create mode 100644 test-apis-ci/.gitignore create mode 100644 test-apis-ci/pom.xml create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CsarArtifacts.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatMetaFirstLevelDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ArtifactFromCsar.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ParametersDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaOutputsTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPoliciesTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRelationshipTemplatesTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaSubstitutionMappingsDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition2.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/DeploymentValiditaion.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/SearchFilterCategoryExternalAPI.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/UserAPIs.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java create mode 100644 test-apis-ci/src/main/resources/ci/conf/attsdc-packages.yaml create mode 100644 test-apis-ci/src/main/resources/ci/conf/attsdc.yaml create mode 100644 test-apis-ci/src/main/resources/ci/conf/extent-config.xml create mode 100644 test-apis-ci/src/main/resources/ci/conf/log4j.properties create mode 100644 test-apis-ci/src/main/resources/ci/conf/log4j.xml create mode 100644 test-apis-ci/src/main/resources/ci/conf/testngLifeCycle.xml create mode 100644 test-apis-ci/src/main/resources/ci/conf/titan.properties create mode 100644 test-apis-ci/src/main/resources/ci/conf/truststore create mode 100644 test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh create mode 100644 test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh create mode 100644 test-apis-ci/src/main/resources/ci/scripts/sendMail.sh create mode 100644 test-apis-ci/src/main/resources/ci/scripts/startTest.sh create mode 100644 test-apis-ci/src/main/resources/ci/scripts/userList.txt create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/SearchExternalAPI.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/artifacts.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/category.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/ciFull.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/general.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/imports.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/product.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/productAPIs.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/property.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/resource.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/sanity.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/service.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/testngLifeCycle.xml create mode 100644 test-apis-ci/src/main/resources/ci/testSuites/user.xml create mode 100644 test-apis-ci/src/main/resources/log4j.properties create mode 100644 test-apis-ci/src/main/resources/log4j.xml create mode 100644 test-apis-ci/src/main/resources/logback.xml create mode 100644 test-apis-ci/src/test/resources/CI/ecomp-error-configuration.yaml create mode 100644 test-apis-ci/src/test/resources/CI/error-configuration.yaml create mode 100644 test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.yml create mode 100644 test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.zip create mode 100644 test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml create mode 100644 test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip create mode 100644 test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml create mode 100644 test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip create mode 100644 test-apis-ci/src/test/resources/CI/other/mapping.json create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json create mode 100644 test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json create mode 100644 test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListNoContentTest/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataNoContentTest/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getResourceArtifactPayloadNoContentTest/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/install_mysql2.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/start_mysql2.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topology.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topologyTemplate.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topology.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topologyTemplate.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/install_mysql2.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/start_mysql2.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topology.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topologyTemplate.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/install_mysql2.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/start_mysql2.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topology.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topologyTemplate.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topology.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topologyTemplate.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_1.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/heatEnv/yuli.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/noContent.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topology.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/uploadComponent/images/mysql.png create mode 100644 test-apis-ci/src/test/resources/CI/tests/uploadComponent/mysql.yml create mode 100644 test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/install_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/start_mysql.sh create mode 100644 test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml create mode 100644 test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml create mode 100644 test-apis-ci/src/test/resources/config.json create mode 100644 test-apis-ci/src/test/resources/logback-test.xml create mode 100644 test-apis-ci/testng.xml create mode 100644 test-apis-ci/testngLifeCycle.xml create mode 100644 test-apis-ci/tmpCSAR create mode 100644 ui-ci-dev/.gitignore create mode 100644 ui-ci-dev/pom.xml create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/scripts/CreateVfsFromOnboarding.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasElement.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasManager.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CleanTypeEnum.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndImportButtonsEnum.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndUpdateStepsEnum.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/MenuOptionsEnum.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/UserCredentials.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/generalTests/GeneralTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceBasicTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceInputsTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfCanvasTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfDeploymentTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfOnboardingTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ArtifactUIUtils.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/FileHandling.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/MethodManipulationUtils.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/OnboardUtility.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ResourceUIUtils.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/RestCDUtils.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ServiceUIUtils.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/ServiceVerificator.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VerificatorUtil.java create mode 100644 ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VfVerificator.java create mode 100644 ui-ci-dev/src/main/resources/ci/conf/attsdc-packages.yaml create mode 100644 ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml create mode 100644 ui-ci-dev/src/main/resources/ci/conf/credentials.yaml create mode 100644 ui-ci-dev/src/main/resources/ci/conf/log4j.properties create mode 100644 ui-ci-dev/src/main/resources/ci/conf/titan.properties create mode 100644 ui-ci-dev/src/main/resources/ci/scripts/startTest.sh create mode 100644 ui-ci-dev/src/main/resources/ci/testSuites/fullTests.xml create mode 100644 ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml create mode 100644 ui-ci-dev/src/main/resources/images/gizmorambo.jpg create mode 100644 ui-ci-dev/src/test/Completetheform.js create mode 100644 ui-ci/.gitignore create mode 100644 ui-ci/hs_err_pid10052.log create mode 100644 ui-ci/pom.xml create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Inputs.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MobProxy.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/NewArtifactTypeGuide.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Vf_Tests_UI.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/extendNode_TemplatePropertiesWithDefaultValues.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/businesslogic/ArtifactBusinessLogic.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ErrorMessageProperties.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatWithParametersDefinition.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserManagementTab.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VFCArtifact.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/AdminUserManagment.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Categories.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ArtifactsCorrelationManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/AttFtpClient.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/MobProxy.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/Retry.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/TestFtp.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTest.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTestManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AdminGeneralPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InputsPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductGeneralPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductLeftMenu.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceLeftMenu.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CustomizationUUIDVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/DeploymentViewVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ErrorMessageUIVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/UserManagementVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCArtifactVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCverificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfModuleVerificator.java create mode 100644 ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.java create mode 100644 ui-ci/src/main/resources/Downloads/CP_WAN.yml create mode 100644 ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml create mode 100644 ui-ci/src/main/resources/ci/conf/attsdc-packages.yaml create mode 100644 ui-ci/src/main/resources/ci/conf/attsdc.yaml create mode 100644 ui-ci/src/main/resources/ci/conf/credentials.yaml create mode 100644 ui-ci/src/main/resources/ci/conf/credentials.yaml_prod create mode 100644 ui-ci/src/main/resources/ci/conf/credentials.yaml_webtest create mode 100644 ui-ci/src/main/resources/ci/conf/extent-config.xml create mode 100644 ui-ci/src/main/resources/ci/conf/log4j.properties create mode 100644 ui-ci/src/main/resources/ci/conf/titan.properties create mode 100644 ui-ci/src/main/resources/ci/drivers/chromedriver.exe create mode 100644 ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh create mode 100644 ui-ci/src/main/resources/ci/scripts/copyToStorage.sh create mode 100644 ui-ci/src/main/resources/ci/scripts/sendMail.sh create mode 100644 ui-ci/src/main/resources/ci/scripts/startTest.sh create mode 100644 ui-ci/src/main/resources/ci/scripts/userList.txt create mode 100644 ui-ci/src/main/resources/ci/testSuites/andreyPara.xml create mode 100644 ui-ci/src/main/resources/ci/testSuites/devOnboardSanity.xml create mode 100644 ui-ci/src/main/resources/ci/testSuites/devSanity.xml create mode 100644 ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml create mode 100644 ui-ci/src/main/resources/ci/testSuites/fullCI.xml create mode 100644 ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml create mode 100644 ui-ci/src/main/resources/ci/testSuites/sanity.xml create mode 100644 ui-ci/src/main/resources/images/gizmorambo.jpg create mode 100644 ui-ci/src/test/Completetheform.js create mode 100644 ui-ci/tarball.xml diff --git a/asdc-tests/pom.xml b/asdc-tests/pom.xml index 0c0e9a2598..02092fdaf3 100644 --- a/asdc-tests/pom.xml +++ b/asdc-tests/pom.xml @@ -270,7 +270,7 @@ org.openecomp.ecompsdkos - ecompFW + epsdk-fw ${ecomp.version} compile 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 a8342f8879..0e1c0e4da1 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 @@ -163,6 +163,7 @@ public interface Urls { final String GET_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s"; final String GET_RESOURCE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/resourceName/%s/resourceVersion/%s"; final String GET_RESOURCE_BY_CSAR_UUID = "http://%s:%s/sdc2/rest/v1/catalog/resources/csar/%s"; + final String GET_RESOURCE_DATA_BY_PARAMS = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/filteredDataByParams?"; final String GET_COMPONENT_REQUIRMENTS_CAPABILITIES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/requirmentsCapabilities"; final String DELETE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s"; @@ -270,7 +271,6 @@ public interface Urls { final String GET_COMPONENT_INSTANCES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/componentInstances"; //{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties final String GET_COMPONENT_INSTANCE_PROPERTIES_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/componentInstances/%s/properties"; - // Tal New API final String UPDATE_MULTIPLE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/multipleComponentInstance"; final String CHANGE_RESOURCE_INSTANCE_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/changeVersion"; diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java index d1b6ff5676..b1d04ba88d 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java @@ -31,7 +31,7 @@ import org.junit.rules.TestName; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; import org.openecomp.sdc.ci.tests.api.Urls; @@ -69,13 +69,13 @@ public class ComponentInstanceAttributeTest extends ComponentBaseTest { .addComponentInstanceToComponentContainer(vfcWithAttributes, vf).left().value(); // util method to get the specific attribute from the vf - Function attributeGetter = resourceVf -> resourceVf + Function attributeGetter = resourceVf -> resourceVf .getComponentInstancesAttributes().values().iterator().next().stream() .filter(att -> att.getName().equals("private_address")).findAny().get(); // update attribute on vfc instance final Resource vfWithInsatncePreUpdate = swallowException( () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER)); - ComponentInstanceAttribute attributeOfRI = attributeGetter.apply(vfWithInsatncePreUpdate); + ComponentInstanceProperty attributeOfRI = attributeGetter.apply(vfWithInsatncePreUpdate); final String newAttValue = "NewValue"; attributeOfRI.setValue(newAttValue); String body = gson.toJson(attributeOfRI); @@ -87,7 +87,7 @@ public class ComponentInstanceAttributeTest extends ComponentBaseTest { // Retrieve updated vf and verify attribute was updated final Resource vfWithInsatncePostUpdate = swallowException( () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER)); - ComponentInstanceAttribute updatedAttribute = attributeGetter.apply(vfWithInsatncePostUpdate); + ComponentInstanceProperty updatedAttribute = attributeGetter.apply(vfWithInsatncePostUpdate); assertEquals(updatedAttribute.getValue(), newAttValue); } diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java index 08e7539b28..24c91935d4 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java @@ -63,12 +63,39 @@ public class ValidateConformanceLevel extends ComponentBaseTest { Service serviceFirstImport = ResponseParser.parseToObjectUsingMapper(createdService.getResponse(), Service.class); Component serviceObject = AtomicOperationUtils.changeComponentState(serviceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); - RestResponse apiRes = ComponentRestUtils.validateConformanceLevel(serviceObject.getUniqueId(), user.getUserId()); + RestResponse apiRes = ComponentRestUtils.validateConformanceLevel(serviceObject.getUUID(), user.getUserId()); String result = apiRes.getResponse(); assertTrue(apiRes.getErrorCode() == 200); assertTrue(result.equals("true")); } + @Test + public void testValidateServiceConformanceLevelForSecondMajorVersion() throws Exception { + User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + ServiceReqDetails service = ElementFactory.getDefaultService(); + RestResponse createdService = ServiceRestUtils.createService(service, user); + BaseRestUtils.checkCreateResponse(createdService); + Service serviceFirstImport = ResponseParser.parseToObjectUsingMapper(createdService.getResponse(), Service.class); + Component serviceObject = AtomicOperationUtils.changeComponentState(serviceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + String uuid1 = serviceObject.getUUID(); + Component service20Object = AtomicOperationUtils.changeComponentState(serviceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service20Object = AtomicOperationUtils.changeComponentState(service20Object, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + String uuid2 = service20Object.getUUID(); + + assertTrue(uuid1 != uuid2); + + RestResponse apiRes = ComponentRestUtils.validateConformanceLevel(uuid1, user.getUserId()); + String result = apiRes.getResponse(); + assertTrue(apiRes.getErrorCode() == 200); + assertTrue(result.equals("true")); + + apiRes = ComponentRestUtils.validateConformanceLevel(uuid2, user.getUserId()); + result = apiRes.getResponse(); + assertTrue(apiRes.getErrorCode() == 200); + assertTrue(result.equals("true")); + } + @Test public void testValidateConformanceLevel404() throws Exception { User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/FilteredDataByParamsComponentServletTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/FilteredDataByParamsComponentServletTest.java new file mode 100644 index 0000000000..541294c141 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/FilteredDataByParamsComponentServletTest.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.ci.tests.execute.imports; + +import static org.testng.AssertJUnit.assertEquals; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.codec.binary.Base64; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.annotations.Test; + + + +public class FilteredDataByParamsComponentServletTest extends ComponentBaseTest{ + + private static final String CSAR_NAME = "LDSA1_with_inputs.csar"; + private static final String COMPONENT_INSTANCES = "include=componentInstances"; + private static final String COMPONENT_INSTANCES_RELATIONS = "include=componentInstancesRelations"; + private static final String DEPLOYMENT_ARTIFACTS = "include=deploymentArtifacts"; + private static final String INFORMATIONAL_ARTIFACTS = "include=artifacts"; + private static final String METADATA = "include=metadata"; + public static TestName name = new TestName(); + + + + protected User designerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + public FilteredDataByParamsComponentServletTest() { + super(name, ImportCsarResourceTest.class.getName()); + } + + + @Test + public void getComponentInstancesAndComponentInstancesRelationsTest() throws Exception { + Resource resource = ResourceRestUtils.importResourceFromCsar(CSAR_NAME); + List parameters = new ArrayList<>(); + parameters.add(COMPONENT_INSTANCES); + parameters.add(COMPONENT_INSTANCES_RELATIONS); + // create UiComponentDataTransfer and parse the ComponentInstancesRelations into it + RestResponse resourceGetResponse = ResourceRestUtils.getResourceFilteredDataByParams(designerDetails, resource.getUniqueId() , parameters); + UiComponentDataTransfer uiComponentWithComponentInstancesAndRelations = ResponseParser.parseToObjectUsingMapper(resourceGetResponse.getResponse() , UiComponentDataTransfer.class); + + uiComponentWithComponentInstancesAndRelations.getComponentInstances().stream().sorted((object1, object2) -> object1.getUniqueId().compareTo(object2.getUniqueId())); + resource.getComponentInstances().stream().sorted((object1, object2) -> object1.getUniqueId().compareTo(object2.getUniqueId())); + + for (int i = 0 ; i < resource.getComponentInstances().size() ; i++){ + assertEquals(uiComponentWithComponentInstancesAndRelations.getComponentInstances().get(i).getUniqueId() ,resource.getComponentInstances().get(i).getUniqueId()); + } + assertEquals(uiComponentWithComponentInstancesAndRelations.getComponentInstancesRelations().size() , resource.getComponentInstancesRelations().size()); + } + + + @Test + public void getComponentDeploymentAndInformationalArtifacts() throws Exception { + Resource resource = ResourceRestUtils.importResourceFromCsar(CSAR_NAME); + List parameters = new ArrayList<>(); + parameters.add(DEPLOYMENT_ARTIFACTS); + parameters.add(INFORMATIONAL_ARTIFACTS); + + // create new UiComponentData transfer and parse the artifacts into it + RestResponse resourceGetResponse = ResourceRestUtils.getResourceFilteredDataByParams(designerDetails, resource.getUniqueId() , parameters); + UiComponentDataTransfer uiComponentWithArtifacts = ResponseParser.parseToObjectUsingMapper(resourceGetResponse.getResponse() , UiComponentDataTransfer.class); + + List deploymentArtifactsFromResource = new ArrayList(resource.getDeploymentArtifacts().values()); + List deploymentArtifactsFromUiComponent = new ArrayList(uiComponentWithArtifacts.getDeploymentArtifacts().values()); + List informationalArtifactsFromResource = new ArrayList(resource.getArtifacts().values()); + List informationalArtifactsFromUiComponent = new ArrayList(uiComponentWithArtifacts.getArtifacts().values()); + + deploymentArtifactsFromResource.stream().sorted((object1, object2) -> object1.getUniqueId().compareTo(object2.getUniqueId())); + deploymentArtifactsFromUiComponent.stream().sorted((object1, object2) -> object1.getUniqueId().compareTo(object2.getUniqueId())); + informationalArtifactsFromResource.stream().sorted((object1, object2) -> object1.getUniqueId().compareTo(object2.getUniqueId())); + informationalArtifactsFromUiComponent.stream().sorted((object1, object2) -> object1.getUniqueId().compareTo(object2.getUniqueId())); + + for (int i = 0 ; i < deploymentArtifactsFromResource.size() ; i++){ + assertEquals(deploymentArtifactsFromResource.get(i).getUniqueId() , deploymentArtifactsFromUiComponent.get(i).getUniqueId()); + } + + for (int i = 0 ; i < informationalArtifactsFromResource.size() ; i++){ + assertEquals(informationalArtifactsFromResource.get(i).getUniqueId() , informationalArtifactsFromUiComponent.get(i).getUniqueId()); + } + } + + + @Test + public void getComponentMetadataTest() throws Exception { + + Resource resource = ResourceRestUtils.importResourceFromCsar(CSAR_NAME); + List parameters = new ArrayList<>(); + parameters.add(METADATA); + + // create new UiResourceDataTransfer and parse the metadata into it + RestResponse resourceGetResponse = ResourceRestUtils.getResourceFilteredDataByParams(designerDetails, resource.getUniqueId() , parameters); + UiResourceDataTransfer uiResourceWithMetadata = ResponseParser.parseToObjectUsingMapper(resourceGetResponse.getResponse(), UiResourceDataTransfer.class); + + // assert that the metadata is equal + assertEquals(uiResourceWithMetadata.getMetadata().getName(), resource.getName()); + assertEquals(uiResourceWithMetadata.getMetadata().getVersion() , resource.getVersion()); + assertEquals(uiResourceWithMetadata.getMetadata().getUniqueId() , resource.getUniqueId()); + assertEquals(uiResourceWithMetadata.getMetadata().getUUID(), resource.getUUID()); + } + + + + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java index 6bf3477c1f..f0421fb026 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java @@ -1468,26 +1468,7 @@ public class ImportCsarResourceTest extends ComponentBaseTest { @Test public void createImportRIRelationByCapNameFromCsarUITest() throws Exception { - User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); - String payloadName = "vmmc_relate_by_cap_name.csar"; - ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); - String rootPath = System.getProperty("user.dir"); - Path path = null; - byte[] data = null; - String payloadData = null; - - path = Paths.get(rootPath + CSARS_PATH + "vmmc_relate_by_cap_name.csar"); - data = Files.readAllBytes(path); - payloadData = Base64.encodeBase64String(data); - resourceDetails.setPayloadData(payloadData); - - // create new resource from Csar - resourceDetails.setCsarUUID(payloadName); - resourceDetails.setPayloadName(payloadName); - resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); - RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); - BaseRestUtils.checkCreateResponse(createResource); - Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + Resource resource = ResourceRestUtils.importResourceFromCsar("vmmc_relate_by_cap_name.csar"); // assert all relations created assertEquals(80, resource.getComponentInstancesRelations().size()); } diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java index 9e8a2a1f95..56841e1c5d 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java @@ -38,7 +38,6 @@ import org.junit.Rule; import org.junit.rules.TestName; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; @@ -1470,12 +1469,12 @@ public class ImportNewResourceCITest extends ComponentBaseTest { checkListValues(listValue.get(1), 2, SPECIAL_CHARACTERS); // Verify attributes - List attributes = resource.getAttributes(); + List attributes = resource.getAttributes(); assertEquals("check properties size", 2, attributes.size()); // Verify attribute from type map - AttributeDefinition attributeMapDefinition = attributes.stream() + PropertyDefinition attributeMapDefinition = attributes.stream() .filter(p -> p.getName().equals("validation_test_map")).findFirst().get(); String defaultMapValue = attributeMapDefinition.getDefaultValue(); Map attributeMapValue = gson.fromJson(defaultMapValue, Map.class); @@ -1484,7 +1483,7 @@ public class ImportNewResourceCITest extends ComponentBaseTest { checkMapValues(attributeMapValue, "key", 2, SPECIAL_CHARACTERS); // Verify attribute from type list - AttributeDefinition attributeListDefinition = attributes.stream() + PropertyDefinition attributeListDefinition = attributes.stream() .filter(p -> p.getName().equals("validation_test_list")).findFirst().get(); String defaultListValue = attributeListDefinition.getDefaultValue(); diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java index 0973135295..ef95b34198 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java @@ -46,7 +46,6 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapReqDef; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; @@ -2837,9 +2836,9 @@ public class ImportToscaResourceTest extends ComponentBaseTest { ToscaNodeTypeInfo parseToscaNodeYaml = utils .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); - HashMap attr = new HashMap<>(); + HashMap attr = new HashMap<>(); - AttributeDefinition newAttr2 = new AttributeDefinition(); + PropertyDefinition newAttr2 = new PropertyDefinition(); newAttr2.setName("networks"); newAttr2.setType("map"); newAttr2.setDefaultValue("{\"keyA\" : val1 , \"keyB\" : val2}"); @@ -2850,17 +2849,17 @@ public class ImportToscaResourceTest extends ComponentBaseTest { newAttr2.setSchema(schema); attr.put("networks", newAttr2); - AttributeDefinition newAttr1 = new AttributeDefinition(); + PropertyDefinition newAttr1 = new PropertyDefinition(); newAttr1.setName("public_address"); newAttr1.setType("string"); attr.put("public_address", newAttr1); - AttributeDefinition newAttr3 = new AttributeDefinition(); + PropertyDefinition newAttr3 = new PropertyDefinition(); newAttr3.setName("ports"); newAttr3.setDescription("this is my description"); attr.put("ports", newAttr3); - AttributeDefinition newAttr = new AttributeDefinition(); + PropertyDefinition newAttr = new PropertyDefinition(); newAttr.setDefaultValue("myDefault"); newAttr.setName("private_address"); newAttr.setStatus("supported"); @@ -2880,8 +2879,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest { AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); } - private void validateResourceAttribute(Resource resource, Map attr) { - List resList = resource.getAttributes(); + private void validateResourceAttribute(Resource resource, Map attr) { + List resList = resource.getAttributes(); int size = resList.size(); String attributeName; for (int i = 0; i < size; i++) { diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java deleted file mode 100644 index 6a4fa3ba55..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java +++ /dev/null @@ -1,1478 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS_DELETE; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Rule; -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.ComponentInstance; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest; -import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -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.ArtifactRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -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.ErrorValidationUtils; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class ChangeServiceInstanceVersionTest extends ComponentInstanceBaseTest { - - protected ArtifactReqDetails heatArtifactDetails; - public String firstVfInstanceUniqueId; - public String firstVfInstanceName; - public String secondVfInstanceUniqueId; - public String secoundVfInstanceName; - public String serviceInstanceToReplaceUniqueId; - public String expectedServiceName; - public String expectedPosX; - public String expectedPosY; - public String actualServiceInstanceName; - public String actualPosX; - public String actualPosY; - - @Rule - public static TestName name = new TestName(); - - public ChangeServiceInstanceVersionTest() { - super(name, ChangeServiceInstanceVersionTest.class.getName()); - } - - @BeforeMethod - public void before() throws Exception { - firstVfInstanceName = null; - secoundVfInstanceName = null; - firstVfInstanceUniqueId = null; - secondVfInstanceUniqueId = null; - serviceInstanceToReplaceUniqueId = null; - expectedServiceName = null; - expectedPosX = null; - expectedPosY = null; - actualServiceInstanceName = null; - actualPosX = null; - actualPosY = null; - init(); - createComponents(); - } - - private void createComponents() throws Exception { - heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); - createAtomicResource(resourceDetailsVFC_01); - changeResourceStateToCertified(resourceDetailsVFC_01); - createAtomicResource(resourceDetailsCP_01); - changeResourceStateToCertified(resourceDetailsCP_01); - createAtomicResource(resourceDetailsVL_01); - changeResourceStateToCertified(resourceDetailsVL_01); - createAtomicResource(resourceDetailsVFC_02); - changeResourceStateToCertified(resourceDetailsVFC_02); - createAtomicResource(resourceDetailsCP_02); - changeResourceStateToCertified(resourceDetailsCP_02); - createAtomicResource(resourceDetailsVL_02); - changeResourceStateToCertified(resourceDetailsVL_02); - createVF(resourceDetailsVF_02); - createVF(resourceDetailsVF_01); - // create check-In services - createService(serviceDetails_01); - createService(serviceDetails_02); - createService(serviceDetails_03); - createProduct(productDetails_01); - createProduct(productDetails_02); - - // add resourceDetailsCP_01 ,resourceDetailsVFC_01 and - // resourceDetailsCP_01 to resourceDetailsVF_01 and certify - // resourceDetailsVF_01 - certifyVf(resourceDetailsVF_01, resourceDetailsVFC_02, resourceDetailsCP_01); - // add resourceDetailsCP_02 ,resourceDetailsVFC_02 and - // resourceDetailsVL_02 to resourceDetailsVF_02 and certify - // resourceDetailsVF_02 - certifyVf(resourceDetailsVF_02, resourceDetailsVFC_02, resourceDetailsCP_02); - RestResponse createVFInstanceResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, - sdncDesignerDetails); // serviceDetails_01 has certified - // resourceDetailsVF_01 - firstVfInstanceName = ResponseParser.getNameFromResponse(createVFInstanceResponse); - createVFInstanceResponse = createVFInstanceDuringSetup(serviceDetails_02, resourceDetailsVF_02, - sdncDesignerDetails); // serviceDetails_01 has certified - // resourceDetailsVF_02 - secoundVfInstanceName = ResponseParser.getUniqueIdFromResponse(createVFInstanceResponse); - RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - } - - @Test - public void changeServiceInstanceVersionByPm() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // get the new VF instance uniqueId after checkout service - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - @Test - public void changeServiceInstanceVersionByAdmin() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // get the new VF instance uniqueId after checkout service - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // service [0.2] state to CERTIFICATIONREQUEST - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CERTIFICATIONREQUEST); - ResourceRestUtils.checkSuccess(changeStatusResponse); - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, - LifeCycleStatesEnum.STARTCERTIFICATION); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncAdminDetails, ComponentTypeEnum.PRODUCT, - true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - @Test - public void changeServiceInstanceToOlderVersion() throws Exception { - // Get VF Instance UniquId [Service version 0.1] - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - ComponentInstance actualComponentInstance = service.getComponentInstances().get(0); - firstVfInstanceUniqueId = actualComponentInstance.getUniqueId(); - String serviceOlderVersionUniquId = ResponseParser.getUniqueIdFromResponse(getServiceResponse); - - // Checkout service [0.2] - RestResponse changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, - sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // get the new VF instance uniqueId after checkout service - getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // Adding service instance (serviceDetails_01 V0.2) to product without - // saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to Older version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceOlderVersionUniquId, sdncPmDetails1, ComponentTypeEnum.PRODUCT, - true); - // RestResponse changeServiceInstanceVersionResponse = - // changeServiceInstanceVersion(productDetails_01.getUniqueId(), - // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid, - // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - // DE190201 - @Test - public void changeServiceInstanceVersionToCertifiedVersion() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - /* - * String serviceNewUniqueUid = - * ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - * serviceDetails_01.setUniqueId(serviceNewUniqueUid); - */ - // get the new VF instance uniqueId after checkout service - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CERTIFICATIONREQUEST); - ResourceRestUtils.checkSuccess(changeStatusResponse); - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, - LifeCycleStatesEnum.STARTCERTIFICATION); - ResourceRestUtils.checkSuccess(changeStatusResponse); - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, - LifeCycleStatesEnum.CERTIFY); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - // RestResponse changeServiceInstanceVersionResponse = - // changeServiceInstanceVersion(productDetails_01.getUniqueId(), - // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid, - // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - // DE191927 - @Test(enabled = false) - public void changeServiceInstanceVersionThenReCheckInProduct() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // get the new VF instance uniqueId after checkout service - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - ///////////////////// - productOldUniqueId = productDetails_01.getUniqueId(); - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - ///////////////////////////////////////////// - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - @Test - public void changeServiceInstanceToHisVersion() throws Exception { - // Get VF Instance UniquId [Service version 0.1] - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - String serviceOlderVersionUniquId = ResponseParser.getUniqueIdFromResponse(getServiceResponse); - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // get the new VF instance uniqueId after checkout service - getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceOlderVersionUniquId, sdncPmDetails1, ComponentTypeEnum.PRODUCT, - true); - // RestResponse changeServiceInstanceVersionResponse = - // changeServiceInstanceVersion(productDetails_01.getUniqueId(), - // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid, - // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - @Test - public void changeServiceInstanceVersionByAdminNotByProductOwner() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncAdminDetails, ComponentTypeEnum.PRODUCT, - true); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - - } - - @Test - public void changeServiceInstanceVersionByPmNotByProductOwner() throws Exception { - // Adding service instance (serviceDetails_01) to product AND ---> - // saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // change uniqueId after product check-out in expected Req&Cap - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - updateNewComponentInstanceId(createServiceInstanceResp, productNewUniqueId); - // CHANGE Service Instance VERSION BY NON PRODUCT OWNER (sdncPmDetails1 - // instead sdncPmDetails1) - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion( - productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails2, - ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void changeServiceInstanceVersionByTester() throws Exception { - // Adding service instance (serviceDetails_01) to product AND ---> - // saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // change uniqueId after product check-out in expected Req&Cap - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // CHANGE Service Instance VERSION BY NON PRODUCT OWNER (sdncPmDetails1 - // instead sdncPmDetails1) - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion( - productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, - sdncTesterDetails, ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void changeServiceInstanceVersionProductIsNotCheckOut() throws Exception { - // Adding service instance (serviceDetails_01) to product AND ---> - // saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // CHANGE Service Instance VERSION for Non checkedOut product - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productOldUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeServiceInstanceVersionResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - // DE191727 - @Test(enabled = false) - public void changeServiceInstanceVersionServiceIsInCheckOutState() throws Exception { - // Adding service instance (serviceDetails_01) to product AND ---> - // saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // change uniqueId after product check-out in expected Req&Cap - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // CHANGE Service Instance VERSION to service in checkOut state - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion( - productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, - ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(serviceNewUniqueUid); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - - } - - @Test - public void changeServiceInstanceVersionServiceInstanceDoesNotExist() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // change service instance to newer version - String serviceUniqueUidNotExist = "1234567890"; - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceUniqueUidNotExist, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(serviceUniqueUidNotExist); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name(), varibales, - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - // DE189392 - @Test(enabled = false) - public void changeServiceInstanceNonExistingProduct() throws Exception { - // Adding service instance (serviceDetails_01) to product saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // change service instance to newer version - Non existing Product - String productNewUniqueIdNotExist = "1234567890"; - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueIdNotExist, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(productNewUniqueIdNotExist); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name(), varibales, - changeServiceInstanceVersionResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void changeServiceInstanceVersionToNonExisitingServiceVersion() throws Exception { - // Adding service instance (serviceDetails_01) to product saving Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - updateNewComponentInstanceId(createServiceInstanceResp, productNewUniqueId); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // change service instance to Non-existing version - String serviceUniqueUidNotExist = "1234567890"; - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceUniqueUidNotExist, sdncPmDetails1, ComponentTypeEnum.PRODUCT, - true); - assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(serviceUniqueUidNotExist); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), varibales, - changeServiceInstanceVersionResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void changeServiceInstanceComponentTypeIsNotProduct() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version for NON-Component Type = - // Product (e.g. service) - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.SERVICE, true); - assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(""); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, - changeServiceInstanceVersionResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void changeServiceInstanceComponentTypeNotSupported() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version for NON-Component Type = - // Product (e.g. service) - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, - ComponentTypeEnum.SERVICE_INSTANCE, true); - assertEquals("Check response code ", STATUS_CODE_UNSUPPORTED_ERROR, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("null"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, - changeServiceInstanceVersionResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void SeveralServiceInstanceFromSameServiceVersionChangeVersionOnlyForOneServiceInstance() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - serviceDetails_01.setUniqueId(serviceNewUniqueUid); - // get the new VF instance uniqueId after checkout service - RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); - Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); - List serviceComponentInstances = service.getComponentInstances(); - for (ComponentInstance component : serviceComponentInstances) { - if (component.getName().equals(firstVfInstanceName)) { - firstVfInstanceUniqueId = component.getUniqueId(); - } - } - assertTrue(firstVfInstanceUniqueId != null); - // delete resource instance (resourceDetailsVF_01) from Service - RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, - serviceDetails_01, sdncDesignerDetails); - assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Add different VF instance (resourceDetailsVF_02) to Service - RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(restResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get service instance new uniqueId , name and position after checkout - // product - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); - ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); - actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); - actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posX"); - actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), - "posY"); - ComponentInstance componentInstance = ResponseParser - .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Verify that Service instance name and position didn't change after - // changing service instance version - assertTrue(actualServiceInstanceName.equals(expectedServiceName)); - assertTrue(actualPosX.equals(expectedPosX)); - assertTrue(actualPosY.equals(expectedPosY)); - } - - @Test - public void changeServiceInstanceVersionByNonAsdcUser() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); - nonAsdcUser.setUserId("bt760h"); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, nonAsdcUser, ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void changeServiceInstanceVersionEmptyUserId() throws Exception { - // Adding service instance (serviceDetails_01) to product without saving - // Req&Cap - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, - sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Adding service instance (serviceDetails_02) to product AND ---> Save - // Req&Cap - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // check-in product - RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Checkout service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeStatusResponse); - String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - // Check-In service [0.2] - changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeStatusResponse); - // check-out product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeStatusResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); - nonAsdcUser.setUserId(""); - // change service instance to newer version - RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, - serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, nonAsdcUser, ComponentTypeEnum.PRODUCT, true); - assertEquals("Check response code ", STATUS_CODE_MISSING_INFORMATION, - changeServiceInstanceVersionResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), - changeServiceInstanceVersionResponse.getResponse()); - // Check-in product - changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, - LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeStatusResponse); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - //////////////////////////////////// - private void updateNewComponentInstanceId(RestResponse createServiceInstanceResp, String productNewUniqueId) - throws Exception { - String firstServiceInstanceNormalizedName = ResponseParser - .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); - Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); - List componentInstances = product.getComponentInstances(); - for (ComponentInstance component : componentInstances) { - if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { - serviceInstanceToReplaceUniqueId = component.getUniqueId(); - expectedServiceName = component.getName(); - expectedPosX = component.getPosX(); - expectedPosY = component.getPosY(); - } - } - assertTrue(serviceInstanceToReplaceUniqueId != null); - } - - private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception { - RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, - LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, - LifeCycleStatesEnum.CERTIFICATIONREQUEST); - if (restResponse.getErrorCode() == 200) { - restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, - LifeCycleStatesEnum.STARTCERTIFICATION); - } else - return restResponse; - if (restResponse.getErrorCode() == 200) { - restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, - LifeCycleStatesEnum.CERTIFY); - if (restResponse.getErrorCode() == 200) { - String newVersion = ResponseParser.getVersionFromResponse(restResponse); - resourceDetails.setVersion(newVersion); - resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); - resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); - resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); - String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), - "uniqueId"); - resourceDetails.setUniqueId(uniqueIdFromRresponse); - } - } - return restResponse; - } - - private void certifyVf(ResourceReqDetails resource, ResourceReqDetails computeResource, - ResourceReqDetails cpResource) throws Exception { - RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, cpResource, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); - - createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, computeResource, - sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - String toCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); - - RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, - sdncDesignerDetails, resource.getUniqueId()); - ResourceRestUtils.checkSuccess(response); - - String capOwnerId = toCompInstId; - User user = sdncDesignerDetails; - ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE; - - fulfillCpRequirement(resource, fromCompInstId, toCompInstId, capOwnerId, user, containerCompType); - - RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource); - ResourceRestUtils.checkSuccess(changeResourceStateToCertified); - } -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java deleted file mode 100644 index 623b29b8e6..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java +++ /dev/null @@ -1,200 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.rules.TestName; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.GroupingDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; -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.BaseRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.testng.annotations.BeforeMethod; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -public abstract class ProductBaseTest extends ComponentBaseTest { - User productStrategistUser1; - User productStrategistUser2; - User productStrategistUser3; - User productManager1; - User productManager2; - User adminUser; - User designerUser; - - // Category1->Subcategory1->Grouping1 - protected List defaultCategories; - - protected static String auditAction; - protected static ComponentOperationEnum operation; - - public ProductBaseTest(TestName testName, String className) { - super(testName, className); - } - - @BeforeMethod - public void beforeProductTest() throws IOException, Exception { - productStrategistUser1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); - productStrategistUser2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2); - productStrategistUser3 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST3); - productManager1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); - productManager2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2); - adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); - designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); - createDefaultChain(); - } - - private void createDefaultChain() throws Exception { - CategoryDefinition productCategoryDefinition = ElementFactory.getDefaultCategory(); - SubCategoryDefinition productSubCategoryDefinition = ElementFactory.getDefaultSubCategory(); - GroupingDefinition productGroupingDefinition = ElementFactory.getDefaultGroup(); - productCategoryDefinition.addSubCategory(productSubCategoryDefinition); - productSubCategoryDefinition.addGrouping(productGroupingDefinition); - List definitionsList = new ArrayList<>(); - definitionsList.add(productCategoryDefinition); - defaultCategories = createCategoriesChain(definitionsList); - } - - private List createCategoriesChain(List categoryDefinitions) - throws Exception { - for (CategoryDefinition categoryDefinition : categoryDefinitions) { - RestResponse createCategory = CategoryRestUtils.createCategory(categoryDefinition, productStrategistUser1, - PRODUCT_COMPONENT_TYPE); - int status = createCategory.getErrorCode().intValue(); - if (status == BaseRestUtils.STATUS_CODE_CREATED) { - String categoryId = ResponseParser.getUniqueIdFromResponse(createCategory); - categoryDefinition.setUniqueId(categoryId); - } - List subcategories = categoryDefinition.getSubcategories(); - for (SubCategoryDefinition subCategoryDefinition : subcategories) { - RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryDefinition, - categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE); - status = createSubCategory.getErrorCode().intValue(); - if (status == BaseRestUtils.STATUS_CODE_CREATED) { - String subCategoryId = ResponseParser.getUniqueIdFromResponse(createSubCategory); - subCategoryDefinition.setUniqueId(subCategoryId); - } - List groupings = subCategoryDefinition.getGroupings(); - for (GroupingDefinition groupingDefinition : groupings) { - RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition, - subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE); - status = createGroupingRest.getErrorCode().intValue(); - if (status == BaseRestUtils.STATUS_CODE_CREATED) { - String groupingId = ResponseParser.getUniqueIdFromResponse(createGroupingRest); - groupingDefinition.setUniqueId(groupingId); - } - } - } - } - RestResponse allCategories = CategoryRestUtils.getAllCategories(productStrategistUser1, PRODUCT_COMPONENT_TYPE); - Gson gson = new Gson(); - List res = gson.fromJson(allCategories.getResponse(), - new TypeToken>() { - }.getType()); - return res; - } - - // Category1->Subcategory1->[Grouping1, Grouping11] - protected List addSecondGroupingToDefaultCategory() throws Exception { - GroupingDefinition productGroupingDefinition = ElementFactory.getDefaultGroup(); - productGroupingDefinition.setName("Grouping11"); - defaultCategories.get(0).getSubcategories().get(0).addGrouping(productGroupingDefinition); - return createCategoriesChain(defaultCategories); - } - - // Category1->[Subcategory1->[Grouping1, - // Grouping11],Subcategory2->[Grouping12]] - protected List addSubcategoryAndGroupingToDefaultCategory() throws Exception { - GroupingDefinition groupingDefinition1 = ElementFactory.getDefaultGroup(); - groupingDefinition1.setName("Grouping11"); - defaultCategories.get(0).getSubcategories().get(0).addGrouping(groupingDefinition1); - - SubCategoryDefinition subCategory2 = ElementFactory.getDefaultSubCategory(); - subCategory2.setName("Subcategory2"); - GroupingDefinition groupingDefinition2 = ElementFactory.getDefaultGroup(); - groupingDefinition2.setName("Grouping12"); - subCategory2.addGrouping(groupingDefinition2); - defaultCategories.get(0).addSubCategory(subCategory2); - return createCategoriesChain(defaultCategories); - } - - // [Category1->[Subcategory1->[Grouping1, - // Grouping11],Subcategory2->[Grouping12]], - // Category2->[Subcategory1->[Grouping1],Subcategory2->[Grouping1]], - // Category3->[Subcategory1->[Grouping11],Subcategory2->[Grouping11, - // Grouping22]]] - protected List addManyGroupingsDiffCategories() throws Exception { - CategoryDefinition category2 = ElementFactory.getDefaultCategory(); - category2.setName("Category2"); - CategoryDefinition category3 = ElementFactory.getDefaultCategory(); - category3.setName("Category3"); - SubCategoryDefinition subCategory1 = ElementFactory.getDefaultSubCategory(); - subCategory1.setName("Subcategory1"); - SubCategoryDefinition subCategory2 = ElementFactory.getDefaultSubCategory(); - subCategory2.setName("Subcategory2"); - SubCategoryDefinition subCategory1_2 = ElementFactory.getDefaultSubCategory(); - subCategory1_2.setName("Subcategory1"); - SubCategoryDefinition subCategory2_2 = ElementFactory.getDefaultSubCategory(); - subCategory2_2.setName("Subcategory2"); - SubCategoryDefinition subCategory1_3 = ElementFactory.getDefaultSubCategory(); - subCategory1_3.setName("Subcategory1"); - SubCategoryDefinition subCategory2_3 = ElementFactory.getDefaultSubCategory(); - subCategory2_3.setName("Subcategory2"); - - GroupingDefinition groupingDefinition1 = ElementFactory.getDefaultGroup(); - groupingDefinition1.setName("Grouping1"); - GroupingDefinition groupingDefinition11 = ElementFactory.getDefaultGroup(); - groupingDefinition11.setName("Grouping11"); - GroupingDefinition groupingDefinition12 = ElementFactory.getDefaultGroup(); - groupingDefinition12.setName("Grouping12"); - GroupingDefinition groupingDefinition22 = ElementFactory.getDefaultGroup(); - groupingDefinition22.setName("Grouping22"); - - defaultCategories.get(0).getSubcategories().get(0).addGrouping(groupingDefinition11); - subCategory2.addGrouping(groupingDefinition12); - defaultCategories.get(0).addSubCategory(subCategory2); - - defaultCategories.add(category2); - defaultCategories.add(category3); - category2.addSubCategory(subCategory1_2); - category2.addSubCategory(subCategory2_2); - subCategory1_2.addGrouping(groupingDefinition1); - subCategory2_2.addGrouping(groupingDefinition1); - category3.addSubCategory(subCategory1_3); - category3.addSubCategory(subCategory2_3); - subCategory1_3.addGrouping(groupingDefinition11); - subCategory2_3.addGrouping(groupingDefinition11); - subCategory2_3.addGrouping(groupingDefinition22); - return createCategoriesChain(defaultCategories); - } -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java deleted file mode 100644 index 1820315841..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.testng.AssertJUnit.assertEquals; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.enums.AuditJsonKeysEnum; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; -import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; -import org.openecomp.sdc.ci.tests.utils.DbUtils; -import org.openecomp.sdc.ci.tests.utils.general.Convertor; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; -import org.openecomp.sdc.common.api.Constants; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -public class ProductCheckinTest extends ProductLifecycleTest { - - @Rule - public static TestName name = new TestName(); - - public ProductCheckinTest() { - super(name, ProductCheckinTest.class.getName()); - } - - @BeforeClass - public static void staticInit() { - auditAction = CHECKIN_ACTION; - operation = ComponentOperationEnum.CHANGE_STATE_CHECKIN; - } - - @Test - public void checkInProductByCreator() throws Exception { - - String checkinComment = "good checkin"; - RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN, checkinComment); - assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue()); - Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(checkInResponse.getResponse(), - Product.class); - - expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct, - auditAction, productManager1, ActionStatus.OK, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID()); - expectedProductAudit.setCOMMENT(checkinComment); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT); - } - - @Test - public void checkInProductByPM() throws Exception { - - String checkinComment = "good checkin"; - RestResponse response = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN, checkinComment); - assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue()); - - User checkoutUser = productManager2; - response = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue()); - expectedProduct = ResponseParser.parseToObjectUsingMapper(response.getResponse(), Product.class); - - DbUtils.cleanAllAudits(); - checkinComment = "good checkin no 2"; - response = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKIN, - checkinComment); - assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue()); - - Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(response.getResponse(), Product.class); - - expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - expectedProduct.setVersion("0.2"); - expectedProduct.setLastUpdaterUserId(checkoutUser.getUserId()); - expectedProduct.setLastUpdaterFullName(checkoutUser.getFullName()); - - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct, - auditAction, checkoutUser, ActionStatus.OK, "0.2", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID()); - expectedProductAudit.setCOMMENT(checkinComment); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT); - } - - @Test - public void checkInProductByAdmin() throws Exception { - - String checkinComment = "good checkin"; - RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, adminUser, - LifeCycleStatesEnum.CHECKIN, checkinComment); - assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue()); - Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(checkInResponse.getResponse(), - Product.class); - - expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - expectedProduct.setLastUpdaterUserId(adminUser.getUserId()); - expectedProduct.setLastUpdaterFullName(adminUser.getFullName()); - - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct, - auditAction, adminUser, ActionStatus.OK, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID()); - expectedProductAudit.setCOMMENT(checkinComment); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT); - } - - @Test - public void checkInProductByPMNotOwner() throws Exception { - - RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager2, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 403, checkInResponse.getErrorCode().intValue()); - String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(), - productManager1.getLastName(), productManager1.getUserId() }; - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, productManager2, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, "0.1", "0.1", - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - expectedProduct.getUUID(), auditParameters); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - @Test - public void checkInProductByPsRoleNotAllowed() throws Exception { - - RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productStrategistUser1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 409, checkInResponse.getErrorCode().intValue()); - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, productStrategistUser1, ActionStatus.RESTRICTED_OPERATION, "0.1", "0.1", - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - expectedProduct.getUUID()); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - @Test - public void checkInProductNotExist() throws Exception { - String notExisitingUuid = "1234"; - expectedProduct.setUniqueId(notExisitingUuid); - RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 404, checkInResponse.getErrorCode().intValue()); - String[] auditParameters = new String[] { "", "product" }; - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, productManager1, ActionStatus.PRODUCT_NOT_FOUND, Constants.EMPTY_STRING, - Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, auditParameters); - expectedProductAudit.setCURR_STATE(Constants.EMPTY_STRING); - expectedProductAudit.setRESOURCE_NAME(notExisitingUuid); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - @Test - public void checkInProductAlreadyCheckedIn() throws Exception { - RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue()); - DbUtils.cleanAllAudits(); - checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager2, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 409, checkInResponse.getErrorCode().intValue()); - String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(), - productManager1.getLastName(), productManager1.getUserId() }; - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, productManager2, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, "0.1", "0.1", - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, - expectedProduct.getUUID(), auditParameters); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java deleted file mode 100644 index efb4a15255..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.testng.AssertJUnit.assertEquals; - -import java.io.FileNotFoundException; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; -import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; -import org.openecomp.sdc.ci.tests.utils.DbUtils; -import org.openecomp.sdc.ci.tests.utils.Utils; -import org.openecomp.sdc.ci.tests.utils.general.Convertor; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -public class ProductCheckoutTest extends ProductLifecycleTest { - - @Rule - public static TestName name = new TestName(); - - @BeforeClass - public static void staticInit() { - auditAction = CHECKOUT_ACTION; - operation = ComponentOperationEnum.CHANGE_STATE_CHECKOUT; - } - - public ProductCheckoutTest() { - super(name, ProductCheckoutTest.class.getName()); - } - - @Test - public void checkOutProductByPmNotInContacts() throws Exception { - checkOutProductSuccess(productManager2); - } - - @Test - public void checkOutProductByPmInContacts() throws Exception { - checkOutProductSuccess(productManager1); - } - - @Test - public void checkOutProductByAdmin() throws Exception { - checkOutProductSuccess(adminUser); - } - - @Test - public void checkOutProductByPs() throws Exception { - // Changed in 1604 patch - now it's restricted - checkOutProductRestricted(productStrategistUser3); - // checkOutProductSuccess(productStrategistUser3); - } - - @Test - public void checkOutProductByDesignerRoleNotAllowed() throws Exception { - checkOutProductRestricted(designerUser); - } - - @Test - public void checkOutProductAlreadyCheckedOut() throws Exception { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); - Product checkedOutProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - - DbUtils.cleanAllAudits(); - - lcsResponse = LifecycleRestUtils.changeProductState(checkedOutProduct, productManager2, LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkin resource", 403, lcsResponse.getErrorCode().intValue()); - String[] auditParameters = new String[] { checkedOutProduct.getName(), "product", productManager1.getFirstName(), productManager1.getLastName(), productManager1.getUserId() }; - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedOutProduct, auditAction, productManager2, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, "0.2", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, checkedOutProduct.getUUID(), auditParameters); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - private void checkOutProductSuccess(User checkoutUser) throws Exception, FileNotFoundException { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); - - // 0.1 is not highest now - RestResponse prevVersionProductResp = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), productStrategistUser1.getUserId()); - Product prevVersionProduct = ResponseParser.parseToObjectUsingMapper(prevVersionProductResp.getResponse(), Product.class); - Boolean falseParam = false; - assertEquals(falseParam, prevVersionProduct.isHighestVersion()); - - Product checkedOutProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - - expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - expectedProduct.setVersion("0.2"); - expectedProduct.setLastUpdaterUserId(checkoutUser.getUserId()); - expectedProduct.setLastUpdaterFullName(checkoutUser.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedOutProduct, operation); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedOutProduct, auditAction, checkoutUser, ActionStatus.OK, "0.1", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, checkedOutProduct.getUUID()); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - private void checkOutProductRestricted(User checkoutUser) throws Exception, FileNotFoundException { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkin resource", 409, lcsResponse.getErrorCode().intValue()); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, auditAction, checkoutUser, ActionStatus.RESTRICTED_OPERATION, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, expectedProduct.getUUID()); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java deleted file mode 100644 index fe5a6e34f9..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java +++ /dev/null @@ -1,1175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS_DELETE; -import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Rule; -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.ComponentInstance; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest; -import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; -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; -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.ArtifactRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -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.ErrorValidationUtils; -import org.testng.AssertJUnit; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest { - - protected ArtifactReqDetails heatArtifactDetails; - @Rule - public static TestName name = new TestName(); - - public ProductComponentInstanceCRUDTest() { - super(name, ProductComponentInstanceCRUDTest.class.getName()); - } - - @BeforeMethod - public void before() throws Exception { - init(); - createComponents(); - } - - private void createComponents() throws Exception { - - heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); - createAtomicResource(resourceDetailsVFC_01); - changeResourceStateToCertified(resourceDetailsVFC_01); - createAtomicResource(resourceDetailsCP_01); - changeResourceStateToCertified(resourceDetailsCP_01); - createAtomicResource(resourceDetailsVL_01); - changeResourceStateToCertified(resourceDetailsVL_01); - createAtomicResource(resourceDetailsVFC_02); - changeResourceStateToCertified(resourceDetailsVFC_02); - createAtomicResource(resourceDetailsCP_02); - changeResourceStateToCertified(resourceDetailsCP_02); - createAtomicResource(resourceDetailsVL_02); - changeResourceStateToCertified(resourceDetailsVL_02); - createVF(resourceDetailsVF_02); - createVF(resourceDetailsVF_01); - // create check-In services - createService(serviceDetails_01); - createService(serviceDetails_02); - createService(serviceDetails_03); - createProduct(productDetails_01); - createProduct(productDetails_02); - - // addresourceDetailsCP_02 ,resourceDetailsVFC_02 and - // resourceDetailsVL_02 to resourceDetailsVF_02 check-in VF - RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02, sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsCP_02, sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVL_02, sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); - resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - // addresourceDetailsCP_01 ,resourceDetailsVFC_01 and - // resourceDetailsVL_01 to resourceDetailsVF_01 and certify - // resourceDetailsVF_01 - certifyVf(resourceDetailsVF_01); - createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); // serviceDetails_01 - // has - // certified - // VF - createVFInstanceDuringSetup(serviceDetails_02, resourceDetailsVF_02, sdncDesignerDetails); // serviceDetails_02 - // has - // check-in - // VF - restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - } - - // pass - @Test - public void createServiceInstanceTest() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - // DE189427 - @Test(enabled = false) - public void createServiceInstanceFromCheckedOutState() throws Exception { - // can't create instance of checked-out component - RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceInToAnotherServiceInstance() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String uniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, uniqueIdFromResponse, ComponentTypeEnum.PRODUCT); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_NOT_FOUND); - } - - @Test - public void createSeveralServiceInstanceFromSameServices() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void createSeveralServiceInstanceFromDifferentServices() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void createCertifiedServiceInstance() throws Exception { - changeServiceStateToCertified(serviceDetails_01); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceByPm() throws Exception { - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceWithoutVf() throws Exception { - LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncAdminDetails, "0.1", LifeCycleStatesEnum.CHECKIN); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_02, serviceDetails_03, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_02, 1, 0); - } - - @Test - public void createServiceInstanceByNonProductOwner() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails2); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceByNonAsdcUser() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); - ; - nonExistingSdncUser.setUserId("bt1234"); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonExistingSdncUser); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceToNotCheckOutProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - // pass - @Test - public void createServiceInstanceNameIsEmpty() throws Exception { - String expectedServiceInstanceName = serviceDetails_01.getName() + " 1"; - String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1"; - serviceDetails_01.setName(""); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName); - getComponentAndValidateRIs(productDetails_01, 1, 0); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(expectedServiceInstanceName, actualComponentInstance.getName()); - assertEquals((expectedServiceInstancenormalizedName).toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - // pass - @Test - public void createServiceInstanceNameIsNull() throws Exception { - String expectedServiceInstanceName = serviceDetails_01.getName() + " 1"; - String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1"; - serviceDetails_01.setName(null); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName); - getComponentAndValidateRIs(productDetails_01, 1, 0); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(expectedServiceInstanceName, actualComponentInstance.getName()); - assertEquals((expectedServiceInstancenormalizedName).toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - @Test(enabled = false) - public void createServiceInstanceToNonExistingProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, "blabla", ComponentTypeEnum.PRODUCT); - AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, createServiceInstanceResp.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("blabla"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceToNonSupportedComponentType() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.RESOURCE_INSTANCE); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR); - ArrayList varibales = new ArrayList(); - varibales.add("null"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - // pass - @Test - public void createServiceInstancePositionIsEmpty() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - serviceInstanceReqDetails.setPosX(""); - serviceInstanceReqDetails.setPosY(""); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstancePositionIsNull() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - serviceInstanceReqDetails.setPosX(null); - serviceInstanceReqDetails.setPosY(null); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class); - addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceByDesigner() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncDesignerDetails); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void createServiceInstanceUserIdIsEmpty() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); - nonSdncDetails.setUserId(""); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonSdncDetails); - assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - //// Update Service instance - - @Test - public void updateServiceInstanceNameByPm() throws Exception { - // Check-in Product by PM and Check-out by PM - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - // Create service instance by PM - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "abcD"; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance Name ", newName, instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(newName, actualComponentInstance.getName()); - assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - @Test - public void updateServiceInstanceNewNameAndLocation() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "updaatedName100"; - serviceInstanceReqDetails.setPosX("100"); - serviceInstanceReqDetails.setPosY("100"); - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); - assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); - assertEquals(newName, actualComponentInstance.getName()); - assertEquals(newName.toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - @Test(enabled = false) - public void updateServiceInstanceNameRemoveSpacesFromBiginningAndEnd() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = " Abcd "; - String expectedNewName = " Abcd "; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (expectedNewName).toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance Name ", expectedNewName, instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(expectedNewName, actualComponentInstance.getName()); - assertEquals((expectedNewName).toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - // pass - @Test - public void updateServiceInstanceNameAllowedCharacters() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "qwer-TYUIOP_asd_0987654321.Abcd"; - String ExpectedNormalizName = "qwertyuiopasd0987654321abcd"; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", ExpectedNormalizName, instanceNormalizedName); - assertEquals("check Resource Instance Name ", newName, instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(newName, actualComponentInstance.getName()); - assertEquals(ExpectedNormalizName, actualComponentInstance.getNormalizedName()); - - } - - @Test - public void updateInstanceNameInvalidCharacters() throws Exception { - char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',' }; - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "Abcd1"; - String updateName; - for (int i = 0; i < invalidChars.length; i++) { - updateName = newName + invalidChars[i]; - serviceInstanceReqDetails.setName(updateName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT, updateServiceInstanceResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("Service Instance"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), varibales, updateServiceInstanceResponse.getResponse()); - } - } - - // pass - @Test - public void updateInstanceNameMaxLength() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl12345"; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance Name ", newName, instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(newName, actualComponentInstance.getName()); - assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - @Test - public void updateInstanceNameExceedMaxLength() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String expectedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name"); - String expectedNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); - String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456"; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT, updateServiceInstanceResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("Service Instance"); - varibales.add("50"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), varibales, updateServiceInstanceResponse.getResponse()); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(expectedName, actualComponentInstance.getName()); - assertEquals(expectedNormalizedName, actualComponentInstance.getNormalizedName()); - } - - @Test - public void updateServiceInstanceNameEmpty() throws Exception { - // see US534663 In case a PS/PM removes the current service instance - // name then BE has to generate again the "default" service instance - // name - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = ""; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(instanceName, actualComponentInstance.getName()); - assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName()); - } - - // pass - @Test - public void updateServiceInstanceNameNull() throws Exception { - // see US534663 In case a PS/PM removes the current service instance - // name then BE has to generate again the "default" service instance - // name - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = null; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(instanceName, actualComponentInstance.getName()); - assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName()); - } - - @Test - public void updateServiceInstanceCheckedByOtherUser() throws Exception { - // see US534663 In case a PS/PM removes the current service instance - // name then BE has to generate again the "default" service instance - // name - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "blabla"; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails2, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, updateServiceInstanceResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateServiceInstanceResponse.getResponse()); - } - - @Test - public void updateServiceInstance_UserIdIsNonAsdcUser() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "blabla"; - serviceInstanceReqDetails.setName(newName); - User nonSdncUserDetails = new User(); - nonSdncUserDetails.setUserId("bt4567"); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, nonSdncUserDetails, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, updateServiceInstanceResponse.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateServiceInstanceResponse.getResponse()); - } - - @Test - public void updateServiceInstanceNameToAlreadyExisting() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String ServiceName1 = ResponseParser.getNameFromResponse(createServiceInstanceResp); - createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // Update service instance2 name to service instance1 - serviceInstanceReqDetails.setName(ServiceName1); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS, updateServiceInstanceResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("Service Instance"); - varibales.add(ServiceName1); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales, updateServiceInstanceResponse.getResponse()); - } - - @Test - public void updateServiceInstanceForNonExistingProduct() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "blabla"; - serviceInstanceReqDetails.setName(newName); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, "blablabla", ComponentTypeEnum.PRODUCT); - AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, updateServiceInstanceResponse.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(""); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, updateServiceInstanceResponse.getResponse()); - - } - - @Test - public void updateNonExistingServiceInstance() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String newName = "blabla"; - serviceInstanceReqDetails.setName(newName); - serviceInstanceReqDetails.setUniqueId("11111111"); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ArrayList varibales = new ArrayList(); - varibales.add(newName); - varibales.add("service instance"); - AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, updateServiceInstanceResponse.getErrorCode().intValue()); - // need to change ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name() to - // ActionStatus.SERVICE_INSTANCE_NOT_FOUND.name() - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND.name(), varibales, updateServiceInstanceResponse.getResponse()); - } - - @Test - public void updateServiceInstanceLocation() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - serviceInstanceReqDetails.setPosX("50"); - serviceInstanceReqDetails.setPosY("100"); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); - assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); - } - - @Test - public void updateServiceInstanceToNonExistingLocation() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - String nameFromResponse = ResponseParser.getNameFromResponse(createServiceInstanceResp); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - serviceInstanceReqDetails.setPosX("-50"); - serviceInstanceReqDetails.setPosY("-100"); - serviceInstanceReqDetails.setName(nameFromResponse); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); - assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); - assertEquals(nameFromResponse, actualComponentInstance.getName()); - } - - @Test - public void updateServiceInstanceLocationNameIsEmpty() throws Exception { - String expectedServiceInstanceName = serviceDetails_01.getName() + " 2"; - String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "2"; - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - serviceInstanceReqDetails.setPosX("100"); - serviceInstanceReqDetails.setPosY("200"); - serviceInstanceReqDetails.setName(""); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String nameFromResponse = ResponseParser.getNameFromResponse(updateServiceInstanceResponse); - String postX = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posX"); - String postY = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posY"); - assertEquals(nameFromResponse, expectedServiceInstanceName); - assertEquals(postX, "100"); - assertEquals(postY, "200"); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); - assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); - assertEquals(nameFromResponse, actualComponentInstance.getName()); - assertEquals(expectedServiceInstancenormalizedName.toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - // pass - @Test - public void updateServiceInstanceNameToProductName() throws Exception { - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); - RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // ComponentInstance componentInstance = - // ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), - // ComponentInstance.class); - // addCompInstReqCapToExpected(componentInstance, - // ComponentTypeEnum.PRODUCT); - serviceInstanceReqDetails.setName(productDetails_01.getName()); - RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); - String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); - String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); - assertEquals("check Resource Instance normalizedName ", (serviceInstanceReqDetails.getName()).toLowerCase(), instanceNormalizedName); - assertEquals("check Resource Instance Name ", serviceInstanceReqDetails.getName(), instanceName); - // get product and verify that service instanceName is correct - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - assertEquals(serviceInstanceReqDetails.getName(), actualComponentInstance.getName()); - assertEquals((serviceInstanceReqDetails.getName()).toLowerCase(), actualComponentInstance.getNormalizedName()); - } - - //// Delete Service Instance - - @Test - public void deleteAllServiceInstanceFromProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 0, 0); - } - - @Test - public void deleteServiceWhileServiceInstanceExistInProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - // Delete service while service instance of it exist in product - RestResponse deleteServiceResponse = ServiceRestUtils.deleteServiceById(serviceDetails_01.getUniqueId(), sdncDesignerDetails.getUserId()); - assertTrue(deleteServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - // Get product and verify that service instance still exists - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - // ComponentInstance actualComponentInstance = - // actualProduct.getComponentInstances().get(0); - // assertTrue(serviceInstanceUniqueIdFromResponse == - // actualComponentInstance.getUniqueId()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - // pass - @Test - public void deleteServiceInstanceByPm() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void deleteServiceInstanceByPmCreatedByPm() throws Exception { - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void deleteServiceInstanceByPmWhichIsCheckedOutByAnotherPm() throws Exception { - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails2); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - // DE190189 - @Test - public void deleteServiceInstanceByPmCreatedByPs() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - String productOldUniqueId = productDetails_01.getUniqueId(); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get product and get service instance new uniquId - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - String serviceInstanceUniqueId = actualComponentInstance.getUniqueId(); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 0, 0); - } - - // DE190189 - @Test - public void deleteServiceInstanceByAdminCreatedByPs() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - String productOldUniqueId = productDetails_01.getUniqueId(); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse); - updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); - // get product and get service instance new uniquId - RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncAdminDetails.getUserId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); - ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); - String serviceInstanceUniqueId = actualComponentInstance.getUniqueId(); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncAdminDetails); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 0, 0); - } - - @Test - public void createAndDeleteServiceInstanceByAdmin() throws Exception { - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(restResponse); - // productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncAdminDetails); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void deleteServiceInstanceFromNonCheckOutProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void deleteServiceInstanceByDesigner() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncDesignerDetails); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteServiceInstanceByTester() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncTesterDetails); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteServiceInstanceByPsWhichIsCheckedOutByAnotherPs() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPsDetails2); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - // pass - @Test - public void deleteServiceInstanceByNonAsdcUser() throws Exception { - User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); - ; - nonExistingSdncUser.setUserId("bt1234"); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, nonExistingSdncUser); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteServiceInstanceFromNonExistingProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, "1234567890", serviceInstanceUniqueId, ComponentTypeEnum.PRODUCT); - assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND); - ArrayList varibales = new ArrayList(); - varibales.add(""); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteNonExistingServiceInstanceFromProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - // String serviceInstanceUniqueId = - // ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), "1234567890123456unExistingServiceInstance", ComponentTypeEnum.PRODUCT); - assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND); - ArrayList varibales = new ArrayList(); - varibales.add("1234567890123456unExistingServiceInstance"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteServiceInstanceFromNonSupportedComponentType() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.RESOURCE_INSTANCE); - assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR); - ArrayList varibales = new ArrayList(); - varibales.add("null"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, deleteResourceInstanceResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteServiceInstanceComponentTypeIsNotProduct() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.SERVICE); - assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND); - ArrayList varibales = new ArrayList(); - varibales.add(""); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse()); - getComponentAndValidateRIs(productDetails_01, 2, 0); - } - - @Test - public void deleteServiceInstanceUserIdIsEmpty() throws Exception { - User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); - nonSdncDetails.setUserId(""); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, nonSdncDetails); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - @Test - public void deleteCertifiedServiceInstance() throws Exception { - changeServiceStateToCertified(serviceDetails_01); - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); - assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); - getComponentAndValidateRIs(productDetails_01, 1, 0); - } - - //////////////////////////////////// - - private void certifyVf(ResourceReqDetails resource) throws Exception { - RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01, sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); - - createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_02, sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); - - createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01, sdncDesignerDetails); - ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); - String vlCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); - - // Fixing Vl/Cp req/cap - ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE; - User user = sdncDesignerDetails; - fulfillCpRequirement(resource, cpCompInstId, computeCompInstId, computeCompInstId, user, containerCompType); - consumeVlCapability(resource, cpCompInstId, vlCompInstId, cpCompInstId, user, containerCompType); - - RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails, resource.getUniqueId()); - ResourceRestUtils.checkSuccess(response); - RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource); - ResourceRestUtils.checkSuccess(changeResourceStateToCertified); - } - - private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception { - RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(restResponse); - restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST); - if (restResponse.getErrorCode() == 200) { - restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, LifeCycleStatesEnum.STARTCERTIFICATION); - } else - return restResponse; - if (restResponse.getErrorCode() == 200) { - restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, LifeCycleStatesEnum.CERTIFY); - if (restResponse.getErrorCode() == 200) { - String newVersion = ResponseParser.getVersionFromResponse(restResponse); - resourceDetails.setVersion(newVersion); - resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); - resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); - resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); - String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), "uniqueId"); - resourceDetails.setUniqueId(uniqueIdFromRresponse); - } - } - return restResponse; - } - - private RestResponse changeServiceStateToCertified(ServiceReqDetails serviceDetails) throws Exception { - /* - * RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); ResourceRestUtils.checkSuccess(restResponse); - */ - RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST); - if (restResponse.getErrorCode() == 200) { - restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, LifeCycleStatesEnum.STARTCERTIFICATION); - } else - return restResponse; - if (restResponse.getErrorCode() == 200) { - restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, LifeCycleStatesEnum.CERTIFY); - if (restResponse.getErrorCode() == 200) { - serviceDetails.setVersion("1.0"); - serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); - serviceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); - serviceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); - String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), "uniqueId"); - serviceDetails.setUniqueId(uniqueIdFromRresponse); - } - } - return restResponse; - } - - @Test - public void deleteServiceInstanceTest() throws Exception { - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - String compInstId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - - createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 2, 0); - String compInstId2 = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - - RestResponse deleteServiceInstanceResp = deleteServiceInstance(compInstId, productDetails_01, sdncPmDetails1); - ResourceRestUtils.checkDeleteResponse(deleteServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 1, 0); - - deleteServiceInstanceResp = deleteServiceInstance(compInstId2, productDetails_01, sdncPmDetails1); - ResourceRestUtils.checkDeleteResponse(deleteServiceInstanceResp); - getComponentAndValidateRIs(productDetails_01, 0, 0); - } - - @Test - public void returnedServiceInstanceTypeAttributeTest() throws Exception { - String expectedServiceType = ComponentTypeEnum.SERVICE.getValue().toUpperCase(); - - RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); - ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); - String serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); - ComponentInstanceRestUtils.checkComponentInstanceType(createServiceInstanceResp, expectedServiceType); - - RestResponse getProductResp = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPsDetails1.getUserId()); - ProductRestUtils.checkSuccess(getProductResp); - Product productObject = ResponseParser.parseToObjectUsingMapper(getProductResp.getResponse(), Product.class); - List productComponentInstances = productObject.getComponentInstances(); - for (ComponentInstance comp : productComponentInstances) { - String actualOriginType = comp.getOriginType().getValue().toUpperCase(); - assertTrue(expectedServiceType.equals(actualOriginType)); - } - - ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_02); - serviceInstanceReqDetails.setUniqueId(serviceUniqueIdFromResponse); - serviceInstanceReqDetails.setComponentUid(serviceDetails_01.getUniqueId()); - RestResponse updateResourceInstance = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); - ComponentInstanceRestUtils.checkSuccess(updateResourceInstance); - ComponentInstanceRestUtils.checkComponentInstanceType(updateResourceInstance, expectedServiceType); - - } -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java deleted file mode 100644 index 7ac24bdd69..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java +++ /dev/null @@ -1,1711 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; - -import java.util.Arrays; - -import org.json.JSONArray; -import org.json.JSONException; -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; -import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; -import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; -import org.openecomp.sdc.ci.tests.utils.DbUtils; -import org.openecomp.sdc.ci.tests.utils.Utils; -import org.openecomp.sdc.ci.tests.utils.general.Convertor; -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.ProductRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; -import org.openecomp.sdc.common.api.Constants; -import org.testng.annotations.Test; - -public class ProductCreateWithValidationsTest extends ProductBaseTest { - @Rule - public static TestName name = new TestName(); - - public static String INITIAL_PRODUCT_VERSION = "0.1"; - public static String CREATE_AUDIT_ACTION = "Create"; - public String normalizedName; - - public ProductCreateWithValidationsTest() { - super(name, ProductCreateWithValidationsTest.class.getName()); - } - - @Test - public void createProductSuccessValidation() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNotByPmUser() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productStrategistUser1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, - productStrategistUser1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productStrategistUser1, ActionStatus.RESTRICTED_OPERATION, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNotByAsdcUser() throws Exception { - User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); - nonAsdcUser.setUserId("bt750k"); - nonAsdcUser.setFirstName(null); - nonAsdcUser.setLastName(null); - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, nonAsdcUser); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, - nonAsdcUser); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, nonAsdcUser, ActionStatus.RESTRICTED_OPERATION, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductUserIdIsEmpty() throws Exception { - User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); - nonAsdcUser.setUserId(""); - nonAsdcUser.setFirstName(null); - nonAsdcUser.setLastName(null); - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, nonAsdcUser); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, - nonAsdcUser); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, nonAsdcUser, ActionStatus.MISSING_INFORMATION, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationLessThanMinCharacters() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Pro"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, - ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, - null, null, Constants.EMPTY_STRING, "Product", "abbreviated"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationMaxLength() throws Exception { - // Max length = 25 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Qwertyuiop1234567890asdfA"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationExceedMaxLength() throws Exception { - // Max length = 25 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Qwertyuiop1234567890asdfAa"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, - ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, - null, null, Constants.EMPTY_STRING, "Product", "abbreviated"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationEmptyName() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName(""); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", - "abbreviated"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameAlreadyExist() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - // productReqDetails.setName("ProDuct1"); - DbUtils.deleteFromEsDbByPattern("_all"); - createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_ALREADY_EXISTS, - createProduct.getErrorCode().intValue()); - productReqDetails.setVersion("0.1"); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", - productReqDetails.getName()); - constructFieldsForAuditValidation.setCURR_VERSION("0.1"); - constructFieldsForAuditValidation.setCURR_STATE(""); - constructFieldsForAuditValidation.setCURR_STATE("NOT_CERTIFIED_CHECKOUT"); - constructFieldsForAuditValidation.setSERVICE_INSTANCE_ID(null); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationNameIsNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName(null); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", - "abbreviated"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - // DE193857 - @Test(enabled = false) - public void createProductNameValidationAllowedCharacters() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Ac_2@3:4& m=n+b-u.j-u'g#b"); // Bug @:&=+'# - normalizedName = "ac234mnbujugb"; - String expectedProductName = "Ac_2@3:4& M=n+b-u.j-u'g#b"; - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - productReqDetails.setName(expectedProductName); - productReqDetails.setName("Ac_2@3:4& M=n+b-u.j-u'g#b"); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setNormalizedName(normalizedName); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - // DE193857 - @Test(enabled = false) - public void createProductNameValidationREmoveExtraNonAlphanumericChars() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Ac____222----333......asd"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setName("Ac_222-333.asd"); - normalizedName = "ac222333asd"; - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationNotAllowedCharacters() throws Exception { - ExpectedProductAudit constructFieldsForAuditValidation; - char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', - '\\', ',', '$' }; - for (int i = 0; i < invalidChars.length; i++) { - DbUtils.deleteFromEsDbByPattern("_all"); - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("abc" + invalidChars[i]); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", - productManager1); - constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, - CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", - "abbreviated"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - } - - @Test - public void createProductFullNameContainSpecialCharacters() throws Exception { - char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', - '\\', ',', '$' }; - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - for (int i = 0; i < invalidChars.length; i++) { - DbUtils.deleteFromEsDbByPattern("_all"); - productReqDetails.setFullName("abc" + invalidChars[i]); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED, - createProduct.getErrorCode().intValue()); - RestResponse deleteProduct = ProductRestUtils.deleteProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, - deleteProduct.getErrorCode().intValue()); - } - } - - @Test(enabled = false) - public void createProductNameValidationRemoveSpaceFromBeginning() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName(" Qwertyuiop1234567890asdfA"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); - normalizedName = productReqDetails.getName().trim().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test(enabled = false) - public void createProductNameValidationRemoveSpaceFromTheEnd() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Qwertyuiop1234567890asdfA "); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); - normalizedName = productReqDetails.getName().trim().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationStartWithNumber() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("1Qwert"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); - normalizedName = productReqDetails.getName().trim().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationStartWithNonAlphaNumeric() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("_Qwert"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); - normalizedName = productReqDetails.getName().trim().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, - ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, Constants.EMPTY_STRING, Constants.EMPTY_STRING, - null, null, Constants.EMPTY_STRING, "Product", "abbreviated"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - // productReqDetails.setTags(Arrays.asList("abba")); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - // productReqDetails.setName("Abba"); - /* - * String actualNormalizedNameFromResponse = - * ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), - * "normalizedName"); - * assertTrue(actualNormalizedNameFromResponse.equals(normalizedName)); - */ - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameValidationIsEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setFullName(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "full"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameValidationIsNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setFullName(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "full"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameLessThanMinLength() throws Exception { - // Min is 4 characters - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setFullName("abc"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, - ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, - null, null, Constants.EMPTY_STRING, "Product", "full"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameHasMinLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setFullName("abcd"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameHasMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setFullName( - "Abba1234567890asdfghjk l123zxcvbnm432adfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameExceedMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setFullName( - "Abba1234567890asdfghjk l123zxcvbnm432adfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.123"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, - ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, - null, null, Constants.EMPTY_STRING, "Product", "full"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductFullNameRemoveExtraSpaces() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setFullName("Abbaaa a1"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setFullName("Abbaaa a1"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionValidationIsEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setDescription(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_DESCRIPTION, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionValidationIsNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setDescription(null); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_DESCRIPTION, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionValidCharacters01() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionValidCharacters02() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionInValidCharacters() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription("מה"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_DESCRIPTION, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionRemoveSpacesFromBeginning() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription(" abcd12345"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setDescription("abcd12345"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionRemoveSpacesFromTheEnd() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription("abcd 12345 xcvb "); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setDescription("abcd 12345 xcvb"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription( - "Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12asdfghjklzxcvbnmqwertyui"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDescriptionExceedMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setDescription( - "Abxba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12asdfghjklzxcvbnmqwertyui"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "1024"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductTagIsEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product"); - productReqDetails.setTags(Arrays.asList("")); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_FIELD_FORMAT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "tag"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - // DE192351 - @Test - public void createProductTagValidationAllowedCharacters() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Acde2@3:4& m=n+b-u.j-u'g#b")); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductTagsNameValidationProductNameIsNotInTag() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Qwertyuiop1234567890asdfA"); - productReqDetails.setTags(Arrays.asList("Abc")); - normalizedName = productReqDetails.getName().trim().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductSingleTagMaxLength() throws Exception { - // SingleTagMaxLength = 50 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags( - Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345678")); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductSingleTagExceedMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags( - Arrays.asList(productReqDetails.getName(), "Axbba1234567890asdfghjkl123zxcvbnm432asdfgh12345678")); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "50"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductAllTagsMaxLength() throws Exception { - // AllTagsMaxLength = 1024 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags( - Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345")); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductAllTagsExceedMaxLength() throws Exception { - // AllTagsMaxLength = 1024 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags( - Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456")); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "1024"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductDuplicateTagRemoved() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductContactsIsEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - productReqDetails.setContacts(Arrays.asList("")); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_CONTACT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductContactsInvalidFormat() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - productReqDetails.setContacts(Arrays.asList("bt750345")); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_CONTACT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductConvertContactsToLowerCase() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - productReqDetails.setContacts(Arrays.asList(productManager1.getUserId().toUpperCase())); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setContacts(Arrays.asList(productManager1.getUserId().toLowerCase())); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductContactsDoexNotContainTheProductCreator() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - productReqDetails.setContacts(Arrays.asList(productManager2.getUserId())); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setContacts(Arrays.asList(productManager2.getUserId(), productManager1.getUserId())); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductContactsNotAllowedAsdcUsers() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - productReqDetails.setContacts(Arrays.asList(designerUser.getUserId())); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PRODUCT_CONTACT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, - designerUser.getUserId()); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductContactsNotAsdcUser() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); // Bug @:&=+'# - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase(); - String nonAsdcUser = "bh1234"; - productReqDetails.setContacts(Arrays.asList(nonAsdcUser)); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PRODUCT_CONTACT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, nonAsdcUser); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeIsEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_PROJECT_CODE, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeIsNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode(null); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_PROJECT_CODE, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeIsNotNumeric() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode("asdfgh"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeHasnMinCharacters() throws Exception { - // Min =5 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode("12345"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeHasnMaxCharacters() throws Exception { - // Max =10 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode("1234567890"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeExceedMaxCharacters() throws Exception { - // Max =10 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode("12345678901"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductProjectCodeLessThanMinCharacters() throws Exception { - // Max =10 - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setProjectCode("1234"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIconIsEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setIcon(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_ICON, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIconIsNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setIcon(null); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_ICON, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIconMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setIcon("asdfghjklqwertyuiozxcvbfv"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIconExceedMaxLength() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setIcon("asdfghjklqwertyuiozxcvbf12"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "25"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIconAllowedCharacters() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setIcon("a--s-fghjk_q__r1234567890"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIconInValidCharacters() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - String icon = "asdfg"; - char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', - '|', '\\', ',' }; - RestResponse createProduct; - for (int i = 0; i < invalidChars.length; i++) { - productReqDetails.setIcon(icon + invalidChars[i]); - createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", - productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_ICON, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - } - - @Test - public void createProductIsActiveisEmpty() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setActive(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setActive("false"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIsActiveisNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setActive(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - productReqDetails.setActive("false"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIsActiveisFalse() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setActive("false"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIsActiveisHasInvalidValue() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setActive("xfalse"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, - createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_CONTENT, - Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - constructFieldsForAuditValidation.setRESOURCE_NAME(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test - public void createProductIsActiveisTrue() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Product1"); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - productReqDetails.setActive("true"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - ////////////////////////////////////////////// - // DE192424 - @Test - public void createProductNameValidationNormalizationNameWithSpaces() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setName("Abba Emma"); - // productReqDetails.setName("abba emma"); - // productReqDetails.setTags(Arrays.asList("abba emma")); - normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - String actualNormalizedNameFromResponse = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), - "normalizedName"); - assertTrue(actualNormalizedNameFromResponse.equals(normalizedName)); - // productReqDetails.setName("Abba Emma"); - String productUuid = ResponseParser.getUuidFromResponse(createProduct); - compareExpectedAndActualProducts(productReqDetails, createProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProductRes); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( - expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, - "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - private void compareExpectedAndActualProducts(ProductReqDetails productReqDetails, RestResponse createProduct) - throws JSONException { - String productName = ResponseParser.getNameFromResponse(createProduct); - assertTrue(productReqDetails.getName().equals(productName)); - String productIcon = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "icon"); - assertTrue(productReqDetails.getIcon().equals(productIcon)); - String productFullName = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "fullName"); - assertTrue(productReqDetails.getFullName().equals(productFullName)); - String productProjectCode = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "projectCode"); - assertTrue(productReqDetails.getProjectCode().equals(productProjectCode)); - String productIsActive = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "isActive"); - String expectedIsActive = (productReqDetails.getActive() != null ? productReqDetails.getActive() : "false"); - assertTrue(productIsActive.equals(expectedIsActive)); - String productdescription = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "description"); - assertTrue(productReqDetails.getDescription().equals(productdescription)); - String productNormalizedName = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), - "normalizedName"); - assertTrue(normalizedName.equals(productNormalizedName)); - String productContacts = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "contacts"); - JSONArray reciviedContacts = new JSONArray(productContacts); - String actualContact = null; - for (int i = 0; i < reciviedContacts.length(); i++) { - actualContact = reciviedContacts.getString(i); - assertEquals(productReqDetails.getContacts().get(i), actualContact); - } - String productTags = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "tags"); - JSONArray reciviedTages = new JSONArray(productTags); - String actualTag = null; - for (int i = 0; i < reciviedTages.length(); i++) { - actualTag = reciviedTages.getString(i); - assertEquals(productReqDetails.getTags().get(i), actualTag); - } - } - - // END - /////////////////////////////////////////////////////// - @Test - public void createProductSuccessFlow() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, - createProduct.getErrorCode().intValue()); - - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, - getProductRes.getErrorCode().intValue()); - - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(false)); - } - - @Test - public void createProductSetIsActive() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setActive("true"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, - createProduct.getErrorCode().intValue()); - - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), - productManager1.getUserId()); - assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, - getProductRes.getErrorCode().intValue()); - - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, - ComponentOperationEnum.GET_COMPONENT); - assertEquals(actualProduct.getIsActive(), new Boolean(true)); - } - - @Test - public void createProductNoIcon() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setIcon(null); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_DATA, - createProduct.getErrorCode().intValue()); - - } - - @Test - public void createProductNoProjectCode() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - productReqDetails.setProjectCode(null); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_DATA, - createProduct.getErrorCode().intValue()); - - } - -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java deleted file mode 100644 index d91391d967..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java +++ /dev/null @@ -1,2203 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.ci.tests.api.Urls; -import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; -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.ExpectedProductAudit; -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.general.Convertor; -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.CatalogRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -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.ci.tests.utils.validation.ErrorValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; -import org.openecomp.sdc.common.api.Constants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -public class ProductCrudTest extends ProductBaseTest { - private static Logger log = LoggerFactory.getLogger(ProductCrudTest.class.getName()); - @Rule - public static TestName name = new TestName(); - - public static String INITIAL_PRODUCT_VERSION = "0.1"; - public static String CREATE_AUDIT_ACTION = "Create"; - public static String UPDATE_AUDIT_ACTION = "Update"; - public static String COMPONENT_TYPE = "Product"; - - private ProductReqDetails productReqDetails; - private RestResponse createProduct; - private Product product; - - public ProductCrudTest() { - super(name, ProductCrudTest.class.getName()); - } - - @Test // (enabled=false) - public void createAndGetAll() throws Exception { - createProductAndGet(UserRoleEnum.DESIGNER); - } - - private void createProductAndGet(UserRoleEnum user) throws Exception, IOException { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - - RestResponse catalog = CatalogRestUtils.getCatalog(user.getUserId()); - assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_SUCCESS, catalog.getErrorCode().intValue()); - - try { - JsonElement jElement = new JsonParser().parse(catalog.getResponse()); - JsonObject jObject = jElement.getAsJsonObject(); - JsonArray products = (JsonArray) jObject.get("products"); - assertEquals("Check product array size", 1, products.size()); - Iterator iter = products.iterator(); - while (iter.hasNext()) { - JsonElement next = iter.next(); - Product product = ResponseParser.parseToObjectUsingMapper(next.toString(), Product.class); - assertNotNull(product); - assertEquals("Check product name", productReqDetails.getName(), product.getName()); - // Map allVersions = product.getAllVersions(); - // assertEquals("Check product name", 1, allVersions.size()); - } - - } catch (Exception e) { - log.debug("exception", e); - } - } - - @Test - public void getAllNoProcduts() throws Exception { - - RestResponse catalog = CatalogRestUtils.getCatalog(); - assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_SUCCESS, catalog.getErrorCode().intValue()); - - try { - JsonElement jElement = new JsonParser().parse(catalog.getResponse()); - JsonObject jObject = jElement.getAsJsonObject(); - JsonArray products = (JsonArray) jObject.get("products"); - assertEquals("Check product array size", 0, products.size()); - } catch (Exception e) { - log.debug("exception", e); - } - - } - - @Test - public void getAllNoAttHeader() throws Exception { - String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort()); - - List headersToRemove = new ArrayList(); - headersToRemove.add(HttpHeaderEnum.USER_ID.getValue()); - - RestResponse catalog = CatalogRestUtils.sendGetAndRemoveHeaders(url, null, headersToRemove); - assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, catalog.getErrorCode().intValue()); - - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), catalog.getResponse()); - } - - @Test - public void getAllWrongUser() throws Exception { - RestResponse catalog = CatalogRestUtils.getCatalog("kj8976"); - assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, catalog.getErrorCode().intValue()); - - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), catalog.getResponse()); - } - - @Test // (enabled=false) - public void getAllWithProductStrategist_User() throws Exception { - createProductAndGet(UserRoleEnum.PRODUCT_STRATEGIST1); - } - - @Test // (enabled=false) - public void getAllWithProductManager_User() throws Exception { - createProductAndGet(UserRoleEnum.PRODUCT_MANAGER1); - } - - @Test // (enabled=false) - public void createProductNoCategories() throws Exception { - createProductWithCategories(null); - } - - @Test // (enabled=false) - public void createProductOneGrouping() throws Exception { - // Category1->[Subcategory1->[Grouping1]] - createProductWithCategories(defaultCategories); - } - - @Test // (enabled=false) - public void createProductTwoGroupingsSameSubCategory() throws Exception { - // Category1->Subcategory1->[Grouping1, Grouping11] - List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); - createProductWithCategories(addSecondGroupingToDefaultCategory); - } - - @Test // (enabled=false) - public void createProductTwoSubsDifferentGroupings() throws Exception { - // Category1->[Subcategory1->[Grouping1, - // Grouping11],Subcategory2->[Grouping12]] - List addSubcategoryAndGroupingToDefaultCategory = addSubcategoryAndGroupingToDefaultCategory(); - createProductWithCategories(addSubcategoryAndGroupingToDefaultCategory); - } - - @Test // (enabled=false) - public void createManyGroupingsDiffCategories() throws Exception { - // [Category1->[Subcategory1->[Grouping1, - // Grouping11],Subcategory2->[Grouping12]], - // Category2->[Subcategory1->[Grouping1],Subcategory2->[Grouping1]], - // Category3->[Subcategory1->[Grouping11],Subcategory2->[Grouping11, - // Grouping22]]] - List addSubcategoryAndGroupingToDefaultCategory = addManyGroupingsDiffCategories(); - createProductWithCategories(addSubcategoryAndGroupingToDefaultCategory); - } - - @Test // (enabled=false) - public void createProductEmptyUserId() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - User emptyUser = new User(); - emptyUser.setUserId(""); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, emptyUser); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, emptyUser); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, emptyUser, ActionStatus.MISSING_INFORMATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, - null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test // (enabled=false) - public void createProductNonExistingUserId() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - User notExistingUser = new User(); - notExistingUser.setUserId("jj6444"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, notExistingUser); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, notExistingUser); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, notExistingUser, ActionStatus.RESTRICTED_OPERATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, - null, null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test // (enabled=false) - public void createProductInvalidJson() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct_Invalid_Json(productManager1.getUserId()); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, productManager1); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_CONTENT, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, - null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setRESOURCE_NAME(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test // (enabled=false) - public void createProductAdminRoleNotAllowed() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - User wrongRole = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, wrongRole); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, wrongRole); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, wrongRole, ActionStatus.RESTRICTED_OPERATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, - null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test // (enabled=false) - public void createProductProductStrategistRoleNotAllowed() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - User wrongRole = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST3); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, wrongRole); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, createProduct.getErrorCode().intValue()); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, wrongRole); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, wrongRole, ActionStatus.RESTRICTED_OPERATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, - null, Constants.EMPTY_STRING); - constructFieldsForAuditValidation.setCURR_VERSION(""); - constructFieldsForAuditValidation.setCURR_STATE(""); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - @Test // (enabled=false) - public void getProductSuccessFlow() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue()); - - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.GET_COMPONENT); - } - - @Test // (enabled=false) - public void getNonExistedProduct() throws Exception { - - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue()); - - Product product = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); - assertEquals("Assert on product icon", "Product1", product.getName()); - - RestResponse deleteProductRes = ProductRestUtils.deleteProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code for deletign Product", BaseRestUtils.STATUS_CODE_SUCCESS, deleteProductRes.getErrorCode().intValue()); - - RestResponse getProductAfterDeleteRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code after getting deleted Product", BaseRestUtils.STATUS_CODE_NOT_FOUND, getProductAfterDeleteRes.getErrorCode().intValue()); - } - - @Test // (enabled=false) - public void getProductMissingHeader() throws Exception { - - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - - productManager1.setUserId(null); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code after getting created Producuct with UserId extracted from header", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, getProductRes.getErrorCode().intValue()); - - } - - @Test // (enabled=false) - public void getProductNonExistingUser() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - - productManager1.setUserId("bt1111"); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code after getting created Producuct with non exsisting user", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, getProductRes.getErrorCode().intValue()); - } - - @Test // (enabled=false) - public void createProductAndGetProductWithDifferentUser() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - User sdncProductStrategistUserAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), sdncProductStrategistUserAdminDetails.getUserId()); - assertEquals("Check response code after getting created Product different user role", BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue()); - } - - // US594753 - Update Product metadata - - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductAllFieldsByPM() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - // Update product - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("NewProductName"); - List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); - productReqDetails.setFullName("New Full name"); - productReqDetails.setActive("false"); - productReqDetails.setContacts(Arrays.asList(productManager2.getUserId().toLowerCase(), productManager1.getUserId().toLowerCase())); - productReqDetails.setDescription("New Product Description"); - productReqDetails.setIcon("asdfghjklqwertyuiozxcvbfv"); - productReqDetails.setProjectCode("98765"); - productReqDetails.setCategories(addSecondGroupingToDefaultCategory); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), - // productOldName)); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductByPS() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("New discription"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productStrategistUser1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateProduct.getResponse()); - } - - @Test // (enabled=false) - public void updateProductByAdmin() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("New discription"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, designerUser); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateProduct.getResponse()); - } - - @Test // (enabled=false) - public void updateProductByNonPmUser() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - // Update product name - productReqDetails.setDescription("New discription"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, designerUser); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateProduct.getResponse()); - } - - @Test // (enabled=false) - public void updateProductByNonAsdcUser() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - // Update product name - productReqDetails.setDescription("New discription"); - User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); - nonAsdcUser.setUserId("bt789k"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, nonAsdcUser); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateProduct.getResponse()); - } - - @Test // (enabled=false) - public void updateProductUserIdIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - // Update product name - productReqDetails.setDescription("New discription"); - User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); - nonAsdcUser.setUserId(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, nonAsdcUser); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), updateProduct.getResponse()); - } - - @Test // (enabled=false) - public void updateProductByNonProductOwner() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("New discription"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.GET_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNotInCheckoutState() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - // Update product name - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(changeProductLifeCycle.getResponse(), "lastUpdateDate"); - expectedProduct.setLastUpdateDate(Long.parseLong(valueFromJsonResponse)); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNameIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("abbreviated"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNameIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager2, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - // List tags = productReqDetails.getTags(); - // tags.removeAll(tags); - productReqDetails.setTags(new ArrayList<>()); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName(null); // no update will be performed - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); - ProductRestUtils.checkSuccess(updateProduct); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager2); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(product.getName().toLowerCase()); - expectedProduct.setName(product.getName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNameLessThanMinLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("ABC"); // no update will be performed - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("abbreviated"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductNameHasMinLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager2, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("NewP"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - productReqDetails.setLastUpdaterUserId(productManager2.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager2.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager2); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - // DE193857 - Normalized Name is not removing special characters - @Test(enabled = false) - public void updateProductNameMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - // Update product name - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("Ac_2B3U4k mSKnob-u.j-uGgP"); - String newNormalizedName = "ac2b3u4kmsknobujuggp"; - String newName = "Ac_2B3U4k MSKnob-u.j-uGgP"; - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setTags(Arrays.asList(newName)); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(newNormalizedName); - expectedProduct.setName(newName); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNameExceedMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("Ac_2B3U4k mSKnob-u.j-uGgPx"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("abbreviated"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNameAlreadyExist() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2); - ProductRestUtils.checkCreateResponse(createProduct); - Product product1 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product1, productManager2, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setName("Product2000"); - // productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2); - ProductRestUtils.checkCreateResponse(createProduct); - Product product2 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product2, productManager2, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product2, productManager2, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product2.getUniqueId()); - productReqDetails.setUUID(product2.getUUID()); - productReqDetails.setName(product1.getName()); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_ALREADY_EXISTS, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add(product1.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager2.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product2.getUniqueId()); - expectedProduct.setVersion(product2.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // DE193857 - Normalized Name is not removing special characters - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductNameAllowedCharacters() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - // Update product name - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("A_BU4k m&K=o#b-u.j-uG'g+P"); // Allowed - // characters - // [a-z,A-Z,0-9] - // , ‘ ‘ - // (space), - // ampersand - // "&", dash - // “-“, plus - // "+", period - // ".", - // apostrophe - // "'", hashtag - // "#", equal - // "=", period - // ":", at "@", - // and - // underscore - // "_" - String newNormalizedName = "abu4km&kobujuggp"; - String newName = "A_BU4k M&K=o#b-u.j-uG'g+P"; - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setTags(Arrays.asList(newName)); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(newNormalizedName); - expectedProduct.setName(newName); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductNameRemoveSpaceFromBeginning() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName(" asdfg"); - String newNormalizedName = "asdfg"; - String newName = "Asdfg"; - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // productReqDetails.setTags(Arrays.asList(newName, productOldName)); - productReqDetails.setTags(Arrays.asList(newName)); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(newNormalizedName); - expectedProduct.setName(newName); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductNameRemoveSpaceFromEnd() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("asdfg fc "); - String newNormalizedName = "asdfgfc"; - String newName = "Asdfg Fc"; - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // productReqDetails.setTags(Arrays.asList(newName, productOldName)); - productReqDetails.setTags(Arrays.asList(newName)); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(newNormalizedName); - expectedProduct.setName(newName); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - //// DE193857 - Normalized Name is not removing special characters - // If user update "product name" we need to remove the old product name from - //// "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductNameRemoveExtraNonAlphanumericChars() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("A__k &&==##---u..hG'''+++"); - String newNormalizedName = "akhg"; - String newName = "A_k &=#-u.hG'+"; - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // productReqDetails.setTags(Arrays.asList(newName, productOldName)); - productReqDetails.setTags(Arrays.asList(newName)); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(newNormalizedName); - expectedProduct.setName(newName); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // If user update "product name" we need to remove the old product name from - // "Tags" and add the new product name instead - will handled in mew US - @Test(enabled = false) - public void updateProductNameValidationStartWithNumber() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("1000Ab"); - String newNormalizedName = productReqDetails.getName().toLowerCase(); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); - // productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), - // productOldName)); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setNormalizedName(newNormalizedName); - expectedProduct.setName(productReqDetails.getName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductNameValidationStartWithNonAlphaNumeric() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setName("_1000Ab"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("abbreviated"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNameIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("full"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNameIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setNormalizedName(product.getNormalizedName()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setFullName(product.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNameHasMinLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName("asdc"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setNormalizedName(product.getNormalizedName()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setFullName(productReqDetails.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNameHasMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName("1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setNormalizedName(product.getNormalizedName()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setFullName(productReqDetails.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNamelessThanMinLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName("123"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("full"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNameExceedMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName("1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjkx"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("full"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - // DE193947 - @Test - public void updateProductFullNameWithSpecialCharacters() throws Exception { - char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',', '$', '#', '@', '+' }; - String fullName = "avbng"; - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - for (int i = 0; i < invalidChars.length; i++) { - productReqDetails.setFullName(fullName + invalidChars[i]); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, updateProduct.getErrorCode().intValue()); - } - } - - @Test // (enabled=false) - public void updateProductFullNameValidCharactersCharacters01() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setNormalizedName(product.getNormalizedName()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setFullName("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductFullNameRemoveExtraSpaces() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setFullName("Abbaaa a1"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setNormalizedName(product.getNormalizedName()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setFullName("Abbaaa a1"); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test(enabled = false) - public void updateProductDescriptionValidCharacters01() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionValidCharacters02() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionInValidCharacters() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("מה"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionRemoveSpacesFromBeginning() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription(" abcd12345 g"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setDescription("abcd12345 g"); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionRemoveSpacesFromTheEnd() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setDescription("abcd12345 gdf "); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setDescription("abcd12345 gdf"); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - String description = "1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfg"; - productReqDetails.setDescription(description); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setDescription(description); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductDescriptionExceedMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - String description = "01234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfg"; - productReqDetails.setDescription(description); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("1024"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductTagIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList("")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - varibales.add("tag"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductTagIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setTags(product.getTags()); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductTagsNameValidationProductNameIsNotInTag() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList("Abc")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME.name(), new ArrayList(), updateProduct.getResponse()); - } - - @Test // (enabled=false) - public void createProductSingleTagMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345678")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setTags(productReqDetails.getTags()); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductSingleTagExceedMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456788")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("50"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductAllTagsMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setTags(productReqDetails.getTags()); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductAllTagsExceedMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", - "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add("1024"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductTagsDuplicateTagRemoved() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "KoKo", "KoKo")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata updated - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setTags(Arrays.asList(productReqDetails.getName(), "KoKo")); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductContactsIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setContacts(Arrays.asList("")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductContactsIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setContacts(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductContactsInvalidFormat() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setContacts(Arrays.asList("bt750345")); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(COMPONENT_TYPE); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductConvertContactsToLowerCase() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setContacts(Arrays.asList(productManager2.getUserId().toUpperCase())); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setContacts(Arrays.asList(productManager2.getUserId().toLowerCase(), productManager1.getUserId())); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductContactsNotAllowedAsdcUsers() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setContacts(Arrays.asList(productStrategistUser1.getUserId())); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(productStrategistUser1.getUserId()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PRODUCT_CONTACT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductContactsNotAsdcUser() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - String nonAsdcUserUserId = "bt567h"; - productReqDetails.setContacts(Arrays.asList(nonAsdcUserUserId)); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList varibales = new ArrayList(); - varibales.add(nonAsdcUserUserId); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PRODUCT_CONTACT.name(), varibales, updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_PROJECT_CODE.name(), new ArrayList(), updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setProjectCode(product.getProjectCode()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeLessThanMinCharacters() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode("9870"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList(), updateProduct.getResponse()); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeHasnMinCharacters() throws Exception { // min - // =5 - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode("98700"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setProjectCode(productReqDetails.getProjectCode()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeHasnMaxCharacters() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode("1234567890"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setProjectCode(productReqDetails.getProjectCode()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeExceedMaxCharacters() throws Exception {// Max - // =10 - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode("12345678901"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList(), updateProduct.getResponse()); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setProjectCode(product.getProjectCode()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductProjectCodeIsNotNumeric() throws Exception { - // Max =10 - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setProjectCode("1234a"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList(), updateProduct.getResponse()); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setProjectCode(product.getProjectCode()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIconIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setIcon(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList variables = new ArrayList(); - variables.add(COMPONENT_TYPE); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables, updateProduct.getResponse()); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIcon(product.getIcon()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIconIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setIcon(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - // Get Product and verify that metadata didn't change - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIcon(product.getIcon()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIconMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setIcon("A_a-1-2--b__BB1234567890A"); // Max length = - // 25 - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIcon(productReqDetails.getIcon()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIconExceedMaxLength() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setIcon("A_a-1-2--b__BB1234567890A_"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList variables = new ArrayList(); - variables.add(COMPONENT_TYPE); - variables.add("25"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT.name(), variables, updateProduct.getResponse()); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIcon(product.getIcon()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIconInValidCharacters() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - String icon = "asdfg"; // Allowed characters [a-zA-Z0-9], dash (‘-‘), - // underscore (‘_’). - char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',' }; - RestResponse updateProduct; - for (int i = 0; i < invalidChars.length; i++) { - productReqDetails.setIcon(icon + invalidChars[i]); - updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ArrayList variables = new ArrayList(); - variables.add(COMPONENT_TYPE); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), variables, updateProduct.getResponse()); - } - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIcon(product.getIcon()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIsActiveIsEmpty() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setActive(""); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIsActive(false); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIsActiveIsTrue() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setActive("true"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIsActive(true); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIsActiveIsNull() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); - productReqDetails.setActive("true"); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setActive(null); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIsActive(true); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIsActiveIsFalse() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setActive("false"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - expectedProduct.setIsActive(false); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductIsActiveHasInvalidValue() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setActive("eeeee"); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), updateProduct.getResponse()); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue()); - RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - ProductRestUtils.checkSuccess(getProduct); - Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - expectedProduct.setUniqueId(product.getUniqueId()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); - expectedProduct.setVersion(product.getVersion()); - expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); - expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductAssociations() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); - productReqDetails.setCategories(addSecondGroupingToDefaultCategory); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setCategories(productReqDetails.getCategories()); - expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductAssociations02() throws Exception { - List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); // Category1->Subcategory1->[Grouping1, - // Grouping11] - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(addSecondGroupingToDefaultCategory); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - List defaultCategory = addSubcategoryAndGroupingToDefaultCategory(); // Category1->[Subcategory1->[Grouping1, - // Grouping11],Subcategory2->[Grouping12]] - productReqDetails.setCategories(defaultCategory); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setCategories(productReqDetails.getCategories()); - expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductRemoveAllAssociations() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - List defaultCategory = new ArrayList(); - productReqDetails.setCategories(defaultCategory); - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setCategories(productReqDetails.getCategories()); - expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - @Test // (enabled=false) - public void updateProductAssociationsCategotyIsNull() throws Exception { - createProducrByPSAndCheckIn(); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - productReqDetails.setUniqueId(product.getUniqueId()); - productReqDetails.setUUID(product.getUUID()); - productReqDetails.setCategories(null);// product categories will not be - // updated - RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); - ProductRestUtils.checkSuccess(updateProduct); - productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); - productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); - expectedProduct.setUUID(product.getUUID()); - expectedProduct.setInvariantUUID(product.getInvariantUUID()); - expectedProduct.setCategories(product.getCategories()); - expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT); - } - - //////////////////////////////////////////////////////////////////////// - - private void createProductWithCategories(List categoryDefinitions) throws Exception { - ProductReqDetails productReqDetails = (categoryDefinitions != null ? ElementFactory.getDefaultProduct(categoryDefinitions) : ElementFactory.getDefaultProduct()); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - Product actualProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - String actualUuid = ResponseParser.getUuidFromResponse(createProduct); - Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, productManager1); - String normalizedNameFomJsonResponse = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "normalizedName"); - expectedProduct.setNormalizedName(normalizedNameFomJsonResponse); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.CREATE_COMPONENT); - ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, "0.1", null, - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, actualUuid); - AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); - } - - private void createProducrByPSAndCheckIn() throws Exception { - productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); - createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - ProductRestUtils.checkCreateResponse(createProduct); - product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.checkSuccess(changeProductLifeCycle); - } - - @Test - public void checkInvariantUuidIsImmutable() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!"; - productReqDetails.setInvariantUUID(invariantUuidDefinedByUser); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - BaseRestUtils.checkStatusCode(createProduct, "create request failed", false, 201); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - Product ProductCreation = ResponseParser.convertProductResponseToJavaObject(createProduct.getResponse()); - String invariantUUIDcreation = ProductCreation.getInvariantUUID(); - - // validate get response - RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId()); - BaseRestUtils.checkSuccess(getProductRes); - Product productGetting = ResponseParser.convertProductResponseToJavaObject(getProductRes.getResponse()); - String invariantUUIDgetting = productGetting.getInvariantUUID(); - assertEquals(invariantUUIDcreation, invariantUUIDgetting); - - // Update Product with new invariant UUID - RestResponse restResponseUpdate = ProductRestUtils.updateProduct(productReqDetails, productManager1); - BaseRestUtils.checkSuccess(restResponseUpdate); - Product updatedProduct = ResponseParser.convertProductResponseToJavaObject(restResponseUpdate.getResponse()); - String invariantUUIDupdating = updatedProduct.getInvariantUUID(); - assertEquals(invariantUUIDcreation, invariantUUIDupdating); - - // Do checkin - RestResponse restResponseCheckin = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKIN); - BaseRestUtils.checkSuccess(restResponseCheckin); - Product checkinProduct = ResponseParser.convertProductResponseToJavaObject(restResponseCheckin.getResponse()); - String invariantUUIDcheckin = checkinProduct.getInvariantUUID(); - String version = checkinProduct.getVersion(); - assertEquals(invariantUUIDcreation, invariantUUIDcheckin); - assertEquals(version, "0.1"); - - // Do checkout - RestResponse restResponseCheckout = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKOUT); - BaseRestUtils.checkSuccess(restResponseCheckout); - Product checkoutProduct = ResponseParser.convertProductResponseToJavaObject(restResponseCheckout.getResponse()); - String invariantUUIDcheckout = checkoutProduct.getInvariantUUID(); - version = checkoutProduct.getVersion(); - assertEquals(invariantUUIDcreation, invariantUUIDcheckout); - assertEquals(version, "0.2"); - - } - - // US672129 Benny - private void getProductValidateInvariantUuid(String productUniqueId, String invariantUUIDcreation) throws Exception { - RestResponse getProduct = ProductRestUtils.getProduct(productUniqueId, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); - assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getProduct.getErrorCode().intValue()); - assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(getProduct)); - } - - @Test // invariantUUID generated when the component is created and never - // changed - public void productInvariantUuid() throws Exception { - ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); - String invariantUuidDefinedByUser = "12345"; - productReqDetails.setInvariantUUID(invariantUuidDefinedByUser); - RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); - assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue()); - // invariantUUID generated when the component is created and never - // changed - String invariantUUIDcreation = ResponseParser.getInvariantUuid(createProduct); - getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); - // Update Product with new invariant UUID - RestResponse restResponse = ProductRestUtils.updateProduct(productReqDetails, productManager1); - assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); - getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); - // Checkin - restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKIN); - assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); - assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); - getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); - // Checkout - restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKOUT); - assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); - assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); - getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); - - // UnDo-CheckOut - restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); - assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); - getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); - - } - -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java deleted file mode 100644 index aebea697b2..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -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.ProductRestUtils; -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.validation.ProductValidationUtils; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class ProductGetFollowedTest extends ProductBaseTest { - - protected Product product200; - protected Product product400; - - private ProductReqDetails productDetails200; - private ProductReqDetails productDetails400; - - @Rule - public static TestName name = new TestName(); - - public ProductGetFollowedTest() { - super(name, ProductGetFollowedTest.class.getName()); - } - - @BeforeMethod - public void init() throws Exception { - createProducts(); - } - - @Test - public void followedPageTest() throws Exception { // Actions - RestResponse changeLifeCycleResponse; - changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeLifeCycleResponse); - changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeLifeCycleResponse); - // Expected users Followed page - ProductValidationUtils.checkUserFollowedPage(productManager1, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); - ProductValidationUtils.checkUserFollowedPage(productManager2, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); - } - - @Test - public void followedPagePmCheckedOutProductWasCheckInByOtherPm() throws Exception { - ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.changeProductLifeCycle(product400, productManager1, LifeCycleStatesEnum.CHECKOUT); - RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager2, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeLifeCycleResponse); - - ProductValidationUtils.checkUserFollowedPage(productManager1, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); - } - - @Test - public void followedPagePmCheckInProduct02() throws Exception { - ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); - - ProductValidationUtils.checkUserFollowedPage(productManager1, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); - ProductValidationUtils.checkUserFollowedPage(productManager2, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); - } - - @Test - public void followedPageAdminCheckoutProductWasCheckedinByPm() throws Exception { - ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); - RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeLifeCycleResponse); - - ProductValidationUtils.checkUserFollowedPage(productManager1, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); - } - - @Test - public void followedPageAdminCheckInProduct() throws Exception { - ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKOUT); - RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKIN); - ResourceRestUtils.checkSuccess(changeLifeCycleResponse); - - ProductValidationUtils.checkUserFollowedPage(productManager1, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); - } - - @Test - public void followedPagePmCheckoutProductWasCheckedinByAdmin() throws Exception { - ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); - ProductRestUtils.changeProductLifeCycle(product200, adminUser, LifeCycleStatesEnum.CHECKOUT); - ProductRestUtils.changeProductLifeCycle(product200, adminUser, LifeCycleStatesEnum.CHECKIN); - RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager2, LifeCycleStatesEnum.CHECKOUT); - ResourceRestUtils.checkSuccess(changeLifeCycleResponse); - - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product200); - ProductValidationUtils.checkUserFollowedPage(productManager2, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); - ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); - } - - private void createProducts() throws Exception { - // PM1 (Product manager) create :PR200 (check In State) - // PM2 (Product manager) create :PR400 (check In State) - - productDetails200 = ElementFactory.getDefaultProduct("CiProd200", defaultCategories); - productDetails400 = ElementFactory.getDefaultProduct("CiProd400", defaultCategories); - - RestResponse createProduct = ProductRestUtils.createProduct(productDetails200, productManager1); - ResourceRestUtils.checkCreateResponse(createProduct); - product200 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - - createProduct = ProductRestUtils.createProduct(productDetails400, productManager2); - ResourceRestUtils.checkCreateResponse(createProduct); - product400 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - } - -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java deleted file mode 100644 index 26bb3e29e9..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.testng.AssertJUnit.assertEquals; - -import org.junit.rules.TestName; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; -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.BaseRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.testng.annotations.BeforeMethod; - -public abstract class ProductLifecycleTest extends ProductBaseTest { - - protected static final String CHECKIN_ACTION = "Checkin"; - protected static final String CHECKOUT_ACTION = "Checkout"; - protected static final String UNDO_CHECKOUT_ACTION = "UndoCheckout"; - - protected Product expectedProduct; - - public ProductLifecycleTest(TestName testName, String className) { - super(testName, className); - } - - @BeforeMethod - public void init() throws Exception { - ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories); - RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productManager1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, - createProduct.getErrorCode().intValue()); - expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - } -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java deleted file mode 100644 index 479dbb9436..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.log4j.lf5.util.ResourceUtils; -import org.junit.Before; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; -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.UserRoleEnum; -import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; -import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; -import org.openecomp.sdc.ci.tests.utils.DbUtils; -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.ComponentInstanceRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -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; - -public class ProductTestBase extends ProductBaseTest { - - public ProductTestBase(TestName testName, String className) { - super(testName, className); - } - - protected ResourceReqDetails downloadResourceDetails; - protected ServiceReqDetails serviceDetails; - protected ComponentInstanceReqDetails resourceInstanceReqDetails; - protected User sdncUserDetails; - protected ArtifactReqDetails heatArtifactDetails; - protected ArtifactReqDetails defaultArtifactDetails; - protected ResourceUtils resourceUtils; - protected ArtifactUtils artifactUtils; - protected Resource resource; - protected Service service; - protected Product product; - - // protected static ServiceUtils serviceUtils = new ServiceUtils(); - - @Before - public void before() throws Exception { - - initializeMembers(); - createComponents(); - - } - - public void initializeMembers() throws IOException, Exception { - - downloadResourceDetails = ElementFactory.getDefaultResource(); - serviceDetails = ElementFactory.getDefaultService(); - sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); - heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); - resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); - - } - - protected void createComponents() throws Exception { - - RestResponse response = ResourceRestUtils.createResource(downloadResourceDetails, sdncUserDetails); - assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); - assertNotNull("resource uniqueId is null:", downloadResourceDetails.getUniqueId()); - - ArtifactReqDetails heatArtifactDetails = ElementFactory - .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); - response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncUserDetails, - downloadResourceDetails.getUniqueId()); - assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), - response.getErrorCode() == 200); - - // certified resource - response = LifecycleRestUtils.certifyResource(downloadResourceDetails); - assertTrue("certify resource request returned status:" + response.getErrorCode(), - response.getErrorCode() == 200); - - response = ResourceRestUtils.getResource(downloadResourceDetails.getUniqueId()); - assertTrue("response code is not 200, returned: " + response.getErrorCode(), response.getErrorCode() == 200); - resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); - - response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); - assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); - assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId()); - - // add resource instance with HEAT deployment artifact to the service - resourceInstanceReqDetails.setComponentUid(downloadResourceDetails.getUniqueId()); - response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncUserDetails, - serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); - assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201); - - // certified service - response = LifecycleRestUtils.certifyService(serviceDetails); - assertTrue("certify service request returned status:" + response.getErrorCode(), - response.getErrorCode() == 200); - - response = ServiceRestUtils.getService(serviceDetails, sdncUserDetails); - assertTrue("response code is not 200, returned: " + response.getErrorCode(), response.getErrorCode() == 200); - service = ResponseParser.convertServiceResponseToJavaObject(response.getResponse()); - - DbUtils.cleanAllAudits(); - - ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories); - RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productStrategistUser1); - assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, - createProduct.getErrorCode().intValue()); - product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); - - // add service instance to product - // - - } -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java deleted file mode 100644 index 412e6fd92d..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.model.ArtifactUiDownloadData; -import org.openecomp.sdc.ci.tests.utils.Decoder; -import org.openecomp.sdc.ci.tests.utils.Utils; -import org.testng.annotations.Test; - -import com.google.gson.Gson; - -public class ProductToscaYamlGenerationTest extends ProductTestBase { - - @Rule - public static TestName name = new TestName(); - - public ProductToscaYamlGenerationTest() { - super(name, ProductToscaYamlGenerationTest.class.getName()); - } - - @Test - public void productToscaYamlFormat() throws IOException { - - String heatEnvArtifactHeader = (String) Utils.parseYamlConfig("heatEnvArtifactHeader"); - // System.out.println("heatEnvArtifactHeader = \n" + - // heatEnvArtifactHeader); - - String heatEnvArtifactFooter = (String) Utils.parseYamlConfig("heatEnvArtifactFooter"); - // System.out.println("heatEnvArtifactFooter = \n" + - // heatEnvArtifactFooter); - - // temporary commented - // RestResponse downloadResourceInstanceHeatArtifact = - // ArtifactRestUtils.downloadResourceInstanceArtifact(service.getUniqueId(), - // resourceInstanceId, sdncUserDetails, - // heatArtifactDefinition.getUniqueId()); - // assertTrue("expected request returned status:" + 200 + ", actual: " + - // downloadResourceInstanceHeatArtifact.getErrorCode(), - // downloadResourceInstanceHeatArtifact.getErrorCode()==200); - - // InputStream stream = - // getDecodedSteramFromString(downloadResourceInstanceHeatArtifact.getResponse()); - // System.out.println(Utils.getParamValueFromYamlByKey(stream, - // "description", String.class)); - - // node_types - - } - - private InputStream getDecodedSteramFromString(String encoded64Payload) throws IOException { - - Gson gson = new Gson(); - ArtifactUiDownloadData artifactUiDownloadData = gson.fromJson(encoded64Payload, ArtifactUiDownloadData.class); - String decodedPayload = Decoder.decode(artifactUiDownloadData.getBase64Contents()); - return new ByteArrayInputStream(decodedPayload.getBytes()); - - } - -} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java deleted file mode 100644 index d4bfb62377..0000000000 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.product; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNull; - -import java.io.FileNotFoundException; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; -import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; -import org.openecomp.sdc.ci.tests.utils.general.Convertor; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; -import org.openecomp.sdc.common.api.Constants; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -public class ProductUndoCheckoutTest extends ProductLifecycleTest { - - @Rule - public static TestName name = new TestName(); - - @BeforeClass - public static void staticInit() { - auditAction = UNDO_CHECKOUT_ACTION; - operation = ComponentOperationEnum.CHANGE_STATE_UNDO_CHECKOUT; - } - - public ProductUndoCheckoutTest() { - super(name, ProductUndoCheckoutTest.class.getName()); - } - - @Test - public void undoCheckOutProductByPm() throws Exception { - undoCheckOutProductSuccess(productManager1, false); - } - - @Test - public void undoCheckOutProductByAdmin() throws Exception { - undoCheckOutProductSuccess(adminUser, true); - } - - @Test - public void undoCheckOutAfterCreate() throws Exception { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals("Check response code after undo checkout product", 200, lcsResponse.getErrorCode().intValue()); - - // Verify version was removed - lcsResponse = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), productManager1.getUserId()); - assertEquals("Check response code after get undone product", 404, lcsResponse.getErrorCode().intValue()); - - Product emptyProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - assertNull(emptyProduct); - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(emptyProduct, - auditAction, productManager1, ActionStatus.OK, "0.1", Constants.EMPTY_STRING, - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null, Constants.EMPTY_STRING); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - - } - - @Test - public void undoCheckOutNotExist() throws Exception { - String notExistId = "1234"; - expectedProduct.setUniqueId(notExistId); - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals("Check response code after undo checkout product", 404, lcsResponse.getErrorCode().intValue()); - expectedProduct.setName(notExistId); - String[] auditParameters = new String[] { Constants.EMPTY_STRING }; - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, productManager1, ActionStatus.PRODUCT_NOT_FOUND, Constants.EMPTY_STRING, - Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, auditParameters); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - - } - - @Test - public void undoCheckOutNotInCheckout() throws Exception { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals("Check response code after undo checkout product", 409, lcsResponse.getErrorCode().intValue()); - - String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(), - productManager1.getLastName(), productManager1.getUserId() }; - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, productManager1, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, "0.1", "0.1", - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, - expectedProduct.getUUID(), auditParameters); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - - } - - @Test - public void undoCheckOutProductByPsRoleNotAllowed() throws Exception { - undoCheckOutProductRestricted(productStrategistUser1); - } - - @Test - public void undoCheckOutProductByPmNotStateOwner() throws Exception { - undoCheckOutProductForbidden(productManager2); - } - - private void undoCheckOutProductSuccess(User user, boolean isAdmin) throws Exception, FileNotFoundException { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); - - // Checking undo checkout of admin even if not state owner - User checkoutUser = isAdmin ? productManager1 : user; - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, - LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue()); - Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - - lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, user, LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals("Check response code after undo checkout product", 200, lcsResponse.getErrorCode().intValue()); - - // Verify version was removed - lcsResponse = ProductRestUtils.getProduct(productToBeUndone.getUniqueId(), user.getUserId()); - assertEquals("Check response code after get undone product", 404, lcsResponse.getErrorCode().intValue()); - - lcsResponse = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), user.getUserId()); - assertEquals("Check response code after get latest version", 200, lcsResponse.getErrorCode().intValue()); - - Product latestProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - - expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, latestProduct, operation); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(latestProduct, - auditAction, user, ActionStatus.OK, "0.2", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, latestProduct.getUUID()); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - private void undoCheckOutProductRestricted(User undoCheckoutUser) throws Exception, FileNotFoundException { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue()); - Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - - lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, undoCheckoutUser, - LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals("Check response code after undocheckout product", 409, lcsResponse.getErrorCode().intValue()); - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(productToBeUndone, - auditAction, undoCheckoutUser, ActionStatus.RESTRICTED_OPERATION, "0.2", "0.2", - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - productToBeUndone.getUUID()); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - - private void undoCheckOutProductForbidden(User undoCheckoutUser) throws Exception, FileNotFoundException { - RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKIN); - assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); - - lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, - LifeCycleStatesEnum.CHECKOUT); - assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue()); - Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); - - lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, undoCheckoutUser, - LifeCycleStatesEnum.UNDOCHECKOUT); - assertEquals("Check response code after undocheckout product", 403, lcsResponse.getErrorCode().intValue()); - String[] auditParameters = new String[] { productToBeUndone.getName(), "product", - productManager1.getFirstName(), productManager1.getLastName(), productManager1.getUserId() }; - - ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, - auditAction, undoCheckoutUser, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, "0.2", "0.2", - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - productToBeUndone.getUUID(), auditParameters); - AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); - } - -} 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 6e4a6a8018..90371662a7 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 @@ -24,16 +24,22 @@ import static org.testng.AssertJUnit.assertEquals; import java.io.FileNotFoundException; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringUtils; import org.apache.http.client.ClientProtocolException; import org.json.JSONException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -62,6 +68,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceRestUtils extends BaseRestUtils { + + private static final String CSARS_PATH = "/src/test/resources/CI/csars/"; private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName()); // ****** CREATE ******* @@ -384,6 +392,16 @@ public class ResourceRestUtils extends BaseRestUtils { return http.httpSendGet(url, headersMap); } + + public static RestResponse getResourceFilteredDataByParams(User sdncModifierDetails, String uniqueId , List parameters) throws IOException { + Config config = Utils.getConfig(); + String urlGetResourceDataByParams = Urls.GET_RESOURCE_DATA_BY_PARAMS; + String joinedParameters = StringUtils.join(parameters , "&"); + String url = String.format(urlGetResourceDataByParams + joinedParameters , config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); + return sendGet(url, sdncModifierDetails.getUserId()); + + } + public static RestResponse sendOptionsTowardsCatalogFeWithUuid() throws IOException { @@ -661,5 +679,33 @@ public class ResourceRestUtils extends BaseRestUtils { return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId, newResourceUniqueId, sdncModifierDetails, componentType); } + + public static Resource importResourceFromCsar(String csarName) throws Exception{ + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = csarName; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + + String payloadData = null; + + path = Paths.get(rootPath + CSARS_PATH + csarName); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + // create new resource from Csar + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + return resource; + + // add to restResourceUtil + } + } diff --git a/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml b/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml index 5d1a3e1537..fae7ab7ece 100644 --- a/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml +++ b/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml @@ -8,5 +8,4 @@ packages: - org.openecomp.sdc.ci.tests.execute.artifacts - org.openecomp.sdc.ci.tests.execute.imports - org.openecomp.sdc.ci.tests.execute.category - - org.openecomp.sdc.ci.tests.execute.distribution - - org.openecomp.sdc.ci.tests.execute.product \ No newline at end of file + - org.openecomp.sdc.ci.tests.execute.distribution \ No newline at end of file diff --git a/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml b/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml index 26a85fd9c6..1d81e0f689 100644 --- a/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml +++ b/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml @@ -83,54 +83,7 @@ name="org.openecomp.sdc.ci.tests.execute.resource.ValidateExtendedVfData" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - diff --git a/asdc-tests/src/main/resources/ci/testSuites/resource.xml b/asdc-tests/src/main/resources/ci/testSuites/resource.xml index 803fb01e70..64f4377420 100644 --- a/asdc-tests/src/main/resources/ci/testSuites/resource.xml +++ b/asdc-tests/src/main/resources/ci/testSuites/resource.xml @@ -315,46 +315,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/asdc-tests/src/main/resources/ci/testSuites/sanity.xml b/asdc-tests/src/main/resources/ci/testSuites/sanity.xml index 8e787bc8cd..21b7043ad3 100644 --- a/asdc-tests/src/main/resources/ci/testSuites/sanity.xml +++ b/asdc-tests/src/main/resources/ci/testSuites/sanity.xml @@ -152,53 +152,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/network/images/network.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/network/images/network.png index c8bf18f31a..c98eef324e 100644 Binary files a/asdc-tests/src/test/resources/CI/components/normativeTypes/network/images/network.png and b/asdc-tests/src/test/resources/CI/components/normativeTypes/network/images/network.png differ diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/images/network.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/images/network.png index c8bf18f31a..c98eef324e 100644 Binary files a/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/images/network.png and b/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/images/network.png differ diff --git a/asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar b/asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar index 63a478939c..b11bd9386a 100644 Binary files a/asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar and b/asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar differ diff --git a/asdctool/pom.xml b/asdctool/pom.xml index cb31d553b7..da1b9160fd 100644 --- a/asdctool/pom.xml +++ b/asdctool/pom.xml @@ -165,6 +165,10 @@ org.json json + + org.slf4j + slf4j-log4j12 + @@ -180,6 +184,12 @@ titan-cassandra ${titan.version} compile + + + org.slf4j + slf4j-log4j12 + + @@ -202,6 +212,12 @@ 2.5.0 true compile + + + org.slf4j + slf4j-log4j12 + + @@ -210,6 +226,12 @@ 2.5.0 true compile + + + org.slf4j + slf4j-log4j12 + + diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/EsToCassandraDataMigrationConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/EsToCassandraDataMigrationConfig.java index 2c0471fb17..3242c27384 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/EsToCassandraDataMigrationConfig.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/EsToCassandraDataMigrationConfig.java @@ -23,6 +23,7 @@ package org.openecomp.sdc.asdctool.impl; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraClient; +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -47,5 +48,9 @@ public class EsToCassandraDataMigrationConfig { public CassandraClient cassandraClient() { return new CassandraClient(); } - + + @Bean(name = "sdc-schema-files-cassandra-dao") + public SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao() { + return new SdcSchemaFilesCassandraDao(); + } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java index 3f63570ecd..ace1c038f2 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java @@ -2,18 +2,14 @@ package org.openecomp.sdc.asdctool.impl; import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; import java.util.Map; 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.graph.datatype.ActionEnum; import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.resources.data.UserData; @@ -72,49 +68,28 @@ public class TitanGraphInitializer { return false; } - private static void createDefaultUsers() { - List users = createUserList(); - for (UserData user : users) { - Vertex vertex = null; - Map checkedProperties = new HashMap(); - checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); - checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); - Map properties = null; - if (!isVertexExist(checkedProperties)) { - vertex = graph.addVertex(); - vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); - properties = user.toGraphMap(); - for (Map.Entry entry : properties.entrySet()) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - } + private static void createDefaultAdminUser() { + createUser(getDefaultUserAdmin()); graph.tx().commit(); } - private static List createUserList() { - LinkedList users = new LinkedList(); - users.add(getDefaultUserAdmin1()); - users.add(getDefaultUserAdmin2()); - users.add(getDefaultUserDesigner1()); - users.add(getDefaultUserDesigner2()); - users.add(getDefaultUserTester1()); - users.add(getDefaultUserTester2()); - users.add(getDefaultUserTester3()); - users.add(getDefaultUserGovernor1()); - users.add(getDefaultUserGovernor2()); - users.add(getDefaultUserOps1()); - users.add(getDefaultUserOps2()); - users.add(getDefaultUserProductManager1()); - users.add(getDefaultUserProductManager2()); - users.add(getDefaultUserProductStrategist1()); - users.add(getDefaultUserProductStrategist2()); - users.add(getDefaultUserProductStrategist3()); - return users; + private static void createUser(UserData user) { + Map checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + Map properties = null; + if (!isVertexExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + properties = user.toGraphMap(); + for (Map.Entry entry : properties.entrySet()) { + vertex.property(entry.getKey(), entry.getValue()); + } + } } - private static UserData getDefaultUserAdmin1() { + private static UserData getDefaultUserAdmin() { UserData userData = new UserData(); userData.setAction(ActionEnum.Create); userData.setElementType(GraphElementTypeEnum.Node); @@ -128,215 +103,6 @@ public class TitanGraphInitializer { return userData; } - private static UserData getDefaultUserAdmin2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("tr0001"); - userData.setEmail("admin@sdc.com"); - userData.setFirstName("Todd"); - userData.setLastName("Rundgren"); - userData.setRole("ADMIN"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserDesigner1() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("cs0008"); - userData.setEmail("designer@sdc.com"); - userData.setFirstName("Carlos"); - userData.setLastName("Santana"); - userData.setRole("DESIGNER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserDesigner2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("me0009"); - userData.setEmail("designer@sdc.com"); - userData.setFirstName("Melissa"); - userData.setLastName("Etheridge"); - userData.setRole("DESIGNER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserTester1() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("jm0007"); - userData.setEmail("tester@sdc.com"); - userData.setFirstName("Joni"); - userData.setLastName("Mitchell"); - userData.setRole("TESTER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserTester2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("kb0004"); - userData.setEmail("tester@sdc.com"); - userData.setFirstName("Kate"); - userData.setLastName("Bush"); - userData.setRole("TESTER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserTester3() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("jt0005"); - userData.setEmail("tester@sdc.com"); - userData.setFirstName("James"); - userData.setLastName("Taylor"); - userData.setRole("TESTER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserOps1() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("op0001"); - userData.setEmail("ops@sdc.com"); - userData.setFirstName("Steve"); - userData.setLastName("Regev"); - userData.setRole("OPS"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserOps2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("af0006"); - userData.setEmail("designer@sdc.com"); - userData.setFirstName("Aretha"); - userData.setLastName("Franklin"); - userData.setRole("OPS"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserGovernor1() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("gv0001"); - userData.setEmail("governor@sdc.com"); - userData.setFirstName("David"); - userData.setLastName("Shadmi"); - userData.setRole("GOVERNOR"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserGovernor2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("ah0002"); - userData.setEmail("admin@sdc.com"); - userData.setFirstName("Alex"); - userData.setLastName("Harvey"); - userData.setRole("GOVERNOR"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserProductManager1() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("pm0001"); - userData.setEmail("pm1@sdc.com"); - userData.setFirstName("Teddy"); - userData.setLastName("Isashar"); - userData.setRole("PRODUCT_MANAGER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserProductManager2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("pm0002"); - userData.setEmail("pm2@sdc.com"); - userData.setFirstName("Sarah"); - userData.setLastName("Bettens"); - userData.setRole("PRODUCT_MANAGER"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserProductStrategist1() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("ps0001"); - userData.setEmail("ps1@sdc.com"); - userData.setFirstName("Eden"); - userData.setLastName("Rozin"); - userData.setRole("PRODUCT_STRATEGIST"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserProductStrategist2() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("ps0002"); - userData.setEmail("ps2@sdc.com"); - userData.setFirstName("Ella"); - userData.setLastName("Kvetny"); - userData.setRole("PRODUCT_STRATEGIST"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static UserData getDefaultUserProductStrategist3() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("ps0003"); - userData.setEmail("ps3@sdc.com"); - userData.setFirstName("Geva"); - userData.setLastName("Alon"); - userData.setRole("PRODUCT_STRATEGIST"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } private static void createVertexIndixes() { logger.info("** createVertexIndixes started"); @@ -399,6 +165,6 @@ public class TitanGraphInitializer { private static void createIndexesAndDefaults() { createVertexIndixes(); createEdgeIndixes(); - createDefaultUsers(); + createDefaultAdminUser(); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java deleted file mode 100644 index d74bae6087..0000000000 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.openecomp.sdc.asdctool.impl.migration; - -public interface Migration { - - /** - * performs a migration operation - * @return true if migration completed successfully or false otherwise - */ - boolean migrate(); - - /** - * - * @return a description of what this migration does - */ - String description(); - -} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java new file mode 100644 index 0000000000..92e185dbd7 --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.asdctool.impl.migration; + +/** + * for 1707 migration only!!! + * please don't implement this interface unless you are sure you want to run with 1707 migration classes + */ +public interface Migration1707Task { + + /** + * performs a migration operation + * @return true if migration completed successfully or false otherwise + */ + boolean migrate(); + + /** + * + * @return a description of what this migration does + */ + String description(); + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java index 514c28b9b1..25132caf28 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java @@ -27,9 +27,11 @@ import org.openecomp.sdc.asdctool.impl.migration.v1610.TitanFixUtils; import org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment; import org.openecomp.sdc.asdctool.impl.migration.v1702.DataTypesUpdate; import org.openecomp.sdc.asdctool.impl.migration.v1702.Migration1702; -import org.openecomp.sdc.asdctool.impl.migration.v1707.VfModulesPropertiesAdding; +import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707RelationsFix; +import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707VnfFix; import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.*; @@ -51,7 +53,32 @@ import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; -import org.openecomp.sdc.be.model.operations.impl.*; +import org.openecomp.sdc.be.model.operations.impl.AdditionalInformationOperation; +import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; +import org.openecomp.sdc.be.model.operations.impl.AttributeOperation; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation; +import org.openecomp.sdc.be.model.operations.impl.CsarOperation; +import org.openecomp.sdc.be.model.operations.impl.ElementOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.model.operations.impl.GroupInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.GroupOperation; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation; +import org.openecomp.sdc.be.model.operations.impl.InputsOperation; +import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.OnboardingClient; +import org.openecomp.sdc.be.model.operations.impl.ProductOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.RequirementOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.be.user.IUserBusinessLogic; @@ -66,6 +93,11 @@ import org.springframework.context.annotation.Primary; @Import(DAOSpringConfig.class) public class AppConfig { + @Bean(name="artifact-resolver") + public ArtifactsResolver artifactsResolver() { + return new ArtifactResolverImpl(); + } + @Bean(name = "sdc-schema-files-cassandra-dao") public SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao() { return new SdcSchemaFilesCassandraDao(); @@ -543,9 +575,22 @@ public class AppConfig { return new MigrationOperationUtils(); } - @Bean(name = "vfModulesPropertiesAdding") - public VfModulesPropertiesAdding vfModulesPropertiesAdding() { - return new VfModulesPropertiesAdding(); - } + @Bean("consumer-operation") + public ConsumerOperation consumerOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + return new ConsumerOperation(titanGenericDao); + } + @Bean(name = "migration1707relationsFix") + public Migration1707RelationsFix migration1707RelationsFix() { + return new Migration1707RelationsFix(); + } + @Bean(name = "migration1707vnfFix") + public Migration1707VnfFix migration1707VnfFix() { + return new Migration1707VnfFix(); + } + +// @Bean(name = "migration1707relationsFix") +// public Migration1707RelationsFix migration1707RelationsFix() { +// return new Migration1707RelationsFix(); +// } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java index 861e9136a3..6fa8b45734 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java @@ -1036,10 +1036,8 @@ public class Migration1702 { property.setName(fe.getKey()); Map definitionInYaml = (Map) fe.getValue(); property.setType((String) definitionInYaml.get("type")); - // Fix by Tal G property.setRequired((Boolean) definitionInYaml.get("required")); property.setDescription((String) definitionInYaml.get("description")); - // Fix by Tal G String defaultValue = definitionInYaml.get("default") == null ? null : definitionInYaml.get("default").toString(); if (defaultValue != null) { property.setDefaultValue(defaultValue); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java new file mode 100644 index 0000000000..7c0b57fb1d --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java @@ -0,0 +1,140 @@ +package org.openecomp.sdc.asdctool.impl.migration.v1707; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import fj.data.Either; + +@Component("distributionStatusUpdate") +public class DistributionStatusUpdate { + private static Logger LOGGER = LoggerFactory.getLogger(DistributionStatusUpdate.class); + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + @Autowired + private TitanDao titanDao; + + + public boolean migrate() { + boolean result = true; + Either, StorageOperationStatus> getAllServiceComponentsRes = getAllServiceComponents(); + if(getAllServiceComponentsRes.isRight()){ + result = false; + } + if(result && MapUtils.isNotEmpty(getAllServiceComponentsRes.left().value())){ + updateDistributionStatusFromMetadata(getAllServiceComponentsRes.left().value()); + updateDistributionStatusToNotDistributed(getAllServiceComponentsRes.left().value()); + } + + toscaOperationFacade.commit(); + + return result; + } + + + private void updateDistributionStatusToNotDistributed(Map components) { + + Map filteredComponents = components.entrySet() + .stream() + .filter(e -> e.getValue().getLifecycleState() != LifecycleStateEnum.CERTIFIED) + .collect(Collectors.toMap(e -> e.getKey(), e -> (Service)e.getValue())); + + Service service; + Either updateResponse; + GraphVertex metadataV; + + for(Entry currComponent : filteredComponents.entrySet()){ + metadataV = currComponent.getKey(); + service = currComponent.getValue(); + try { + metadataV.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + updateResponse = titanDao.updateVertex(metadataV); + + if (updateResponse.isRight()) { + LOGGER.debug("failed to updateDistributionStatusToNotDistributed service {} error {}", service.getUniqueId(), updateResponse.right().value()); + } + + } catch (Exception e) { + LOGGER.debug("failed to updateDistributionStatusToNotDistributed service {} error {}", service.getUniqueId(), e.toString()); + } + } + } + + private void updateDistributionStatusFromMetadata(Map components) { + Service service; + String statusFromMetadata; + Either updateResponse; + GraphVertex metadataV; + + for(Entry currComponent : components.entrySet()){ + metadataV = currComponent.getKey(); + service = currComponent.getValue(); + try { + statusFromMetadata = (String) metadataV.getJsonMetadataField(JsonPresentationFields.DISTRIBUTION_STATUS); + metadataV.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, statusFromMetadata); + updateResponse = titanDao.updateVertex(metadataV); + + if (updateResponse.isRight()) { + LOGGER.debug("failed to updateDistributionStatusFromMetadata service {} error {}", service.getUniqueId(), updateResponse.right().value()); + } + + } catch (Exception e) { + LOGGER.debug("failed to read distribution status of service {} error {}", service.getUniqueId(), e.toString()); + } + + } + } + + + public Either, StorageOperationStatus> getAllServiceComponents() { + + Map components = new HashMap<>(); + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + propertiesNotMatch.put(GraphPropertyEnum.IS_DELETED, true); + Either, TitanOperationStatus> getVerticiesRes = toscaOperationFacade.getTitanDao().getByCriteria(null, propertiesToMatch, propertiesNotMatch, JsonParseFlagEnum.ParseAll); + + if (getVerticiesRes.isRight() && getVerticiesRes.right().value() != TitanOperationStatus.NOT_FOUND) { + LOGGER.debug("Failed to fetch all service components. Status is {}", getVerticiesRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticiesRes.right().value())); + } + if(getVerticiesRes.isLeft()){ + List componentVerticies = getVerticiesRes.left().value(); + for (GraphVertex componentV : componentVerticies) { + ComponentParametersView filters = new ComponentParametersView(true); + Either getComponentsRes = toscaOperationFacade.getToscaElement(componentV.getUniqueId(), filters); + if (getComponentsRes.isRight()) { + return Either.right(getComponentsRes.right().value()); + } + components.put(componentV, (Service) getComponentsRes.left().value()); + } + } + return Either.left(components); + } + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java index be40e4cd0d..84214cc0b0 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java @@ -1,27 +1,29 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707; -import org.openecomp.sdc.asdctool.impl.migration.Migration; +import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.annotation.Resource; import java.util.List; +import java.util.Optional; @Component("migration1707") public class Migration1707 { private static Logger LOGGER = LoggerFactory.getLogger(Migration1707.class); - private List migrations; + private List migrations; - public Migration1707(List migrations) { + public Migration1707(List migrations) { this.migrations = migrations; } public boolean migrate() { - for (Migration migration : migrations) { + int startMigrationFrom = Optional.ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getStartMigrationFrom()).orElse(0); + List migrations = this.migrations.subList(startMigrationFrom, this.migrations.size()); + for (Migration1707Task migration : migrations) { LOGGER.info(String.format("Starting migration. %s", migration.description())); boolean migrationCompletedSuccessfully = migration.migrate(); if (!migrationCompletedSuccessfully) { @@ -33,5 +35,4 @@ public class Migration1707 { 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 9c39b58404..eeb29d67c2 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 @@ -3,19 +3,8 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707; import java.util.List; -import org.openecomp.sdc.asdctool.impl.migration.Migration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.MigrationByIdDerivedNodeTypeResolver; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.NormativesMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.NormativesResolver; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ResourceVersionMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ResourcesCategoriesMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ServiceCategoriesMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ServiceVersionMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.ServicesMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.UserStatesMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.UsersMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.VFResourcesMigration; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.VersionMigration; +import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task; +import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.*; import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledCapabilitiesMigrationService; import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledRequirementsMigrationService; import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.RequirementsCapabilitiesMigrationService; @@ -37,6 +26,7 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; +import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation; import org.openecomp.sdc.be.model.operations.impl.ElementOperation; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; @@ -45,6 +35,7 @@ import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; @Configuration @@ -52,69 +43,72 @@ public class Migration1707Config { @Bean(name = "migration1707") - public Migration1707 migration1707(List migrations) { + public Migration1707 migration1707(List migrations) { return new Migration1707(migrations); } - @Bean(name = "renameGraphPropertyKeysMigration") - @Order(1) - public Migration renameGraphPropertyKeysMigration() { - return new RenameGraphPropertyKeys(); - } + //@Bean(name = "renameGraphPropertyKeysMigration") + //@Order(1) + //public Migration1707Task renameGraphPropertyKeysMigration() { + // return new RenameGraphPropertyKeys(); + // } - @Bean(name = "toscaNamesUpdate") - @Order(2) - public Migration toscaNamesUpdate() { - return new ToscaNamesUpdate(); - } + //@Bean(name = "toscaNamesUpdate") + //@Order(2) + //public Migration1707Task toscaNamesUpdate() { + // return new ToscaNamesUpdate(); + //} @Bean(name = "users-migration") - @Order(3) - public Migration usersMigration() { + @Order(1) + public Migration1707Task usersMigration() { return new UsersMigration(); } @Bean(name = "resource-category-migration") - @Order(4) - public Migration resourceCategoriesMigration() { + @Order(2) + public Migration1707Task resourceCategoriesMigration() { return new ResourcesCategoriesMigration(); } @Bean(name = "service-category-migration") - @Order(5) - public Migration serviceCategoriesMigration() { + @Order(3) + public Migration1707Task serviceCategoriesMigration() { return new ServiceCategoriesMigration(); } @Bean(name = "normatives-migration") - @Order(6) - public Migration normativesMigration() { + @Order(4) + public Migration1707Task normativesMigration() { return new NormativesMigration(); } @Bean(name = "vf-migration") - @Order(7) - public Migration vfMigration() { + @Order(5) + public Migration1707Task vfMigration() { return new VFResourcesMigration(); } @Bean(name = "service-migration") - @Order(8) - public Migration serviceMigration() { + @Order(6) + public Migration1707Task serviceMigration() { return new ServicesMigration(); } - @Bean(name = "user-states-migration") - @Order(9) - public Migration userStatesMigration() { - return new UserStatesMigration(); + @Bean(name = "consumers-migration") + @Order(7) + public Migration1707Task consumersMigration() { return new ConsumersMigration(); } + + @Bean(name = "tosca-template-regeneration") + @Order(8) + public Migration1707Task ToscaTemplateRegeneration() { + return new ToscaTemplateRegeneration(); + } + + @Bean(name = "distributionStatusUpdate") + public DistributionStatusUpdate distributionStatusUpdate() { + return new DistributionStatusUpdate(); } - -// @Bean(name = "tosca-template-regeneration") -// @Order(10) -// public Migration ToscaTemplateRegeneration() { -// return new ToscaTemplateRegeneration(); -// } @Bean("resource-version-migration") public VersionMigration resourceVersionMigration() { @@ -236,5 +230,20 @@ public class Migration1707Config { return new MigrationByIdDerivedNodeTypeResolver(); } + @Bean(name = "invariant-uuid-resolver") + public InvariantUUIDResolver invariantUUIDResolver() { + return new InvariantUUIDResolver(); + } + + @Bean(name="consumer-operation-mig") + @Primary + public ConsumerOperation consumerOperation(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) { + return new ConsumerOperation(titanGenericDao); + } + + @Bean(name = "vfModulesPropertiesAdding") + public VfModulesPropertiesAdding vfModulesPropertiesAdding() { + return new VfModulesPropertiesAdding(); + } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java new file mode 100644 index 0000000000..47bce78893 --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java @@ -0,0 +1,131 @@ +package org.openecomp.sdc.asdctool.impl.migration.v1707; + +import java.util.EnumMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import fj.data.Either; +@Component("migration1707relationsFix") +public class Migration1707RelationsFix { + + private static Logger LOGGER = LoggerFactory.getLogger(Migration1707RelationsFix.class); + + @Autowired + private TitanDao titanDao; + + public boolean migrate() { + boolean result = true; + + try{ + Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + Either, TitanOperationStatus> getAllTopologyTemplatesRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (getAllTopologyTemplatesRes.isRight() && getAllTopologyTemplatesRes.right().value() != TitanOperationStatus.NOT_FOUND) { + LOGGER.debug("Failed to fetch all non marked as deleted topology templates , error {}", getAllTopologyTemplatesRes.right().value()); + result = false; + } + if(getAllTopologyTemplatesRes.isLeft()){ + fixComponentsRelations(getAllTopologyTemplatesRes.left().value()); + } + if(result){ + Either, TitanOperationStatus> getAllNodeTypesRes = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, null, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (getAllNodeTypesRes.isRight() && getAllNodeTypesRes.right().value() != TitanOperationStatus.NOT_FOUND) { + LOGGER.debug("Failed to fetch all non marked as deleted node types , error {}", getAllNodeTypesRes.right().value()); + result = false; + } + if(getAllNodeTypesRes.isLeft()){ + fixComponentsRelations(getAllNodeTypesRes.left().value()); + } + } + } catch (Exception e){ + LOGGER.debug("The exception {} occured upon migration 1707 relations fixing. ", e.getMessage()); + e.printStackTrace(); + result = false; + } + finally{ + if(result){ + titanDao.commit(); + } else { + titanDao.rollback(); + } + } + return result; + } + + private void fixComponentsRelations(List notDeletedComponentVerticies) { + notDeletedComponentVerticies.stream().forEach(this::fixComponentRelations); + } + + private void fixComponentRelations(GraphVertex componentV) { + fixCreatorComponentRelation(componentV); + fixLastModifierComponentRelation(componentV); + fixStateComponentRelation(componentV); + } + + private void fixStateComponentRelation(GraphVertex componentV) { + boolean relevantEdgeFound = false; + Iterator edges = componentV.getVertex().edges(Direction.IN, EdgeLabelEnum.STATE.name()); + String getState = (String) componentV.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE); + while(edges.hasNext()){ + Edge edge = edges.next(); + String edgeState = (String) edge.property(GraphPropertyEnum.STATE.getProperty()).orElse(null); + if(getState.equals(edgeState) && !relevantEdgeFound){ + relevantEdgeFound = true; + } else { + removeEdge(edge); + } + } + } + + private void fixCreatorComponentRelation(GraphVertex componentV) { + boolean relevantUserFound = false; + Iterator edges = componentV.getVertex().edges(Direction.IN, EdgeLabelEnum.CREATOR.name()); + String getCreatorUserId = (String) componentV.getJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR); + while(edges.hasNext()){ + Edge edge = edges.next(); + String userId = (String) edge.outVertex().property(GraphPropertyEnum.USERID.getProperty()).orElse(null); + if(getCreatorUserId.equals(userId) && !relevantUserFound){ + relevantUserFound = true; + } else { + removeEdge(edge); + } + } + } + + private void fixLastModifierComponentRelation(GraphVertex componentV) { + boolean relevantUserFound = false; + Iterator edges = componentV.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_MODIFIER.name()); + String getLastUpdaterUserId = (String) componentV.getJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER); + while(edges.hasNext()){ + Edge edge = edges.next(); + String updaterId = (String) edge.outVertex().property(GraphPropertyEnum.USERID.getProperty()).orElse(null); + if(getLastUpdaterUserId.equals(updaterId) && !relevantUserFound){ + relevantUserFound = true; + } else { + removeEdge(edge); + } + } + } + + private void removeEdge(Edge edge) { + LOGGER.debug("Going to remove edge {} upon migration 1707 relations fixing. ", edge.id()); + edge.remove(); + LOGGER.debug("The edge {} has been removed. ", edge.id()); + } + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java new file mode 100644 index 0000000000..d3bd494a85 --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java @@ -0,0 +1,100 @@ +package org.openecomp.sdc.asdctool.impl.migration.v1707; + +import java.util.EnumMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@Component("migration1707vnfFix") +public class Migration1707VnfFix{ + + private static final String VF_MODULES_METADATA = "vfModulesMetadata"; + + @Autowired + private TitanDao titanDao; + + @Autowired + private TopologyTemplateOperation topologyTemplateOperation; + + private static Logger LOGGER = LoggerFactory.getLogger(Migration1707RelationsFix.class); + + public boolean migrate() { + boolean result = true; + + Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + + Map propsHas = new EnumMap<>(GraphPropertyEnum.class); + propsHas.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + propsHas.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name()); + propsHas.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED); + + Either, TitanOperationStatus> getAllTopologyTemplatesRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (getAllTopologyTemplatesRes.isRight() && getAllTopologyTemplatesRes.right().value() != TitanOperationStatus.NOT_FOUND) { + LOGGER.debug("Failed to fetch all non marked as deleted topology templates , error {}", getAllTopologyTemplatesRes.right().value()); + result = false; + } + List metadataVertices = getAllTopologyTemplatesRes.left().value(); + for (GraphVertex metadataV : metadataVertices) { + Either, TitanOperationStatus> dataFromGraph = topologyTemplateOperation.getDataFromGraph(metadataV.getUniqueId(), EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (dataFromGraph.isLeft()) { + Map artifacts = dataFromGraph.left().value(); + if (artifacts.containsKey(VF_MODULES_METADATA)) { + artifacts.remove(VF_MODULES_METADATA); + Either vertexById = titanDao.getVertexById(metadataV.getUniqueId()); + TitanVertex vertex = vertexById.left().value().getVertex(); + Iterator edges = vertex.edges(Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS.name()); + if (edges.hasNext()) { + Edge edge = edges.next(); + Vertex dataV = edge.inVertex(); + + String jsonStr; + try { + jsonStr = JsonParserUtils.jsonToString(artifacts); + dataV.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); + } catch (Exception e) { + LOGGER.debug("Failed to update deployment artifacts for VF {}", metadataV.getUniqueId()); + } + } + } + } + TitanOperationStatus commit = titanDao.commit(); + if ( commit != TitanOperationStatus.OK){ + LOGGER.debug("Failed to commit changes for deployment artifacts for VF {} {}", metadataV.getUniqueId(), metadataV.getMetadataProperty(GraphPropertyEnum.NAME)); + } + } + + return result; + } + + public String description() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java index a69fb9d011..a1c1b6b4cc 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java @@ -1,8 +1,6 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707; -import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg; -import org.openecomp.sdc.asdctool.impl.migration.Migration; -import org.openecomp.sdc.asdctool.impl.migration.MigrationOperationUtils; +import org.openecomp.sdc.asdctool.impl.migration.*; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -11,7 +9,7 @@ import java.util.HashMap; import java.util.Map; @Component("renameGraphPropertyKeysMigration") -public class RenameGraphPropertyKeys implements Migration { +public class RenameGraphPropertyKeys implements Migration1707Task { private final static Map KEY_PROPERTIES_TO_RENAME; diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java index 262c300009..5213fae619 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java @@ -8,7 +8,7 @@ import java.util.function.Function; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.asdctool.impl.migration.Migration; +import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task; import org.openecomp.sdc.be.dao.graph.GraphElementFactory; import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; @@ -46,7 +46,7 @@ import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; @Component("toscaNamesUpdate") -public class ToscaNamesUpdate implements Migration { +public class ToscaNamesUpdate implements Migration1707Task { private static Logger log = LoggerFactory.getLogger(ToscaNamesUpdate.class.getName()); @Override diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java index 824bb83ec9..09e52619f0 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java @@ -1,14 +1,11 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707; import java.util.EnumMap; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.asdctool.impl.migration.Migration; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -34,7 +31,7 @@ import org.springframework.stereotype.Component; import fj.data.Either; @Component("toscaTemplateRegeneration") -public class ToscaTemplateRegeneration implements Migration { +public class ToscaTemplateRegeneration implements Migration1707Task { private static Logger LOGGER = LoggerFactory.getLogger(ToscaTemplateRegeneration.class); @@ -50,13 +47,13 @@ public class ToscaTemplateRegeneration implements Migration { @Override public boolean migrate() { boolean result = true; - Either, StorageOperationStatus> getAllCertifiedComponentsRes; + Either, StorageOperationStatus> getAllCertifiedComponentsRes; try{ getAllCertifiedComponentsRes = getAllCertifiedComponents(); if(getAllCertifiedComponentsRes.isRight()){ result = false; } - if(result && MapUtils.isNotEmpty(getAllCertifiedComponentsRes.left().value())){ + if(result && CollectionUtils.isNotEmpty(getAllCertifiedComponentsRes.left().value())){ result = regenerateToscaTemplateArtifacts(getAllCertifiedComponentsRes.left().value()); } } catch(Exception e){ @@ -72,17 +69,21 @@ public class ToscaTemplateRegeneration implements Migration { return result; } - private boolean regenerateToscaTemplateArtifacts(Map components) { + private boolean regenerateToscaTemplateArtifacts(List components) { boolean result = true; - - Map filteredComponents = components.entrySet() - .stream() - .filter(e -> e.getValue().getToscaArtifacts()!=null && e.getValue().getToscaArtifacts().containsKey(ToscaExportHandler.ASSET_TOSCA_TEMPLATE)) - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - - for(Entry currComponent : filteredComponents.entrySet()){ - result = regenerateToscaTemplateArtifact(currComponent); - if(!result){ + for(GraphVertex componentV : components){ + Either getComponentsRes = toscaOperationFacade.getToscaElement(componentV); + if (getComponentsRes.isRight()) { + result = false; + break; + } + if(getComponentsRes.left().value().getToscaArtifacts()!=null && getComponentsRes.left().value().getToscaArtifacts().containsKey(ToscaExportHandler.ASSET_TOSCA_TEMPLATE)){ + result = regenerateToscaTemplateArtifact(getComponentsRes.left().value(), componentV); + } + if(result){ + toscaOperationFacade.commit(); + } else { + toscaOperationFacade.rollback(); break; } } @@ -90,26 +91,26 @@ public class ToscaTemplateRegeneration implements Migration { } @SuppressWarnings("unchecked") - private boolean regenerateToscaTemplateArtifact(Map.Entry parent) { + private boolean regenerateToscaTemplateArtifact(org.openecomp.sdc.be.model.Component parent, GraphVertex parentV) { boolean result = true; Either toscaDataVertexRes = null; ArtifactDataDefinition data = null; LOGGER.debug("tosca artifact generation"); - Either exportComponent = toscaExportUtils.exportComponent(parent.getValue()); + Either exportComponent = toscaExportUtils.exportComponent(parent); if (exportComponent.isRight()) { - LOGGER.debug("Failed export tosca yaml for component {} error {}", parent.getValue().getUniqueId(), exportComponent.right().value()); + LOGGER.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value()); result = false; } if(result){ - LOGGER.debug("Tosca yaml exported for component {} ", parent.getValue().getUniqueId()); - toscaDataVertexRes = toscaOperationFacade.getTitanDao().getChildVertex(parent.getKey(), EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson); + LOGGER.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); + toscaDataVertexRes = toscaOperationFacade.getTitanDao().getChildVertex(parentV, EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson); if(toscaDataVertexRes.isRight()){ - LOGGER.debug("Failed to fetch tosca data vertex {} for component {}. Status is {}", EdgeLabelEnum.TOSCA_ARTIFACTS, parent.getValue().getUniqueId(), exportComponent.right().value()); + LOGGER.debug("Failed to fetch tosca data vertex {} for component {}. Status is {}", EdgeLabelEnum.TOSCA_ARTIFACTS, parent.getUniqueId(), exportComponent.right().value()); result = false; } } if(result){ - data = parent.getValue().getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + data = parent.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); data.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(exportComponent.left().value().getMainYaml().getBytes())); ((Map) toscaDataVertexRes.left().value().getJson()).put(ToscaExportHandler.ASSET_TOSCA_TEMPLATE, data); @@ -129,26 +130,19 @@ public class ToscaTemplateRegeneration implements Migration { return result; } - public Either, StorageOperationStatus> getAllCertifiedComponents() { + public Either, StorageOperationStatus> getAllCertifiedComponents() { - Map components = new HashMap<>(); Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - Either, TitanOperationStatus> getVerticiesRes = toscaOperationFacade.getTitanDao().getByCriteria(null, propertiesToMatch,JsonParseFlagEnum.ParseAll); + List components = null; + Either, TitanOperationStatus> getVerticiesRes = toscaOperationFacade.getTitanDao().getByCriteria(null, propertiesToMatch,JsonParseFlagEnum.ParseMetadata); if (getVerticiesRes.isRight() && getVerticiesRes.right().value() != TitanOperationStatus.NOT_FOUND) { LOGGER.debug("Failed to fetch all certified components. Status is {}", getVerticiesRes.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticiesRes.right().value())); } if(getVerticiesRes.isLeft()){ - List componentVerticies = getVerticiesRes.left().value(); - for (GraphVertex componentV : componentVerticies) { - Either getComponentsRes = toscaOperationFacade.getToscaElement(componentV); - if (getComponentsRes.isRight()) { - return Either.right(getComponentsRes.right().value()); - } - components.put(componentV, getComponentsRes.left().value()); - } + components = getVerticiesRes.left().value(); } return Either.left(components); } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java index 5b1441903f..ca1ed2b2a8 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java @@ -13,10 +13,12 @@ import javax.annotation.Resource; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.asdctool.impl.migration.v1702.DataTypesUpdate; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -45,7 +47,7 @@ import fj.data.Either; @Component("vfModulesPropertiesAdding") public class VfModulesPropertiesAdding { - private static Logger LOGGER = LoggerFactory.getLogger(ToscaTemplateRegeneration.class); + private static Logger LOGGER = LoggerFactory.getLogger(VfModulesPropertiesAdding.class); @Autowired private ToscaOperationFacade toscaOperationFacade; @@ -61,25 +63,35 @@ public class VfModulesPropertiesAdding { public boolean migrate(String groupsTypeYmlFilePath) { + LOGGER.debug("Going to add new properties to vfModules. "); boolean result = true; - Either, StorageOperationStatus> getAllComponentsRes = null; GroupTypeDefinition vfModule; Either, TitanOperationStatus> getAllTopologyTemplatesRes = null; - List newProperties = null; - + String vfModuleUid = "org.openecomp.groups.VfModule.1.0.grouptype"; Either getGroupTypeVfModuleRes ; + List updatedProperties = null; try{ - getGroupTypeVfModuleRes = groupTypeOperation.getGroupTypeByUid("org.openecomp.groups.VfModule.1.0.grouptype"); + LOGGER.debug("Going to fetch {}. ", vfModuleUid); + getGroupTypeVfModuleRes = groupTypeOperation.getGroupTypeByUid(vfModuleUid); - if(getGroupTypeVfModuleRes.isRight()){ - result = false; + if(getGroupTypeVfModuleRes.isRight() && getGroupTypeVfModuleRes.right().value() != TitanOperationStatus.NOT_FOUND){ + LOGGER.debug("Failed to fetch the group type {}. The status is {}. ", vfModuleUid, getGroupTypeVfModuleRes.right().value()); + result = false; + } + if(getGroupTypeVfModuleRes.isRight() && getGroupTypeVfModuleRes.right().value() == TitanOperationStatus.NOT_FOUND){ + LOGGER.debug("The group type with id {} was not found. Skipping adding the new properties. ", vfModuleUid); + return true; } if(result){ + LOGGER.debug("Going to add the new properties {} to org.openecomp.groups.VfModule.1.0.grouptype. "); vfModule = getGroupTypeVfModuleRes.left().value(); - newProperties = getNewVfModuleTypeProperties(getAllVfModuleTypePropertiesFromYaml(groupsTypeYmlFilePath), vfModule); - result = addNewPropertiesToGroupType(vfModule, newProperties); + updatedProperties = getAllVfModuleTypePropertiesFromYaml(groupsTypeYmlFilePath); + result = addNewPropertiesToGroupType(vfModule, getNewVfModuleTypeProperties(updatedProperties, vfModule)); + if(!result){ + LOGGER.debug("Failed to add the new properties {} to org.openecomp.groups.VfModule.1.0.grouptype. "); + } } - if(result && CollectionUtils.isNotEmpty(newProperties)){ + if(result && CollectionUtils.isNotEmpty(updatedProperties)){ Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); getAllTopologyTemplatesRes = toscaOperationFacade.getTitanDao().getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseAll); @@ -89,13 +101,7 @@ public class VfModulesPropertiesAdding { } } if(result && getAllTopologyTemplatesRes!=null && getAllTopologyTemplatesRes.isLeft()){ - getAllComponentsRes = getAllContainerComponents(getAllTopologyTemplatesRes.left().value()); - if(getAllComponentsRes.isRight()){ - result = false; - } - } - if(result && getAllComponentsRes != null){ - result = addNewVfModulesProperties(getAllComponentsRes.left().value(), newProperties); + result = addNewVfModulesProperties(getAllTopologyTemplatesRes.left().value(), updatedProperties); } } catch (Exception e){ result = false; @@ -110,41 +116,61 @@ public class VfModulesPropertiesAdding { return result; } - private boolean addNewVfModulesProperties(Map components, List newGroupTypeProperties) { + private boolean addNewVfModulesProperties(List components, List updatedProperties) { boolean result = true; - for(Map.Entry component : components.entrySet()){ - result = addNewPropertiesToVfModules(component, newGroupTypeProperties); + for(GraphVertex component : components){ + LOGGER.debug("Going to add the new properties {} to component {}. ", updatedProperties, component.getUniqueId()); + result = addNewPropertiesToVfModules(component, updatedProperties); if(!result){ + LOGGER.debug("Failed to add the new properties {} to component {}. ", updatedProperties, component.getUniqueId()); break; } + toscaOperationFacade.commit(); } return result; } - private boolean addNewPropertiesToVfModules(Entry component, List newGroupTypeProperties) { + private boolean addNewPropertiesToVfModules(GraphVertex componentV, List updatedProperties) { boolean result = true; List vfModules = null; - if(CollectionUtils.isNotEmpty(component.getKey().getGroups())){ - vfModules = component.getKey().getGroups().stream().filter(g -> g.getType().equals(BaseOperation.VF_MODULE)).collect(Collectors.toList()); + Either getToscaElementRes = toscaOperationFacade.getToscaElement(componentV); + if(getToscaElementRes.isRight()){ + LOGGER.debug("Failed to fetch the component {}. ", componentV.getUniqueId()); + result = false; + } + else if(CollectionUtils.isNotEmpty(getToscaElementRes.left().value().getGroups())){ + vfModules = getToscaElementRes.left().value().getGroups().stream().filter(g -> g.getType().equals(BaseOperation.VF_MODULE)).collect(Collectors.toList()); } if(vfModules != null){ - vfModules.forEach(vfModule -> vfModule.getProperties().addAll(newGroupTypeProperties)); - StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(component.getValue(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, vfModules, JsonPresentationFields.NAME); + vfModules.forEach(vfModule -> addAllNewProperties(vfModule.getProperties(), updatedProperties)); + StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, vfModules, JsonPresentationFields.NAME); if(status!= StorageOperationStatus.OK){ + LOGGER.debug("Failed to add the new properties {} to groups of component {}. ", updatedProperties, componentV.getUniqueId()); result = false; } } - if(result && CollectionUtils.isNotEmpty(component.getKey().getComponentInstances())){ - result = addPropertiesToVfModuleInstances(component, newGroupTypeProperties); + if(result && CollectionUtils.isNotEmpty(getToscaElementRes.left().value().getComponentInstances())){ + result = addPropertiesToVfModuleInstances(getToscaElementRes.left().value(), componentV, updatedProperties); } return result; } - private boolean addPropertiesToVfModuleInstances(Entry component, List newGroupTypeProperties) { + private void addAllNewProperties(List vfModuleProperties, List updatedProperties) { + Map propertiesMap = vfModuleProperties.stream().collect(Collectors.toMap(p->p.getName(), p->p)); + + for(PropertyDefinition property : updatedProperties){ + if(!propertiesMap.containsKey(property.getName())){ + vfModuleProperties.add(property); + } + } + } + + private boolean addPropertiesToVfModuleInstances(org.openecomp.sdc.be.model.Component component, GraphVertex componentV, List updatedProperties) { boolean result = true; List vfModuleInstances; List pathKeys; - for(ComponentInstance componentInstance : component.getKey().getComponentInstances()){ + LOGGER.debug("Going to add the new properties {} to group instances of component {}. ", updatedProperties, componentV.getUniqueId()); + for(ComponentInstance componentInstance : component.getComponentInstances()){ vfModuleInstances = null; if(CollectionUtils.isNotEmpty(componentInstance.getGroupInstances())){ vfModuleInstances = componentInstance.getGroupInstances() @@ -154,41 +180,25 @@ public class VfModulesPropertiesAdding { } if(vfModuleInstances != null){ for(GroupInstance vfModuleInstance :vfModuleInstances){ - vfModuleInstance.getProperties().addAll(newGroupTypeProperties); + addAllNewProperties(vfModuleInstance.getProperties(),updatedProperties); pathKeys = new ArrayList<>(); pathKeys.add(componentInstance.getUniqueId()); StorageOperationStatus status = topologyTemplateOperation - .updateToscaDataDeepElementOfToscaElement(component.getValue(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, vfModuleInstance, pathKeys, JsonPresentationFields.NAME); + .updateToscaDataDeepElementOfToscaElement(componentV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, vfModuleInstance, pathKeys, JsonPresentationFields.NAME); if(status!= StorageOperationStatus.OK){ result = false; + LOGGER.debug("Failed to add the new properties {} to group instances of component {}. ", updatedProperties, componentV.getUniqueId()); break; } } if(!result){ + LOGGER.debug("Failed to add the new properties {} to group instances of component {}. ", updatedProperties, componentV.getUniqueId()); break; } } } return result; } - - private Either, StorageOperationStatus> getAllContainerComponents(List componentsV) { - Map foundComponents = new HashMap<>(); - Either, StorageOperationStatus> result = null; - for(GraphVertex componentV : componentsV){ - Either getComponentRes = toscaOperationFacade.getToscaElement(componentV); - if(getComponentRes.isRight()){ - result = Either.right(getComponentRes.right().value()); - break; - } - foundComponents.put(getComponentRes.left().value(), componentV); - } - if(result == null){ - result = Either.left(foundComponents); - } - return result; - } - private boolean addNewPropertiesToGroupType(GroupTypeDefinition vfModule, List newProperties) { boolean result = true; 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 c9212f91ca..63eb8879c9 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 @@ -1,20 +1,20 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; -import fj.Function; import fj.data.Either; -import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledCapabilitiesMigrationService; -import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledRequirementsMigrationService; import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.RequirementsCapabilitiesMigrationService; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; +import java.util.List; +import java.util.stream.Collectors; + import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError; public abstract class ComponentMigration extends JsonModelMigration { @@ -27,10 +27,15 @@ public abstract class ComponentMigration extends JsonModel @Resource(name = "req-cap-mig-service") RequirementsCapabilitiesMigrationService requirementsCapabilitiesMigrationService; + @Resource(name = "invariant-uuid-resolver") + private InvariantUUIDResolver invariantUUIDResolver; + @Override - Either save(T element) { + boolean save(T element) { LOGGER.debug(String.format("creating component %s in new graph", element.getName())); - return toscaOperations.createToscaComponent(element).right().map(err -> handleError(err, String.format("failed to create component %s.", element.getName()))); + return toscaOperations.createToscaComponent(element) + .either(savedNode -> true, + err -> handleError(String.format("failed to create component %s with id %s. reason: %s", element.getName(), element.getUniqueId(), err.name()))); } @@ -45,4 +50,26 @@ public abstract class ComponentMigration extends JsonModel return StorageOperationStatus.NOT_FOUND; } + @Override + void doPreMigrationOperation(List elements) { + setMissingInvariantUids(elements); + } + + //some invariants uids are missing in production + private void setMissingInvariantUids(List components) { + List missingInvariantCmpts = getComponentsWithNoInvariantUUIDs(components); + for (T missingInvariantCmpt : missingInvariantCmpts) { + missingInvariantCmpt.setInvariantUUID(invariantUUIDResolver.resolveInvariantUUID(components, missingInvariantCmpt)); + } + } + + private List getComponentsWithNoInvariantUUIDs(List components) { + List cmptsWithoutInvariant = components.stream().filter(c -> c.getInvariantUUID() == null).collect(Collectors.toList()); + if (!cmptsWithoutInvariant.isEmpty()) { + cmptsWithoutInvariant.forEach(cmpt -> MigrationMalformedDataLogger.logMalformedDataMsg(String.format("component %s is missing invariant uuid", cmpt.getUniqueId()))); + } + return cmptsWithoutInvariant; + } + + } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java new file mode 100644 index 0000000000..83078baf6e --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java @@ -0,0 +1,47 @@ +package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; + +import fj.data.Either; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation; +import org.openecomp.sdc.be.resources.data.ConsumerData; + +import javax.annotation.Resource; +import java.util.List; + +import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError; + +public class ConsumersMigration extends JsonModelMigration { + + @Resource(name = "consumer-operation") + private ConsumerOperation consumerOperation; + + @Resource(name = "consumer-operation-mig") + private ConsumerOperation consumerOperationMigration; + + @Override + Either, ?> getElementsToMigrate() { + return consumerOperation.getAll(); + } + + @Override + Either getElementFromNewGraph(ConsumerData element) { + return consumerOperationMigration.getCredentials(element.getConsumerDataDefinition().getConsumerName()); + } + + @Override + boolean save(ConsumerData element) { + return consumerOperationMigration.createCredentials(element) + .either(savedConsumer -> true, + err -> handleError(String.format("failed to save consumer %s. reason: %s", element.getConsumerDataDefinition().getConsumerName(), err.name()))); + } + + @Override + StorageOperationStatus getNotFoundErrorStatus() { + return StorageOperationStatus.NOT_FOUND; + } + + @Override + public String description() { + return "consumers migration"; + } +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java new file mode 100644 index 0000000000..bf28507877 --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java @@ -0,0 +1,41 @@ +package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; + +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +public class InvariantUUIDResolver { + + public String resolveInvariantUUID(List components, T missingInvariantCmpt) { + String uuid = missingInvariantCmpt.getUUID(); + String systemName = missingInvariantCmpt.getSystemName(); + String invariantUid = findInvariantUUidByAllVersionsMap(missingInvariantCmpt, components).orElseGet(() -> findInvariantUUidByUUIDOrSystemName(components, uuid, systemName)); + if (invariantUid == null) { + MigrationMalformedDataLogger.logMalformedDataMsg(String.format("could not find invariant uuid for component %s with id %s", missingInvariantCmpt.getName(), missingInvariantCmpt.getUniqueId())); + } + return invariantUid; + } + + private String findInvariantUUidByUUIDOrSystemName(List components, String uuid, String systemName) { + return components.stream() + .filter(c -> c.getUUID().equals(uuid) || c.getSystemName().equals(systemName)) + .map(Component::getInvariantUUID) + .filter(c -> c != null) + .findAny().orElse(null); + } + + private Optional findInvariantUUidByAllVersionsMap(T component, List allComponents) { + if (component.getAllVersions() == null) return Optional.empty(); + Collection allVersionsComponentIds = component.getAllVersions().values(); + return allComponents.stream().filter(c -> allVersionsComponentIds.contains(c.getUniqueId())) + .map(Component::getInvariantUUID) + .filter(c -> c != null) + .findAny(); + + + } + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java index 6070104d44..4e62b2f497 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java @@ -1,17 +1,19 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; import fj.data.Either; +import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task; import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg; -import org.openecomp.sdc.asdctool.impl.migration.Migration; import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.util.List; -public abstract class JsonModelMigration implements Migration { +public abstract class JsonModelMigration implements Migration1707Task { - private final boolean COMPLETED_OK = true; + private static final Logger LOGGER = LoggerFactory.getLogger(JsonModelMigration.class); @Resource(name = "titan-dao") TitanDao titanDao; @@ -31,7 +33,11 @@ public abstract class JsonModelMigration implements Migration { return true; } + void doPreMigrationOperation(List elements){} + private boolean migrateElementsToNewGraph(List elementsToMigrate) { + LOGGER.info(this.description() + ": starting to migrate elements to new graph. elements to migrate: {}", elementsToMigrate.size()); + doPreMigrationOperation(elementsToMigrate); for (T node : elementsToMigrate) { boolean migratedSuccessfully = migrateElement(node); if (!migratedSuccessfully) { @@ -59,14 +65,10 @@ public abstract class JsonModelMigration implements Migration { } private boolean saveElementIfNotExists(T element) { - return isExists(element).either(isExist -> isExist || createElement(element), + return isExists(element).either(isExist -> isExist || save(element), status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_GET_NODE_FROM_GRAPH.getMessage(status.toString()))); } - private boolean createElement(T element) { - return save(element).either(savedNode -> COMPLETED_OK, - errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_CREATE_NODE.getMessage(element.getClass().getName(), errorStatus.toString()))); - } private Either isExists(T element) { Either byId = getElementFromNewGraph(element); @@ -82,7 +84,7 @@ public abstract class JsonModelMigration implements Migration { abstract Either getElementFromNewGraph(T element); - abstract Either save(T element); + abstract boolean save(T element); abstract S getNotFoundErrorStatus(); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java index 5fc02301dc..82d59e57b7 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java @@ -1,18 +1,22 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; import fj.data.Either; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import jersey.repackaged.com.google.common.collect.Sets; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; +import java.util.Optional; +import java.util.Set; public class NormativesMigration extends ComponentMigration { private static Logger LOGGER = LoggerFactory.getLogger(NormativesMigration.class); + private static final String JCP_VERSION_PROPERTY = "jcp-version"; + private static final Set e2eMalformedVfcs = Sets.newHashSet("71879ee1-ad63-46d0-9943-d33083a6fdbb", "e54e7c4d-6020-4c53-838b-42d34c0da5c9"); @javax.annotation.Resource(name = "normatives-resolver") private NormativesResolver normativesResolver; @@ -30,6 +34,30 @@ public class NormativesMigration extends ComponentMigration { return normativesResolver.getAllNodeTypeNormatives(); } + @Override + boolean save(Resource element) { + if (e2eMalformedVfcs.contains(element.getUniqueId())) { + replaceJcpVersionPropertyTypeToVersion(element); + } + return super.save(element); + } + + private void replaceJcpVersionPropertyTypeToVersion(Resource element) { + getJcpIntegerProperty(element).ifPresent(propertyDefinition -> { + LOGGER.info("resource {} with id {}: found property jcp-version with type 'integer', changing type to 'version'", element.getName(), element.getUniqueId()); + propertyDefinition.setType(ToscaPropertyType.VERSION.getType()); + }); + } + + private Optional getJcpIntegerProperty(Resource element) { + if (element.getProperties() == null) return Optional.empty(); + return element.getProperties().stream() + .filter(prop -> prop.getName().equals(JCP_VERSION_PROPERTY)) + .filter(prop -> prop.getType().equals(ToscaPropertyType.INTEGER.getType())) + .findAny(); + + } + @Override boolean doPostMigrateOperation(List elements) { LOGGER.info("migrating node types versions"); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java index 01654d284f..5285c4c406 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java @@ -2,7 +2,7 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; import fj.data.Either; import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg; -import org.openecomp.sdc.asdctool.impl.migration.Migration; +import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task; import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -11,6 +11,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import javax.annotation.Resource; import java.util.ArrayList; @@ -22,7 +23,7 @@ import static org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.Categori import static org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.CategoriesUtils.filterOldSubCategories; -public class ResourcesCategoriesMigration implements Migration { +public class ResourcesCategoriesMigration implements Migration1707Task { @Resource(name = "element-operation") private IElementOperation elementOperation; @@ -74,7 +75,10 @@ public class ResourcesCategoriesMigration implements Migration { } private List getAllDistinctSubCategories (List categoriesDefinitions) { - Map> subCategoriesByNormalName = categoriesDefinitions.stream().flatMap(ct -> ct.getSubcategories().stream()).collect(Collectors.groupingBy(SubCategoryDefinition::getNormalizedName)); + Map> subCategoriesByNormalName = categoriesDefinitions.stream() + .filter(ct -> ct.getSubcategories()!=null) + .flatMap(ct -> ct.getSubcategories().stream()) + .collect(Collectors.groupingBy(SubCategoryDefinition::getNormalizedName)); return getDistinctSubCategories(subCategoriesByNormalName); } @@ -112,7 +116,7 @@ public class ResourcesCategoriesMigration implements Migration { } private boolean migrateSubcategoryIfNotExists(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) { - return isExists(subCategory).either(isExists -> isExists || migrateSubCategory(parentCategory, subCategory), + return isExists(parentCategory, subCategory).either(isExists -> isExists || migrateSubCategory(parentCategory, subCategory), status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORY.getMessage(subCategory.getName(), status.name()))); } @@ -124,13 +128,13 @@ public class ResourcesCategoriesMigration implements Migration { } private Either isExists(CategoryDefinition category) { - Either byId = getCategoryById(category.getUniqueId()); + Either byId = getCategoryById(category); return byId.either(existingVal -> Either.left(true), this::getEitherNotExistOrErrorStatus); } - private Either isExists(SubCategoryDefinition subCategory) { - return getSubCategoryById(subCategory.getUniqueId()).either(existingVal -> Either.left(true), + private Either isExists(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) { + return getSubCategoryById(parentCategory, subCategory).either(existingVal -> Either.left(true), this::getEitherNotExistOrErrorStatus); } @@ -138,12 +142,19 @@ public class ResourcesCategoriesMigration implements Migration { return status == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND ? Either.left(false) : Either.right(status); } - private Either getCategoryById(String uid) { - return elementOperationMigration.getCategory(NodeTypeEnum.ResourceNewCategory, uid); + private Either getCategoryById(CategoryDefinition category) { + return elementOperationMigration.getCategory(NodeTypeEnum.ResourceNewCategory, category.getUniqueId()); } - private Either getSubCategoryById(String uid) { - return elementOperationMigration.getSubCategory(NodeTypeEnum.ResourceSubcategory, uid); + private Either getSubCategoryById(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) { + String subCategoryUid = getExpectedSubCategoryId(parentCategory, subCategory); + return elementOperationMigration.getSubCategory(NodeTypeEnum.ResourceSubcategory, subCategoryUid); + } + + //since a sub category might belong to a different category in old graph its new graph id is different than its old graph id + private String getExpectedSubCategoryId(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) { + String parentId = UniqueIdBuilder.buildCategoryUid(parentCategory.getNormalizedName(), NodeTypeEnum.ResourceNewCategory); + return UniqueIdBuilder.buildSubCategoryUid(parentId, subCategory.getNormalizedName()); } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java index f745b88d02..f8f79ad9ba 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java @@ -10,6 +10,8 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import javax.annotation.Resource; import java.util.List; +import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError; + public class ServiceCategoriesMigration extends JsonModelMigration { @Resource(name = "element-operation") @@ -31,12 +33,15 @@ public class ServiceCategoriesMigration extends JsonModelMigration getElementFromNewGraph(CategoryDefinition node) { - return elementOperationMigration.getCategory(NodeTypeEnum.ServiceNewCategory, node.getUniqueId()); + String categoryUid = UniqueIdBuilder.buildCategoryUid(node.getNormalizedName(), NodeTypeEnum.ServiceNewCategory);//in malformed graph there are some categories with different id but same normalized name. so in new graph they same id + return elementOperationMigration.getCategory(NodeTypeEnum.ServiceNewCategory, categoryUid); } @Override - Either save(CategoryDefinition graphNode) { - return elementOperationMigration.createCategory(graphNode, NodeTypeEnum.ServiceNewCategory); + boolean save(CategoryDefinition graphNode) { + return elementOperationMigration.createCategory(graphNode, NodeTypeEnum.ServiceNewCategory) + .either(savedCategory -> true, + err -> handleError(String.format("failed to save category %s. error: %s", graphNode.getName(), err.name()))); } @Override diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java index f5ff96284f..254a75b317 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java @@ -1,25 +1,23 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; import fj.data.Either; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.operations.api.IServiceOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.migration.MigrationErrorInformer; +import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class ServicesMigration extends ComponentMigration { + private static final String DEFAULT_CONFORMANCE_LEVEL = "0.0"; private static Logger LOGGER = LoggerFactory.getLogger(ServicesMigration.class); @Resource(name = "service-operation") @@ -39,10 +37,10 @@ public class ServicesMigration extends ComponentMigration { } @Override - Either save(Service element) { - MigrationErrorInformer.logIfServiceUsingMalformedVfs(element); - filterOutVFInstancePropsAndAttrs(element); - element.setConformanceLevel("0.0"); + boolean save(Service element) { + MigrationMalformedDataLogger.logIfServiceUsingMalformedVfs(element); + filterOutDuplicatePropsAndAttrs(element); + element.setConformanceLevel(DEFAULT_CONFORMANCE_LEVEL); requirementsCapabilitiesMigrationService.overrideInstanceCapabilitiesRequirements(element); return super.save(element); } @@ -60,48 +58,95 @@ public class ServicesMigration extends ComponentMigration { return versionMigration.buildComponentsVersionChain(elements); } - private void filterOutVFInstancePropsAndAttrs(Service element) { - if (element.getComponentInstances() != null) { - List vfInstancesIds = getVFInstancesIds(element); - filterOutVFInstacnecProps(element, vfInstancesIds); - filterOutVFInstanceAttrs(element, vfInstancesIds); + private void filterOutDuplicatePropsAndAttrs(Service element) { + if (element.getComponentInstancesProperties() != null) { + removeDuplicatedNameProperties(element); } + if (element.getComponentInstancesAttributes() != null) { + removeDuplicatedNameAttributes(element); + } + } + + private void removeDuplicatedNameProperties(Service service) { + Map> componentInstancesProperties = service.getComponentInstancesProperties(); + componentInstancesProperties.forEach((uid, properties) -> { + componentInstancesProperties.put(uid, getUniquedNamePropertyList(service, properties)); + }); } - private void filterOutVFInstanceAttrs(Service element, List vfInstancesIds) { - Map> componentInstancesAttributes = element.getComponentInstancesAttributes(); - if (componentInstancesAttributes != null) { - element.setComponentInstancesAttributes(filterOutVFInstanceAttributes(componentInstancesAttributes, vfInstancesIds)); + private List getUniquedNamePropertyList(Service service, List properties) { + if (properties == null) { + return null; } + List uniqueNameProperties = new ArrayList<>(); + Map> collect = properties.stream().collect(Collectors.groupingBy(ComponentInstanceProperty::getName)); + collect.forEach((name, duplicatedProperties) -> { + logServiceDuplicateProperties(service, name, duplicatedProperties); + uniqueNameProperties.add(duplicatedProperties.get(0)); + }); + return uniqueNameProperties; } - private void filterOutVFInstacnecProps(Service element, List vfInstancesIds) { - Map> componentInstancesProperties = element.getComponentInstancesProperties(); - if (componentInstancesProperties != null) { - element.setComponentInstancesProperties(filterOutVFInstanceProperties(componentInstancesProperties, vfInstancesIds)); + private void logServiceDuplicateProperties(Service service, String name, List duplicatedProperties) { + if (duplicatedProperties.size() > 1) { + LOGGER.debug("service {} with id {} has instance {} with duplicate property {}", service.getName(), service.getUniqueId(), duplicatedProperties.get(0).getUniqueId(), name); } } - private Map> filterOutVFInstanceProperties(Map> instances, List vfInstanceIds) { - return instances.entrySet() - .stream() - .filter(entry -> !vfInstanceIds.contains(entry.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + private void removeDuplicatedNameAttributes(Service service) { + Map> componentInstancesAttributes = service.getComponentInstancesAttributes(); + componentInstancesAttributes.forEach((uid, attributes) -> { + componentInstancesAttributes.put(uid, getUniquedNameAttributeList(service, attributes)); + }); } - private Map> filterOutVFInstanceAttributes(Map> instances, List vfInstanceIds) { - return instances.entrySet() - .stream() - .filter(entry -> !vfInstanceIds.contains(entry.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + private List getUniquedNameAttributeList(Service service, List attributes) { + if (attributes == null) { + return null; + } + List uniqueNameAttributes = new ArrayList<>(); + Map> collect = attributes.stream().collect(Collectors.groupingBy(ComponentInstanceProperty::getName)); + collect.forEach((name, duplicatedAttributess) -> { + logServiceMalformedAttributes(service, name, duplicatedAttributess); + uniqueNameAttributes.add(duplicatedAttributess.get(0)); + }); + return uniqueNameAttributes; } - private List getVFInstancesIds(Service service) { - return service.getComponentInstances() - .stream() - .filter(componentInstance -> componentInstance.getOriginType() == OriginTypeEnum.VF) - .map(ComponentInstanceDataDefinition::getUniqueId) - .collect(Collectors.toList()); + private void logServiceMalformedAttributes(Service service, String name, List duplicatedAttributess) { + if (duplicatedAttributess.size() > 1) { + MigrationMalformedDataLogger.logMalformedDataMsg(String.format("service %s with id %s has instance %s with duplicate attribute %s", + service.getName(), service.getUniqueId(), duplicatedAttributess.get(0).getUniqueId(), name)); + } } + // private void filterOutVFInstanceAttrs(Service element, List vfInstancesIds) { +// Map> componentInstancesAttributes = element.getComponentInstancesAttributes(); +// if (componentInstancesAttributes != null) { +// element.setComponentInstancesAttributes(filterOutVFInstanceAttributes(componentInstancesAttributes, vfInstancesIds)); +// } +// } +// +// private void filterOutVFInstacnecProps(Service element, List vfInstancesIds) { +// Map> componentInstancesProperties = element.getComponentInstancesProperties(); +// if (componentInstancesProperties != null) { +// element.setComponentInstancesProperties(filterOutVFInstanceProperties(componentInstancesProperties, vfInstancesIds)); +// } +// } +// +// private Map> filterOutVFInstanceProperties(Map> instances, List vfInstanceIds) { +// return instances.entrySet() +// .stream() +// .filter(entry -> !vfInstanceIds.contains(entry.getKey())) +// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); +// } +// +// private Map> filterOutVFInstanceAttributes(Map> instances, List vfInstanceIds) { +// return instances.entrySet() +// .stream() +// .filter(entry -> !vfInstanceIds.contains(entry.getKey())) +// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); +// } + + } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java index b248d90bd2..67d9235cee 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java @@ -7,7 +7,6 @@ import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg; -import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -23,6 +22,7 @@ import java.util.List; import java.util.stream.Collectors; import static fj.data.List.list; +import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError; public class UserStatesMigration extends JsonModelMigration { @@ -71,9 +71,16 @@ public class UserStatesMigration extends JsonModelMigration { } @Override - Either save(Edge userState) { + boolean save(Edge userState) { Either titanVertices = findEdgeInOutVerticesInNewGraph(userState); - return titanVertices.left().bind(inOutVertices -> genericDaoMigration.copyEdge(inOutVertices.getOutVertex(), inOutVertices.getInVertex(), userState)); + return titanVertices.either(inOutVertices -> saveUserState(inOutVertices, userState), + err -> handleError(String.format("could not find user edge %s in vertx. error: %s", userState.label(), err.name()))); + } + + private boolean saveUserState(InOutVertices inOutVertices, Edge userState) { + return genericDaoMigration.copyEdge(inOutVertices.getOutVertex(), inOutVertices.getInVertex(), userState) + .either(edge -> true, + err -> handleError(String.format("failed to save user state edge %s. reason: %s", userState.label(), err.name()))); } @Override @@ -125,7 +132,7 @@ public class UserStatesMigration extends JsonModelMigration { String vertexUniqueId = getVertexUniqueId(vertex); LOGGER.debug(String.format("fetching vertex %s from new graph", vertexUniqueId)); return genericDaoMigration.getVertexByProperty(vertexUniqueId, vertex.property(vertexUniqueId).value()) - .right().map(err -> MigrationUtils.handleError(err, String.format("could not find vertex %s in new graph.", vertexUniqueId))) ; + .right().map(err -> handleError(err, String.format("could not find vertex %s in new graph.", vertexUniqueId))) ; } // private boolean deleteAllEdges(UserData userData, Direction direction) { @@ -154,6 +161,7 @@ public class UserStatesMigration extends JsonModelMigration { TitanVertex getInVertex() { return inVertex; } + } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java index 9dd3fc4853..a578f066bf 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java @@ -1,13 +1,10 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; -import fj.Function; import fj.data.Either; -import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,13 +33,16 @@ public class UsersMigration extends JsonModelMigration { @Override Either getElementFromNewGraph(User user) { LOGGER.debug(String.format("trying to load user %s from new graph", user.getUserId())); - return userAdminOperationMigration.getUserData(user.getUserId(), false); + return user.getStatus().equals(UserStatusEnum.ACTIVE) ? userAdminOperationMigration.getUserData(user.getUserId(), false) : + userAdminOperationMigration.getInactiveUserData(user.getUserId()); } @Override - Either save(User user) { + boolean save(User user) { LOGGER.debug(String.format("trying to save user %s to new graph", user.getUserId())); - return userAdminOperationMigration.saveUserData(user); + return userAdminOperationMigration.saveUserData(user) + .either(savedUser -> true, + err -> handleError(String.format("failed when saving user %s. error %s", user.getUserId(), err.name()))); } @Override diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java index b684883323..34c40f0aa9 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java @@ -31,7 +31,7 @@ public class VFResourcesMigration extends ComponentMigration { } @Override - Either save(Resource element) { + boolean save(Resource element) { requirementsCapabilitiesMigrationService.overrideInstanceCapabilitiesRequirements(element); return super.save(element); } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java index 7dadd79a1b..145ae28c81 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java @@ -1,9 +1,7 @@ package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel; import fj.data.Either; -import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.asdctool.impl.migration.MigrationException; import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg; import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -13,7 +11,6 @@ import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,8 +33,7 @@ public abstract class VersionMigration { private TitanDao titanDao; public boolean buildComponentsVersionChain(List components) { - setMissingInvariantUid(components); - Map> componentsByInvariant = components.stream().collect(Collectors.groupingBy(Component::getInvariantUUID)); + Map> componentsByInvariant = components.stream().filter(c -> c.getInvariantUUID() != null).collect(Collectors.groupingBy(Component::getInvariantUUID)); for (List componentsList : componentsByInvariant.values()) { boolean versionChainBuilt = buildVersionChainForInvariant(componentsList); if (!versionChainBuilt) { @@ -63,7 +59,7 @@ public abstract class VersionMigration { } private void sortComponentsByVersion(List components) { - Collections.sort(components, (o1, o2) -> o1.getVersion().compareTo(o2.getVersion())); + Collections.sort(components, (o1, o2) -> Double.valueOf(o1.getVersion()).compareTo(Double.valueOf(o2.getVersion()))); } private boolean createVersionRelationIfNotExist(String fromUid, String toUid) { @@ -74,10 +70,10 @@ public abstract class VersionMigration { private boolean createVersionRelation(String fromUid, String toUid) { LOGGER.debug(String.format("creating version edge between vertex %s and vertex %s", fromUid, toUid)); - Either vertexById = titanDao.getVertexById(fromUid); - Either vertexById1 = titanDao.getVertexById(toUid); - if (vertexById1.isLeft() && vertexById.isLeft()) { - TitanOperationStatus versionCreated = titanDao.createEdge(vertexById.left().value(), vertexById1.left().value(), EdgeLabelEnum.VERSION, new HashMap<>()); + Either fromVertex = titanDao.getVertexById(fromUid); + Either toVertex = titanDao.getVertexById(toUid); + if (toVertex.isLeft() && fromVertex.isLeft()) { + TitanOperationStatus versionCreated = titanDao.createEdge(fromVertex.left().value(), toVertex.left().value(), EdgeLabelEnum.VERSION, new HashMap<>()); return versionCreated == TitanOperationStatus.OK; } return MigrationUtils.handleError(String.format("could not create version edge between vertex %s and vertex %s.", fromUid, toUid)); @@ -99,28 +95,4 @@ public abstract class VersionMigration { } abstract NodeTypeEnum getNodeTypeEnum(); - - //some invariatn uids are missing in production - private void setMissingInvariantUid(List components) { - List missingInvariantCmpts = getComponentsWithNoInvariantUids(components); - for (T missingInvariantCmpt : missingInvariantCmpts) { - String uuid = missingInvariantCmpt.getUUID(); - missingInvariantCmpt.setInvariantUUID(findInvariantUidOrElseFail(components, uuid)); - } - } - - private List getComponentsWithNoInvariantUids(List components) { - List cmptsWithoutInvariant = components.stream().filter(c -> c.getInvariantUUID() == null).collect(Collectors.toList()); - LOGGER.info(String.format("the following components are missing invariant uids: %s", StringUtils.join(cmptsWithoutInvariant.stream().map(Component::getUniqueId).collect(Collectors.toList()), ","))); - return cmptsWithoutInvariant; - } - - private String findInvariantUidOrElseFail(List components, String uuid) { - return components.stream() - .filter(c -> c.getUUID().equals(uuid)) - .map(Component::getInvariantUUID) - .filter(c -> c != null) - .findAny().orElseThrow(() -> new MigrationException(String.format("cannot find invariantuid for component with uuid %s", uuid))); - } - } 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 c914e3b082..c3d8743b86 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 @@ -35,6 +35,8 @@ 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.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.be.config.ConfigurationManager; import org.openecomp.sdc.common.api.ConfigurationSource; @@ -64,7 +66,10 @@ public class MigrationMenu { FIX_ICONS("fix-icons", "titanFixUtils"), MIGRATION_1610_1702("migrate-1610-1702", "migration1702"), MIGRATION_1702_1707("migrate-1702-1707", "migration1707"), - VFMODULES_PROPERTIES_ADDING("vfModules-properties-adding", "vfModulesPropertiesAdding"); + DISTRIBUTION_STATUS_UPDATE_1707("distribution-status-update-1707", "distributionStatusUpdate"), + VFMODULES_PROPERTIES_ADDING("vfModules-properties-adding", "vfModulesPropertiesAdding"), + MIGRATION_1707_RELATIONS_FIX("fix-relations-after-migration-1707", "migration1707relationsFix"), + MIGRATION_1707_VNF_FIX("fix-vnf-after-migration-1707", "migration1707vnfFix"); // UPDATE_DATA_TYPES("update_data_types", "updateDataTypes"); private String value, beanName; @@ -238,9 +243,8 @@ public class MigrationMenu { } break; - case MIGRATION_1702_1707: + 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"); - System.exit(0); // Migration1707 migration1707 = (Migration1707) context.getBean(operationEnum.getBeanName()); // isSuccessful = migration1707.migrate(); // if (isSuccessful) { @@ -250,18 +254,59 @@ public class MigrationMenu { // log.info("SDC migration from 1702 to 1707 has failed"); // System.exit(2); // } + System.exit(0); break; - case VFMODULES_PROPERTIES_ADDING: - log.info("Start adding new properties to vfModules"); - VfModulesPropertiesAdding migrationVfModulesProperties = (VfModulesPropertiesAdding) context.getBean(operationEnum.getBeanName()); - isSuccessful = migrationVfModulesProperties.migrate(args[1]); - if (isSuccessful) { - log.info("Adding new properties to vfModules was finished successfully"); - System.exit(0); - } else{ - log.info("Adding new properties to vfModules has failed"); - System.exit(2); - } + case VFMODULES_PROPERTIES_ADDING://this migration is currently not needed, but will be commented out for production env +// log.info("Start adding new properties to vfModules"); +// VfModulesPropertiesAdding migrationVfModulesProperties = (VfModulesPropertiesAdding) context.getBean(operationEnum.getBeanName()); +// isSuccessful = migrationVfModulesProperties.migrate(args[1]); +// if (isSuccessful) { +// log.info("Adding new properties to vfModules was finished successfully"); +// System.exit(0); +// } else{ +// log.info("Adding new properties to vfModules has failed"); +// System.exit(2); +// } + System.exit(0); + break; + case MIGRATION_1707_VNF_FIX://this migration is currently not needed, but will be commented out for production env +// log.info("Start fixing vnf after 1707 migration"); +// Migration1707VnfFix migrationVnfFix = (Migration1707VnfFix) context.getBean(operationEnum.getBeanName()); +// isSuccessful = migrationVnfFix.migrate(); +// if (isSuccessful) { +// log.info("Fixing VNFs after 1707 migration was finished successfully"); +// System.exit(0); +// } else{ +// log.info("Fixing VNFs after 1707 migration has failed"); +// System.exit(2); +// } + System.exit(0); + break; + case DISTRIBUTION_STATUS_UPDATE_1707://not needed can be dropped +// log.info("Start Distribution status update 1707"); +// DistributionStatusUpdate distStatusUpdate = (DistributionStatusUpdate) context.getBean(operationEnum.getBeanName()); +// isSuccessful = distStatusUpdate.migrate(); +// if (isSuccessful) { +// log.info("ASDC Distribution status update 1707 was finished successful"); +// System.exit(0); +// } else{ +// log.info("ASDC Distribution status update 1707 has failed"); +// System.exit(2); +// } + System.exit(0); + break; + case MIGRATION_1707_RELATIONS_FIX://not needed can be dropped +// log.info("Start fixing relations after 1707 migration"); +// Migration migrationFix = (Migration1707RelationsFix) context.getBean(operationEnum.getBeanName()); +// isSuccessful = migrationFix.migrate(); +// if (isSuccessful) { +// log.info("Fixing relations after 1707 migration was finished successfully"); +// System.exit(0); +// } else{ +// log.info("Fixing relations after 1707 migration has failed"); +// System.exit(2); +// } + System.exit(0); break; default: usageAndExit(); @@ -298,6 +343,9 @@ public class MigrationMenu { System.out.println("Usage: migrate-1610-1702 "); System.out.println("Usage: migrate-1702-1707 "); System.out.println("Usage: update_data_types "); + System.out.println("Usage: distribution-status-update-1707"); System.out.println("Usage: vfModules-properties-adding "); + System.out.println("Usage: fix-relations-after-migration-1707 "); + System.out.println("Usage: fix-vnf-after-migration-1707 "); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java new file mode 100644 index 0000000000..edeb56787b --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.asdctool.main; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Date; + +import org.apache.commons.codec.digest.DigestUtils; +import org.openecomp.sdc.asdctool.impl.EsToCassandraDataMigrationConfig; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + + +public class SdcSchemaFileImport { + + private static SdcSchemaFilesCassandraDao schemaFilesCassandraDao; + + public static void main(String[] args) throws Exception { + + final String FILE_NAME = "SDC.zip"; + + if (args == null || args.length < 4) { + usageAndExit(); + } + + String pathAndFile = args[0]; + String sdcReleaseNum = args[1]; + String conformanceLevel = args[2]; + String appConfigDir = args[3]; + + File file = new File(pathAndFile); + if(!file.exists()){ + System.out.println("The file or path does not exist"); + System.exit(1); + } else if(!file.isFile()){ + System.out.println("Specify the file name"); + System.exit(1); + } + + AnnotationConfigApplicationContext context = initContext(appConfigDir); + schemaFilesCassandraDao = (SdcSchemaFilesCassandraDao) context.getBean("sdc-schema-files-cassandra-dao"); + + Path path = Paths.get(pathAndFile); + byte[] fileBytes = Files.readAllBytes(path); + + Date date = new Date(); + String md5Hex = DigestUtils.md5Hex(fileBytes); + + SdcSchemaFilesData schemeFileData = new SdcSchemaFilesData(sdcReleaseNum, date, conformanceLevel, FILE_NAME, fileBytes, md5Hex); + CassandraOperationStatus saveSchemaFile = schemaFilesCassandraDao.saveSchemaFile(schemeFileData); + + if(!saveSchemaFile.equals(CassandraOperationStatus.OK)){ + System.out.println("SdcSchemaFileImport failed cassandra error" + saveSchemaFile); + System.exit(1); + } + + System.out.println("SdcSchemaFileImport successfully completed"); + + System.exit(0); + } + + private static void usageAndExit(){ + SdcSchemaFileImportUsage(); + System.exit(1); + } + + private static void SdcSchemaFileImportUsage(){ + System.out.println("Usage: "); + } + + private static AnnotationConfigApplicationContext initContext(String appConfigDir) { + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EsToCassandraDataMigrationConfig.class); + return context; + } +} diff --git a/asdctool/src/main/resources/config/configuration.yaml b/asdctool/src/main/resources/config/configuration.yaml index d376ba3c0e..beca6c98aa 100644 --- a/asdctool/src/main/resources/config/configuration.yaml +++ b/asdctool/src/main/resources/config/configuration.yaml @@ -25,8 +25,8 @@ beSslPort: 8443 version: 1.0 released: 2012-11-30 -titanCfgFile: C:\Git_work\Git_UGN\d2-sdnc\asdctool\src\main\resources\config\titan.properties -titanMigrationKeySpaceCfgFile: C:\Git_work\Git_UGN\d2-sdnc\asdctool\src\main\resources\config\titan-migration.properties +titanCfgFile: src\main\resources\config\titan.properties +titanMigrationKeySpaceCfgFile: src\main\resources\config\titan-migration.properties titanInMemoryGraph: false titanLockTimeout: 1800 titanReconnectIntervalInSeconds: 3 diff --git a/asdctool/src/main/resources/config/groupTypes.yml b/asdctool/src/main/resources/config/groupTypes.yml index c72dc88c53..ce457e4add 100644 --- a/asdctool/src/main/resources/config/groupTypes.yml +++ b/asdctool/src/main/resources/config/groupTypes.yml @@ -63,7 +63,20 @@ org.openecomp.groups.VfModule: Group. VID operator must select the Volume Group instance to attach to a VF-Module at deployment time. - + availability_zone_count: + type: integer + required: false + description: > + Quantity of Availability Zones needed for this VF-Module + (source: Extracted from VF-Module HEAT template) + vfc_list: + type: map + entry_schema: + description: : + type: string + required: false + description: > + Identifies the set of VM types and their count included in the VF-Module tosca.groups.Root: description: The TOSCA Group Type all other TOSCA Group Types derive from interfaces: diff --git a/asdctool/src/main/resources/config/logback.xml b/asdctool/src/main/resources/config/logback.xml index 87795ae163..0426a32d9e 100644 --- a/asdctool/src/main/resources/config/logback.xml +++ b/asdctool/src/main/resources/config/logback.xml @@ -1,7 +1,7 @@ - - + + @@ -36,9 +36,33 @@ + + ${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/malformed-data.log + + + ${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/malformed-data.log.%i + + 1 + 10 + + + + 20MB + + + ${default-log-pattern} + + + + + + + \ No newline at end of file diff --git a/asdctool/src/main/resources/scripts/dataMigration1707.sh b/asdctool/src/main/resources/scripts/dataMigration1707.sh index e67de2a540..11a151a7c3 100644 --- a/asdctool/src/main/resources/scripts/dataMigration1707.sh +++ b/asdctool/src/main/resources/scripts/dataMigration1707.sh @@ -18,7 +18,7 @@ source ${FULL_PATH}/baseOperation.sh mainClass="org.openecomp.sdc.asdctool.main.MigrationMenu" -command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1702-1707 $@" +command="java $JVM_LOG_FILE -Xmx6000M -cp $JARS $mainClass migrate-1702-1707 $@" echo $command $command diff --git a/asdctool/src/main/resources/scripts/distributionStatusUpdate1707.sh b/asdctool/src/main/resources/scripts/distributionStatusUpdate1707.sh new file mode 100644 index 0000000000..a9d308f933 --- /dev/null +++ b/asdctool/src/main/resources/scripts/distributionStatusUpdate1707.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +############################## +# Distribution Status Update 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 -cp $JARS $mainClass distribution-status-update-1707 $@" +echo $command + +$command +result=$? + + + +echo "***********************************" +echo "***** $result *********************" +echo "***********************************" + +exit $result + + diff --git a/asdctool/src/main/resources/scripts/migration1707RelationsFix.sh b/asdctool/src/main/resources/scripts/migration1707RelationsFix.sh new file mode 100644 index 0000000000..c930243750 --- /dev/null +++ b/asdctool/src/main/resources/scripts/migration1707RelationsFix.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +############################## +# Data Migration: fix relations after 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 -cp $JARS $mainClass fix-relations-after-migration-1707 $@" +echo $command + +$command +result=$? + +echo "***********************************" +echo "***** $result *********************" +echo "***********************************" + +exit $result + + diff --git a/asdctool/src/main/resources/scripts/retrieve_schema_file.sh b/asdctool/src/main/resources/scripts/retrieve_schema_file.sh new file mode 100644 index 0000000000..f66b530f20 --- /dev/null +++ b/asdctool/src/main/resources/scripts/retrieve_schema_file.sh @@ -0,0 +1,20 @@ +#!/bin/sh + +cass_user=asdc_user +cass_pass='Aa1234%^!' +sdcReleaseNum=$1 +conformanceLevel=$2 + +CQLSH="/home/vagrant/cassandra/apache-cassandra-2.1.9/bin/cqlsh" + + + ### Get payload + + select_payload="select payload from sdcartifact.sdcschemafiles where conformanceLevel='$conformanceLevel' and sdcReleaseNum='$sdcReleaseNum'" + + echo "Run: [$select_payload]" + +$CQLSH -e "$select_payload" |grep "0x" |xxd -r -p > SDC-downloaded.zip + +res=$? +echo "After select payload, res=[$res]" \ No newline at end of file diff --git a/asdctool/src/main/resources/scripts/vfmoduleFix1707.sh b/asdctool/src/main/resources/scripts/vfmoduleFix1707.sh new file mode 100644 index 0000000000..48579242bf --- /dev/null +++ b/asdctool/src/main/resources/scripts/vfmoduleFix1707.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +############################## +# Distribution Status Update 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 -cp $JARS $mainClass fix-vnf-after-migration-1707 $@" +echo $command + +$command +result=$? + + + +echo "***********************************" +echo "***** $result *********************" +echo "***********************************" + +exit $result + + diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml index e53069cf5a..6f35b3a5a1 100644 --- a/catalog-be/pom.xml +++ b/catalog-be/pom.xml @@ -24,7 +24,7 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml - ${jackson.version} + ${jackson.yaml.version} compile @@ -450,7 +450,7 @@ org.openecomp.ecompsdkos - ecompFW + epsdk-fw ${ecomp.version} compile diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java new file mode 100644 index 0000000000..95f1edd61f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.components; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + +public interface ArtifactsResolver { + + /** + * searching for an artifact with the give {@code artifactId} on the given {@code component} + * @param component the component to look for artifact in + * @param componentType the type of the component to look for artifact in + * @param artifactId the id of the artifact to find + * @return the found artifact or null if not exist + */ + ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId); + + /** + * searching for an artifact with the give {@code artifactId} on the given {@code componentInstance} + * @param componentInstance the component instance to look for the artifact in + * @param artifactId the if of the artifact to find + * @return the found artifact or null if not exist + */ + ArtifactDefinition findArtifactOnComponentInstance(ComponentInstance componentInstance, String artifactId); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java index d1b445b065..5efcfe7fa8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java @@ -118,4 +118,11 @@ public class JsonContainerResourceInstance { public void setSubcategory(String subcategory) { this.subcategory = subcategory; } + + @Override + public String toString() { + return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]"; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java index 8a2ef8e63b..149499811f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java @@ -77,9 +77,11 @@ public class NotificationDataImpl implements INotificationData { this.serviceDescription = serviceDescription; } + @Override public String toString() { - return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceInvariantUUID=" + serviceInvariantUUID + "]"; + return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription=" + serviceDescription + + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources + ", serviceArtifacts=" + serviceArtifacts + "]"; } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java index 71593fa99a..2bcaa4f54a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java @@ -62,6 +62,8 @@ public class VfModuleArtifactPayload { vfModuleModelDescription = group.getDescription(); artifacts = group.getArtifactsUuid(); + artifacts.addAll(group.getGroupInstanceArtifactsUuid()); + // Base Value is set from properties setBaseValue(group); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java new file mode 100644 index 0000000000..7ef3a1961f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java @@ -0,0 +1,62 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.be.components.ArtifactsResolver; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.Service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@org.springframework.stereotype.Component("artifact-resolver") +public class ArtifactResolverImpl implements ArtifactsResolver { + + @Override + public ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId) { + List allComponentsArtifacts = getAllComponentsArtifacts(component, componentType); + return findById(allComponentsArtifacts, artifactId); + + } + + @Override + public ArtifactDefinition findArtifactOnComponentInstance(ComponentInstance componentInstance, String artifactId) { + List allInstanceArtifacts = getAllInstanceArtifacts(componentInstance); + return findById(allInstanceArtifacts, artifactId); + } + + private ArtifactDefinition findById(List artifacts, String artifactId) { + return artifacts.stream() + .filter(artifact -> artifact.getUniqueId().equals(artifactId)) + .findFirst().orElse(null); + } + + private List getAllComponentsArtifacts(Component component, ComponentTypeEnum componentType) { + Map deploymentArtifacts = Optional.ofNullable(component.getDeploymentArtifacts()).orElse(Collections.emptyMap()); + Map artifacts = Optional.ofNullable(component.getArtifacts()).orElse(Collections.emptyMap()); + Map serviceApiArtifacts = Collections.emptyMap(); + if (componentType.equals(ComponentTypeEnum.SERVICE)) { + serviceApiArtifacts = Optional.ofNullable(((Service) component).getServiceApiArtifacts()).orElse(Collections.emptyMap()); + } + return appendAllArtifacts(deploymentArtifacts, artifacts, serviceApiArtifacts); + } + + private List getAllInstanceArtifacts(ComponentInstance instance) { + Map deploymentArtifacts = Optional.ofNullable(instance.getDeploymentArtifacts()).orElse(Collections.emptyMap()); + Map artifacts = Optional.ofNullable(instance.getArtifacts()).orElse(Collections.emptyMap()); + return appendAllArtifacts(deploymentArtifacts, artifacts); + } + + @SafeVarargs + private final List appendAllArtifacts(Map... artifacts) { + List allArtifacts = new ArrayList<>(); + Arrays.stream(artifacts).forEach(a -> allArtifacts.addAll(a.values())); + return allArtifacts; + } + +} 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 6739d28bd4..83c8183a01 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 @@ -43,6 +43,7 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; @@ -180,6 +181,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @Autowired NodeTemplateOperation nodeTemplateOperation; + @Autowired + private ArtifactsResolver artifactsResolver; + public ArtifactsBusinessLogic() { // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { @@ -609,22 +613,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { List list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); - if (list != null && !list.isEmpty()){ + if (list != null && !list.isEmpty()) { resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); - }else{ + } else { resMap = new HashMap<>(); } resultOp = Either.left(resMap); return resultOp; } else { - Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId ); + Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId); if (artifactsMapStatus.isRight()) { if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); resultOp = Either.right(responseFormat); - }else{ + } else { resMap = new HashMap<>(); resultOp = Either.left(resMap); } @@ -934,7 +938,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (validateAndSetArtifactname.isRight()) { return Either.right(validateAndSetArtifactname.right().value()); } - Either artifactById = findArtifactOnParentComponent(parentComponent, parentId, operation, artifactId); + Either artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId); if (artifactById.isRight()) { return Either.right(artifactById.right().value()); } @@ -1033,27 +1037,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactInfo); } - private Either findArtifactOnParentComponent(Component parentComponent, String parentId, ArtifactOperationInfo operation, String artifactId) { + private Either findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { Either result = null; ArtifactDefinition foundArtifact = null; if (StringUtils.isNotEmpty(artifactId)) { - if (parentComponent.getUniqueId().equals(parentId)) { - if (parentComponent.getDeploymentArtifacts() != null) { - foundArtifact = parentComponent.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - if (foundArtifact == null && parentComponent.getArtifacts() != null) { - foundArtifact = parentComponent.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - } else { - ComponentInstance instance = findComponentInstance(parentId, parentComponent); - if (instance.getDeploymentArtifacts() != null) { - foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - if (foundArtifact == null && instance.getArtifacts() != null) { - foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - } + foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); } if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { log.debug("Artifact {} already exist", artifactId); @@ -1069,6 +1058,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return result; } + private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { + ArtifactDefinition foundArtifact; + if (parentComponent.getUniqueId().equals(parentId)) { + foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); + } else { + ComponentInstance instance = findComponentInstance(parentId, parentComponent); + foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); + } + return foundArtifact; + } + private Either validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); @@ -1254,11 +1254,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { for (GroupInstance groupInstance : groupInstances) { isUpdated = false; if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) { - groupInstance.getArtifacts().remove(artifactId); + groupInstance.getGroupInstanceArtifacts().remove(artifactId); isUpdated = true; } if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { - groupInstance.getArtifacts().remove(foundArtifact.getArtifactUUID()); + groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); isUpdated = true; } if (isUpdated) { @@ -1278,7 +1278,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (isMandatory) { log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); resetMandatoryArtifactFields(foundArtifact); - result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId); + result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true); } else if (cloneIsNeeded) { log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); @@ -2098,11 +2098,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return deploymentArtifacts; } ComponentInstance ri = getRI.left().value(); - if(ri.getDeploymentArtifacts() != null){ + if (ri.getDeploymentArtifacts() != null) { deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); } - } else if(parentComponent.getDeploymentArtifacts() !=null){ - deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); + } else if (parentComponent.getDeploymentArtifacts() != null) { + deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); } } return deploymentArtifacts; @@ -3145,7 +3145,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } - if ( !found ){ + if (!found) { artifacts = resourceInstance.getArtifacts(); if (artifacts != null) { for (Map.Entry entry : artifacts.entrySet()) { @@ -3154,7 +3154,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { break; } } - } + } } } return found; @@ -3370,7 +3370,37 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) { String payload = generateHeatEnvPayload(artifactDefinition); - return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + Either generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId); + if (generateResult.isLeft()) { + ArtifactDefinition updatedArtDef = generateResult.left().value(); + if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) { + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + Optional findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance relevantInst = findFirst.get(); + List updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances()); + + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + updatedGroupInstances.forEach(gi -> { + gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId()); + gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID()); + }); + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName()); + return Either.right(responseFormat); + } + } + } + } + } + } + + return generateResult; } private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { @@ -3438,7 +3468,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - // DE265919 fix Tal G + // DE265919 fix String result = sb.toString().replaceAll("\\\\n", "\n"); return result; @@ -3522,7 +3552,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { oldCheckSum = artifactDefinition.getArtifactChecksum(); artifactDefinition.setArtifactChecksum(newCheckSum); - artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); +// artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); artifactDefinition.setEsId(artifactDefinition.getUniqueId()); updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); @@ -3530,6 +3560,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { + artifactDefinition = updateArifactDefinitionStatus.left().value(); artifactData.setId(artifactDefinition.getUniqueId()); CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); @@ -3965,7 +3996,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4026,7 +4057,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4089,7 +4120,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4158,7 +4189,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4223,7 +4254,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4288,7 +4319,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index 84cf20dcfa..4fd4610ef9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -28,8 +28,8 @@ import java.util.Optional; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -65,8 +65,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return AttributeDefinition if created successfully Or ResponseFormat */ - public Either createAttribute(String resourceId, AttributeDefinition newAttributeDef, String userId) { - Either result = null; + public Either createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { + Either result = null; Either resp = validateUserExists(userId, "create Attribute", false); if (resp.isRight()) { return Either.right(resp.right().value()); @@ -111,7 +111,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { // add the new attribute to resource on graph // need to get StorageOpaerationStatus and convert to ActionStatus from // componentsUtils - Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); + Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); if (either.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); return result; @@ -126,7 +126,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } - private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { + private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { boolean isExist = false; if (attributes != null) { isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent(); @@ -141,7 +141,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either getAttribute(String resourceId, String attributeId, String userId) { + public Either getAttribute(String resourceId, String attributeId, String userId) { Either resp = validateUserExists(userId, "get Attribute", false); if (resp.isRight()) { @@ -155,13 +155,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } Resource resource = status.left().value(); - List attributes = resource.getAttributes(); + List attributes = resource.getAttributes(); if (attributes == null) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); } else { - Either result; + Either result; // verify attribute exist in resource - Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); + Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); if (optionalAtt.isPresent()) { result = Either.left(optionalAtt.get()); @@ -182,8 +182,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef, String userId) { - Either result = null; + public Either updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { + Either result = null; StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { @@ -205,7 +205,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // verify attribute exist in resource - Either eitherAttribute = getAttribute(resourceId, attributeId, userId); + Either eitherAttribute = getAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { return Either.right(eitherAttribute.right().value()); } @@ -228,7 +228,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } - Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); + Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); if (eitherAttUpdate.isRight()) { log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); @@ -253,9 +253,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either deleteAttribute(String resourceId, String attributeId, String userId) { + public Either deleteAttribute(String resourceId, String attributeId, String userId) { - Either result = null; + Either result = null; Either resp = validateUserExists(userId, "delete Attribute", false); if (resp.isRight()) { @@ -283,7 +283,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // verify attribute exist in resource - Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); + Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); if (eitherAttributeExist.isRight()) { return Either.right(eitherAttributeExist.right().value()); } 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 f880883438..5ee5c88f69 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 @@ -21,38 +21,31 @@ package org.openecomp.sdc.be.components.impl; import java.util.ArrayList; -import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.function.Function; -import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; -import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; -import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; 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.ComponentInstanceInput; @@ -64,13 +57,10 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -87,9 +77,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.datastax.driver.core.UserType.Field; -import com.wordnik.swagger.models.auth.In; - import fj.data.Either; public abstract class ComponentBusinessLogic extends BaseBusinessLogic { @@ -283,40 +270,43 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } - public Either validateConformanceLevel(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + public Either validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { log.trace("validate conformance level"); if (componentTypeEnum != ComponentTypeEnum.SERVICE) { - log.error("conformance level validation for non service component, id {}", componentId); + log.error("conformance level validation for non service component, id {}", componentUuid); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); return Either.right(errorResponse); } Either resp = validateUserExists(userId, "validateConformanceLevel", false); if (resp.isRight()) { - log.error("can't validate conformance level, user is not validated, id {}, userId {}", componentId, userId); + log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId); return Either.right(resp.right().value()); } - ComponentParametersView filter = new ComponentParametersView(true); - Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); + Either eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); if (eitherComponent.isRight()) { - log.error("can't validate conformance level, component not found, id {}", componentId); - BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentId); - return Either.right(eitherComponent.right().value()); + log.error("can't validate conformance level, component not found, uuid {}", componentUuid); + BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid); + + StorageOperationStatus status = eitherComponent.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); + return Either.right(responseFormat); } - Component component = eitherComponent.left().value(); - if (component.getConformanceLevel() == null || "".equals(component.getConformanceLevel())) { - log.error("component conformance level property is null or empty, id {}", componentId); + String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel(); + if (StringUtils.isBlank(componentConformanceLevel)) { + log.error("component conformance level property is null or empty, uuid {}", componentUuid); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); return Either.right(errorResponse); } String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); Boolean result = true; - if (CommonBeUtils.conformanceLevelCompare(component.getConformanceLevel(), configConformanceLevel) < 0) { - log.error("invalid asset conformance level, id {}, asset conformanceLevel {}, config conformanceLevel {}", componentId, component.getConformanceLevel(), configConformanceLevel); + if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) { + log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel); result = false; } log.trace("conformance level validation finished"); @@ -1154,9 +1144,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.right(fetchAndSetLatestGeneric.right().value()); Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ - List genericTypeProps = genericTypeResource.getProperties(); - List genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericTypeResource.getUniqueId()); - shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeInputs); + shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); if(!shouldUpgrade) { reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); } @@ -1169,12 +1157,37 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); } + private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { + Map currentMap = ToscaDataDefinition.listToMapByName(currentList); + Map upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); + return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); + } - private boolean upgradeToLatestGeneric(Component componentToCheckOut, List upgradedList) { - - if (!componentToCheckOut.shouldGenerateInputs()) - return true; + private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ + List genericTypeProps = latestGeneric.getProperties(); + Either, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); + if (validMerge.isRight()) { + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + List genericTypeAttributes = latestGeneric.getAttributes(); + validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); + if (validMerge.isRight()) { + log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + return true; + } + + private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) { + + if (!componentToCheckOut.shouldGenerateInputs()) { + //node type - validate properties and attributes + return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); + } + List genericTypeProps = latestGeneric.getProperties(); + List genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); List currentList = new ArrayList<>(); // nullify existing ownerId from existing list and merge into updated list if (null != componentToCheckOut.getInputs()) { @@ -1184,20 +1197,20 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { currentList.add(copy); } } - if (null == upgradedList) { + if (null == genericTypeInputs) { componentToCheckOut.setInputs(currentList); return true; } - Map currentMap = PropertyDataDefinition.listToMapByName(currentList); - Map upgradedMap = PropertyDataDefinition.listToMapByName(upgradedList); - Either, String> eitherMerged = PropertyDataDefinition.mergeProperties(upgradedMap, currentMap, true); + + Either, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList); if (eitherMerged.isRight()) { - log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); + log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); return false; } componentToCheckOut.setInputs(new ArrayList(eitherMerged.left().value().values())); return true; } + private List getFilteredInstances(Component component, List resourceTypes) { List filteredInstances = null; 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 1623375926..203a63894b 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 @@ -51,7 +51,6 @@ import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; 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.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; @@ -338,6 +337,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { String type = artifact.getArtifactType(); + + if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){ + finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); + } if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { continue; @@ -351,9 +354,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); - //put heat - finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); - //put env finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); @@ -890,12 +890,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private Either updateAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) { - Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); - Either result; + private Either updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { + Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); + Either result; if (eitherAttribute.isLeft()) { log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid()); - ComponentInstanceAttribute instanceAttribute = eitherAttribute.left().value(); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); result = Either.left(instanceAttribute); @@ -910,9 +910,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return result; } - private Either createAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) { + private Either createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - Either result; + Either result; Wrapper indexCounterWrapper = new Wrapper<>(); Wrapper errorWrapper = new Wrapper<>(); @@ -921,10 +921,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (!errorWrapper.isEmpty()) { result = Either.right(errorWrapper.getInnerElement()); } else { - Either eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); + Either eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); if (eitherAttribute.isLeft()) { log.debug("Attribute value was added to resource instance {}", resourceInstanceId); - ComponentInstanceAttribute instanceAttribute = eitherAttribute.left().value(); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); result = Either.left(instanceAttribute); } else { @@ -948,8 +948,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceAttribute attribute, String userId) { - Either result = null; + public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { + Either result = null; Wrapper errorWrapper = new Wrapper<>(); validateUserExist(userId, "create Or Update Attribute Value", errorWrapper); @@ -1104,8 +1104,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); } - - try { List instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId); @@ -1122,6 +1120,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } + List path = new ArrayList<>(); + path.add(foundResourceInstance.getUniqueId()); + property.setPath(path); + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); @@ -1603,7 +1605,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - List groupInstances = currentResourceInstance.getGroupInstances(); + // List groupInstances = currentResourceInstance.getGroupInstances(); Map deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts(); resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); if (resultOp.isRight()) { @@ -1639,13 +1641,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - if (CollectionUtils.isNotEmpty(groupInstances)) { + /* if (CollectionUtils.isNotEmpty(groupInstances)) { StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances); if (addGroupsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return resultOp; } + + } if (MapUtils.isNotEmpty(deploymentArtifacts)) { StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts); @@ -1654,7 +1658,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return resultOp; } - } + }*/ ComponentParametersView filter = new ComponentParametersView(true); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java index ae6237897a..3d280ab7ca 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java @@ -289,7 +289,7 @@ public class CsarValidationUtils { return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); } byte[] toscaMetaBytes = csar.get(TOSCA_METADATA_FILE); - // Tal && exchanged for || + // && exchanged for || if (toscaMetaBytes == null || toscaMetaBytes.length == 0) { log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); 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 958adc0eef..d8746737d3 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 @@ -990,9 +990,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } Map> resMap = new HashMap<>(); - Either, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE); + Either, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE, true); if (resResources.isLeft()) { - Either, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE); + Either, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE, true); if (resServices.isLeft()) { // Either, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false); // if (resProducts.isLeft()) { @@ -1021,7 +1021,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } if (filters == null || filters.isEmpty()) { - Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum); + Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, false); if(componentsList.isRight()) { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().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 ba08f11928..f298b0f203 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 @@ -79,6 +79,7 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -112,7 +113,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { @javax.annotation.Resource private GroupTypeOperation groupTypeOperation; - @Autowired ArtifactsOperations artifactsOperation; @@ -121,7 +121,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { @Autowired private ApplicationDataTypeCache dataTypeCache; - /** * * 1. validate user exist @@ -145,67 +144,39 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - - Either result = null; - - try { - Either validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction); - - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - User user = validateUserExists.left().value(); - // 5. check service/resource existence - // 6. check service/resource check out - // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; - - // String realComponentId = componentType == - // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - String realComponentId = componentId; - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - }*/ + /* + * public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { + * + * Either result = null; + * + * try { Either validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction); + * + * if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } + * + * User user = validateUserExists.left().value(); // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state org.openecomp.sdc.be.model.Component component = null; + * + * // String realComponentId = componentType == // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; String realComponentId = componentId; + * + * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); + * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); + * + * Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + * + * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); Either canWork = validateCanWorkOnComponent(component, + * userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } + * + * result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } } + */ private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { String componentTypeForResponse = "SERVICE"; @@ -235,7 +206,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } List currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - log.debug("The deployment artifacts of component {} are {}" , component.getNormalizedName(), deploymentArtifacts); + log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); if (false == currentArtifacts.containsAll(artifacts)) { BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -285,48 +256,48 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } -// ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); -// if (componentOperation instanceof ResourceOperation) { -// ResourceOperation resourceOperation = (ResourceOperation) componentOperation; -// -// for (Entry groupMember : groupMembers.entrySet()) { -// -// String componentInstName = groupMember.getKey(); -// String componentInstUid = groupMember.getValue(); -// -// ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); -// String componentUid = componentInstance.getComponentUid(); -// List componentToscaNames = new ArrayList<>(); -// TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); -// if (status != TitanOperationStatus.OK) { -// BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); -// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); -// } -// -// log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); -// -// boolean found = false; -// for (String memberToscaType : memberToscaTypes) { -// if (componentToscaNames.contains(memberToscaType)) { -// found = true; -// break; -// } -// } -// if (found == false) { -// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, -// "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); -// /* -// * # %1 - member name # %2 - group name # %3 - group type -// */ -// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); -// } else { -// log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); -// } -// } -// } else { -// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); -// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); -// } + // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); + // if (componentOperation instanceof ResourceOperation) { + // ResourceOperation resourceOperation = (ResourceOperation) componentOperation; + // + // for (Entry groupMember : groupMembers.entrySet()) { + // + // String componentInstName = groupMember.getKey(); + // String componentInstUid = groupMember.getValue(); + // + // ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); + // String componentUid = componentInstance.getComponentUid(); + // List componentToscaNames = new ArrayList<>(); + // TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); + // if (status != TitanOperationStatus.OK) { + // BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + // } + // + // log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); + // + // boolean found = false; + // for (String memberToscaType : memberToscaTypes) { + // if (componentToscaNames.contains(memberToscaType)) { + // found = true; + // break; + // } + // } + // if (found == false) { + // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, + // "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); + // /* + // * # %1 - member name # %2 - group name # %3 - group type + // */ + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); + // } else { + // log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); + // } + // } + // } else { + // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + // } } @@ -340,21 +311,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { - Either result = null; - List groupIdsToUpdateVersion = new ArrayList<>(); - groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); - Either, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); - if (updateGroupVersion.isLeft()) { - result = Either.left(updateGroupVersion.left().value().get(0)); - } else { - log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); - result = Either.right(updateGroupVersion.right().value()); - } - return result; - }*/ - - + /* + * public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either result = null; List groupIdsToUpdateVersion = new + * ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); Either, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); if (updateGroupVersion.isLeft()) + * { result = Either.left(updateGroupVersion.left().value().get(0)); } else { log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); result = Either.right(updateGroupVersion.right().value()); } return + * result; } + */ /** * Update list of groups versions @@ -363,52 +325,44 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { - - result = groupOperation.updateGroupVersion(groupsUniqueId, true); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } + /* + * public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { + * + * Either, StorageOperationStatus> result = null; + * + * try { + * + * result = groupOperation.updateGroupVersion(groupsUniqueId, true); + * + * return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } + * + * } + */ - }*/ + /** + * Update GroupDefinition metadata + * + * @param componentId + * @param user + * @param componentType + * @param updatedGroup + * @param inTransaction + * @return + */ + public Either validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction) { -/** - * Update GroupDefinition metadata - * @param componentId - * @param user - * @param componentType - * @param updatedGroup - * @param inTransaction - * @return - */ - public Either validateAndUpdateGroupMetadata( - String componentId, - User user, - ComponentTypeEnum componentType, - GroupDefinition updatedGroup, - boolean inTransaction) { - Either result = null; - try{ + try { // Validate user exist Either validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); if (validateUserExists.isRight()) { @@ -429,14 +383,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } List currentGroups = component.getGroups(); - if(CollectionUtils.isEmpty(currentGroups)){ + if (CollectionUtils.isEmpty(currentGroups)) { log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); return result; } // Validate groups exists in the component Optional currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); - if(!currentGroupOpt.isPresent()){ + if (!currentGroupOpt.isPresent()) { log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); return result; @@ -451,14 +405,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType()); - result = Either.right(responseFormat); + result = Either.right(responseFormat); return result; } result = updateGroupMetadata(component, currentGroup, updatedGroup); return result; - + } finally { - if(result.isLeft()){ + if (result.isLeft()) { titanDao.commit(); } else { titanDao.rollback(); @@ -466,15 +420,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } } - + private Either updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { String currentGroupName = currentGroup.getName(); Either result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); - - if(result.isRight()){ + + if (result.isRight()) { log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); } - if(result.isLeft()){ + if (result.isLeft()) { result = updateGroup(component, currentGroup, currentGroupName); } return result; @@ -483,25 +437,25 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private Either updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { Either handleGroupRes; Either result = null; - if(updatedGroup.getName().equals(currentGroupName)){ + if (updatedGroup.getName().equals(currentGroupName)) { handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); - if(handleGroupRes.isRight()){ + if (handleGroupRes.isRight()) { log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); } } else { StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); - if(deleteStatus != StorageOperationStatus.OK){ + if (deleteStatus != StorageOperationStatus.OK) { log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); } handleGroupRes = groupsOperation.addGroup(component, updatedGroup); - if(handleGroupRes.isRight()){ + if (handleGroupRes.isRight()) { log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); } } - if(result == null){ + if (result == null) { result = Either.left(updatedGroup); } return result; @@ -509,6 +463,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { /** * Validate and Update Group Property + * * @param componentId * @param groupUniqueId * @param user @@ -517,43 +472,36 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, ResponseFormat> validateAndUpdateGroupProperties( - String componentId, - String groupUniqueId, - User user, - ComponentTypeEnum componentType, - List groupPropertiesToUpdate, boolean inTransaction) { - + public Either, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List groupPropertiesToUpdate, boolean inTransaction) { + Either, ResponseFormat> result = Either.left(groupPropertiesToUpdate); - try{ + try { Optional optionalGroupConnectedToVf = null; GroupDefinition currentGroup = null; StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); - if( lockResult != StorageOperationStatus.OK ){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - lockResult, componentType), componentId)); + if (lockResult != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId)); } - if( result.isLeft() ){ - //VF exist because lock succedded + if (result.isLeft()) { + // VF exist because lock succedded Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); - optionalGroupConnectedToVf = - //All groups on resource + optionalGroupConnectedToVf = + // All groups on resource vf.getGroups().stream(). - //Filter in group sent is part of VF groups - filter( e -> e.getUniqueId().equals(groupUniqueId)). - //Collect - findAny(); - if( !optionalGroupConnectedToVf.isPresent() ){ - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, - groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); + // Filter in group sent is part of VF groups + filter(e -> e.getUniqueId().equals(groupUniqueId)). + // Collect + findAny(); + if (!optionalGroupConnectedToVf.isPresent()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); } } - - if( result.isLeft() ){ + + if (result.isLeft()) { currentGroup = optionalGroupConnectedToVf.get(); result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); } - if( result.isLeft() ){ + if (result.isLeft()) { result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); if (result.isRight()) { BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); @@ -561,49 +509,47 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - } - catch(Exception e){ + } catch (Exception e) { log.debug("Error in validateAndUpdateGroupProperty {}", e); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - finally{ + } finally { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } return result; } + private void resetEmptyValueWithDefaults(List groupPropertiesToUpdate, GroupDefinition originalGroup) { Map originalProperties = - //Stream of original properties from group + // Stream of original properties from group originalGroup.convertToGroupProperties().stream(). - //Collecting to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - for( GroupProperty gp : groupPropertiesToUpdate){ - if( StringUtils.isEmpty(gp.getValue())){ + // Collecting to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + for (GroupProperty gp : groupPropertiesToUpdate) { + if (StringUtils.isEmpty(gp.getValue())) { gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); } } - + } - private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue( - GroupDefinition originalGroup, List groupPropertiesToUpdate) { - + private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List groupPropertiesToUpdate) { + Either, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); if (ret.isLeft()) { resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); } if (ret.isLeft()) { // Validate Type Match Value - Optional optionalError = - //Stream of group properties + Optional optionalError = + // Stream of group properties groupPropertiesToUpdate.stream(). - //Validate each and map to returned Strorage status value - map( e -> groupOperation .validateAndUpdatePropertyValue(e)). - //Keep only failed result if there is such - filter( e -> e != StorageOperationStatus.OK). - //collect - findFirst(); - if( optionalError.isPresent()){ + // Validate each and map to returned Strorage status value + map(e -> groupOperation.validateAndUpdatePropertyValue(e)). + // Keep only failed result if there is such + filter(e -> e != StorageOperationStatus.OK). + // collect + findFirst(); + if (optionalError.isPresent()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); } @@ -612,60 +558,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (ret.isLeft()) { // Validate min max ect... ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); - } + } return ret; } - private Either, ResponseFormat> validatePropertyBusinessLogic( - List groupPropertiesToUpdate, GroupDefinition originalGroup) { + + private Either, ResponseFormat> validatePropertyBusinessLogic(List groupPropertiesToUpdate, GroupDefinition originalGroup) { Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - + Map nameValueMap = new HashMap<>(); - for(GroupProperty gp : groupPropertiesToUpdate){ - //Filter out non special properties which does not have Enum + for (GroupProperty gp : groupPropertiesToUpdate) { + // Filter out non special properties which does not have Enum final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); - if( gpEnum != null ){ + if (gpEnum != null) { nameValueMap.put(gpEnum, gp.getValue()); } } - - if ( !MapUtils.isEmpty(nameValueMap) ) { - if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) - || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { - - + if (!MapUtils.isEmpty(nameValueMap)) { + + if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { + Map oldValueMap = prepareMapWithOriginalProperties(originalGroup); - - Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, - oldValueMap); + + Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap); if (eitherValid.isRight()) { ret = Either.right(eitherValid.right().value()); } } - if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) - || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { + if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { - Optional optionalError = - //Stream of group Properties + Optional optionalError = + // Stream of group Properties groupPropertiesToUpdate.stream(). - //Filter in only properties that needs text validation - filter(e -> enumHasValueFilter(e.getName(), - enumName -> PropertyNames.findName(enumName), - PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). - //validate text properties - map( e -> validateFreeText(e)). - //filter in only errors if exist - filter( e -> e.isRight()). - //map the Either value to the Error - map( e -> e.right().value()) - //collect - .findFirst(); - if( optionalError.isPresent() ){ + // Filter in only properties that needs text validation + filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). + // validate text properties + map(e -> validateFreeText(e)). + // filter in only errors if exist + filter(e -> e.isRight()). + // map the Either value to the Error + map(e -> e.right().value()) + // collect + .findFirst(); + if (optionalError.isPresent()) { ret = Either.right(optionalError.get()); } - + } } @@ -674,83 +614,77 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private Map prepareMapWithOriginalProperties(GroupDefinition originalGroup) { Map oldValueMap = new HashMap<>(); - PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, - PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; - - for(GroupProperty gp : originalGroup.convertToGroupProperties()){ - if( enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)){ + PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; + + for (GroupProperty gp : originalGroup.convertToGroupProperties()) { + if (enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)) { oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); } } - if( StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES)) ){ + if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) { oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); } return oldValueMap; } - - private Either, ResponseFormat> validateOnlyValueChanged( - List groupPropertiesToUpdate, GroupDefinition originalGroup) { - + + private Either, ResponseFormat> validateOnlyValueChanged(List groupPropertiesToUpdate, GroupDefinition originalGroup) { + Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - if( CollectionUtils.isEmpty(groupPropertiesToUpdate) ){ + if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); - } - else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); + } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); } else { - Map namePropertyMap = - //Original Group Properties Stream + Map namePropertyMap = + // Original Group Properties Stream originalGroup.convertToGroupProperties().stream(). - //Collect to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - - Optional optionalMissingProperty = - //Group Properties to be updated Stream + // Collect to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + + Optional optionalMissingProperty = + // Group Properties to be updated Stream groupPropertiesToUpdate.stream(). - //Filter in property that is not contained in original if there is such - filter(e -> !namePropertyMap.containsKey(e.getName())). - //collect - findFirst(); - + // Filter in property that is not contained in original if there is such + filter(e -> !namePropertyMap.containsKey(e.getName())). + // collect + findFirst(); + if (optionalMissingProperty.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - optionalMissingProperty.get().getName())); - } - else{ - Optional optionalNonValueChange = - //groups to be updated stream + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName())); + } else { + Optional optionalNonValueChange = + // groups to be updated stream groupPropertiesToUpdate.stream(). - //filter in only properties with non-value (illegal) change - filter( e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). - //Collect - findFirst(); + // filter in only properties with non-value (illegal) change + filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). + // Collect + findFirst(); if (optionalNonValueChange.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, - optionalNonValueChange.get().getName())); + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName())); } } - + } return ret; } /** * if groupProperty are the same or if only value is different returns true, otherwise returns false. + * * @param groupProperty * @param groupProperty2 * @return */ private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { - //Create 2 duplicates for groupPropery and reset their values + // Create 2 duplicates for groupPropery and reset their values Gson gson = new GsonBuilder().setPrettyPrinting().create(); try { GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); groupPropertyDuplicate.setValue(null); groupPropertyDuplicate.setSchema(null); groupPropertyDuplicate.setParentUniqueId(null); -// GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); + // GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); groupProperty2Duplicate.setValue(null); groupProperty2Duplicate.setSchema(null); @@ -759,8 +693,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } catch (Exception e) { log.debug("Failed validate group properties. ", e); return false; - } + } } + /** * Validate and update GroupDefinition metadata * @@ -864,183 +799,105 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Component component = null; - try { - - if (groups == null || groups.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); - } - - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; - } - - component = validateGroupsBeforeUpdate.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "Group - Associate Artifacts"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedGroups = new ArrayList<>(); - - List componentGroups = component.getGroups(); - - // per group, associate to it the artifacts - for (GroupDefinition groupDefinition : groups) { - - GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); - if (componentGroup != null) { - List componentArtifacts = componentGroup.getArtifacts(); - int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); - if (artifactsSizeInGroup > 0) { - List artifactsToAssociate = groupDefinition.getArtifacts(); - - // if no artifcats sent - if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { - continue; - } - - boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); - if (isChanged) {// I.e. At least one artifact is already - // associated to the group - log.debug("Some of the artifacts already associated to group {}" , groupDefinition.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); - } - } - } - - Either associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - - if (associateArtifactsToGroup.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); - return result; - } - updatedGroups.add(associateArtifactsToGroup.left().value()); - - } - - result = Either.left(updatedGroups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - }*/ - - /*public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Component component = null; - try { - - if (groups == null || groups.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); - } - - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; - } - - component = validateGroupsBeforeUpdate.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "Group - Associate Members"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedGroups = new ArrayList<>(); - - // per group, associate to it the members - for (GroupDefinition groupDefinition : groups) { - - Either associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true); - - if (associateMembersToGroup.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); - return result; - } else { - updatedGroups.add(associateMembersToGroup.left().value()); - } - - } - - result = Either.left(updatedGroups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } + /* + * public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock + * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Component component = null; try { + * + * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } + * + * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = + * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } + * + * component = validateGroupsBeforeUpdate.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * List updatedGroups = new ArrayList<>(); + * + * List componentGroups = component.getGroups(); + * + * // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { + * + * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List componentArtifacts = + * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); if (artifactsSizeInGroup > 0) { List artifactsToAssociate = groupDefinition.getArtifacts(); + * + * // if no artifcats sent if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { continue; } + * + * boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); if (isChanged) {// I.e. At least one artifact is already // associated to the group log.debug("Some of the artifacts already associated to group {}" , + * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); } } } + * + * Either associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); + * + * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); + * + * } + * + * result = Either.left(updatedGroups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } } + */ - } - }*/ + /* + * public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock + * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Component component = null; try { + * + * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } + * + * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = + * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } + * + * component = validateGroupsBeforeUpdate.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * List updatedGroups = new ArrayList<>(); + * + * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) { + * + * Either associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true); + * + * if (associateMembersToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } else { updatedGroups.add(associateMembersToGroup.left().value()); } + * + * } + * + * result = Either.left(updatedGroups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } } + */ /** * associate artifacts to a given group @@ -1084,17 +941,16 @@ public class GroupBusinessLogic extends BaseBusinessLogic { component = validateComponent.left().value(); Either groupEither = findGroupOnComponent(component, groupId); - + if (groupEither.isRight()) { log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); return result; - } + } GroupDefinition group = groupEither.left().value(); - - + Boolean isBase = null;// Constants.IS_BASE; List props = group.convertToGroupProperties(); if (props != null && !props.isEmpty()) { @@ -1114,14 +970,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { List artifacts = new ArrayList<>(); List artifactsFromComponent = new ArrayList<>(); List artifactsIds = group.getArtifacts(); - + Map deploymentArtifacts = null; - if(MapUtils.isNotEmpty(component.getDeploymentArtifacts())){ + if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); } - + if (artifactsIds != null && !artifactsIds.isEmpty()) { - for(String id: artifactsIds){ + for (String id : artifactsIds) { if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); @@ -1166,15 +1022,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private Either findGroupOnComponent(Component component, String groupId) { - + Either result = null; - if(CollectionUtils.isNotEmpty(component.getGroups())){ + if (CollectionUtils.isNotEmpty(component.getGroups())) { Optional foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); - if(foundGroup.isPresent()){ - result = Either.left(foundGroup.get()); + if (foundGroup.isPresent()) { + result = Either.left(foundGroup.get()); } } - if(result == null){ + if (result == null) { result = Either.right(StorageOperationStatus.NOT_FOUND); } return result; @@ -1260,399 +1116,231 @@ public class GroupBusinessLogic extends BaseBusinessLogic { List currentGroups = component.getGroups(); boolean found = false; - List updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList()); - - List missingGroupNames = updatedGroupsName; - - if (currentGroups != null && false == currentGroups.isEmpty()) { - List currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList()); - - if (currentGroupsName.containsAll(updatedGroupsName)) { - found = true; - } else { - currentGroupsName.removeAll(currentGroupsName); - missingGroupNames = currentGroupsName; - } - } - if (false == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - String listOfGroups = getAsString(missingGroupNames); - result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse); - return result; - } - - return null; - } - - public String getAsString(List list) { - - if (list == null || list.isEmpty()) { - return ""; - } - StringBuilder builder = new StringBuilder(); - list.forEach(p -> builder.append(p + ",")); - - String result = builder.toString(); - return result.substring(0, result.length()); - - } - - /** - * dissociate artifacts from a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - /*public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Component component = null; - - try { - - if (groups == null || groups.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); - } - - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; - } - - component = validateGroupsBeforeUpdate.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedGroups = new ArrayList<>(); - - List componentGroups = component.getGroups(); - // per group, associate to it the artifacts - for (GroupDefinition groupDefinition : groups) { - - GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); - if (componentGroup != null) { - List componentArtifacts = componentGroup.getArtifacts(); - int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); - List artifactsToDissociate = groupDefinition.getArtifacts(); - - // if no artifcats sent - if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { - continue; - } - - if (artifactsSizeInGroup > 0) { - - boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); - if (false == containsAll) { // At least one artifact is - // not associated to the - // group - log.debug("Some of the artifacts already dissociated to group {}" , groupDefinition.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); - } - } else { - if (artifactsSizeInGroup == 0) { - if (artifactsToDissociate != null && false == artifactsToDissociate.isEmpty()) { - log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); - } - } - } - } - - Either associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - - if (associateArtifactsToGroup.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); - return result; - } - updatedGroups.add(associateArtifactsToGroup.left().value()); - - } - - result = Either.left(updatedGroups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - }*/ - - /*public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - List groups = new ArrayList<>(); - org.openecomp.sdc.be.model.Component component = null; - try { - - if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - - if (shouldLockComp && inTransaction) { - BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Either validateUserExists = validateUserExists(userId, CREATE_GROUP, true); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - User user = validateUserExists.left().value(); - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "CreateGroups"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - for (GroupDefinition groupDefinition : groupDefinitions) { - Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); - if (createGroup.isRight()) { - log.debug("Failed to create group {}." , groupDefinition ); - result = Either.right(createGroup.right().value()); - return result; - } - GroupDefinition createdGroup = createGroup.left().value(); - groups.add(createdGroup); - } - } - - result = Either.left(groups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - } - - public Either createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - - Either result = null; - - log.trace("Going to create group {}" , groupDefinition); - - try { - - // 3. verify group not already exist - List groups = component.getGroups(); - boolean found = false; - if (groups != null && false == groups.isEmpty()) { - - GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - - found = existGroupDef != null; - } - - if (true == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse)); - return result; - } - - // 4. verify type of group exist - String groupType = groupDefinition.getType(); - if (groupType == null || groupType.isEmpty()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName())); - return result; - } - Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); - if (getGroupType.isRight()) { - StorageOperationStatus status = getGroupType.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); - return result; - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - } - - // 6. verify the component instances type are allowed according to - // the member types in the group type - GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); - - Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); - - if (areValidMembers.isRight()) { - ResponseFormat responseFormat = areValidMembers.right().value(); - result = Either.right(responseFormat); - return result; - } - - // 7. verify the artifacts belongs to the component - Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); - if (areValidArtifacts.isRight()) { - ResponseFormat responseFormat = areValidArtifacts.right().value(); - result = Either.right(responseFormat); - return result; - } - - NodeTypeEnum nodeTypeEnum = componentType.getNodeType(); - - // add invariantUUID - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - groupDefinition.setInvariantUUID(invariantUUID); - - // add groupUUID - String groupUUID = UniqueIdBuilder.generateUUID(); - groupDefinition.setGroupUUID(groupUUID); - - // add version - groupDefinition.setVersion(INITIAL_VERSION); + List updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList()); - // set groupType uid - groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + List missingGroupNames = updatedGroupsName; - Either addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true); + if (currentGroups != null && false == currentGroups.isEmpty()) { + List currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList()); - if (addGroupToGraph.isRight()) { - StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); + if (currentGroupsName.containsAll(updatedGroupsName)) { + found = true; } else { - GroupDefinition groupDefinitionCreated = addGroupToGraph.left().value(); - result = Either.left(groupDefinitionCreated); + currentGroupsName.removeAll(currentGroupsName); + missingGroupNames = currentGroupsName; } - + } + if (false == found) { + String componentTypeForResponse = getComponentTypeForResponse(component); + String listOfGroups = getAsString(missingGroupNames); + result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse); return result; + } - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } + return null; + } - } + public String getAsString(List list) { + if (list == null || list.isEmpty()) { + return ""; } + StringBuilder builder = new StringBuilder(); + list.forEach(p -> builder.append(p + ",")); + + String result = builder.toString(); + return result.substring(0, result.length()); } - public Either, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List groups, boolean inTransaction) { - List updatedGroups = new ArrayList<>(); - Either, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); - Either updateGroupNameRes; - Either validateGenerateGroupNameRes; - int counter; - for (GroupDefinition group : groups) { - if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { - continue; - } - counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); - validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); - if (validateGenerateGroupNameRes.isRight()) { - updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); - break; - } - updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); - if (updateGroupNameRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); - updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); - break; - } - updatedGroups.add(updateGroupNameRes.left().value()); - } - return updateGroupNamesRes; - }*/ + /** + * dissociate artifacts from a given group + * + * @param componentId + * @param userId + * @param componentType + * @param groups + * @param shouldLockComp + * @param inTransaction + * @return + */ + /* + * public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock + * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Component component = null; + * + * try { + * + * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } + * + * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = + * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } + * + * component = validateGroupsBeforeUpdate.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * List updatedGroups = new ArrayList<>(); + * + * List componentGroups = component.getGroups(); // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { + * + * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List componentArtifacts = + * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); List artifactsToDissociate = groupDefinition.getArtifacts(); + * + * // if no artifcats sent if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { continue; } + * + * if (artifactsSizeInGroup > 0) { + * + * boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); if (false == containsAll) { // At least one artifact is // not associated to the // group log.debug("Some of the artifacts already dissociated to group {}" , + * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } else { if (artifactsSizeInGroup == 0) { if (artifactsToDissociate != null && + * false == artifactsToDissociate.isEmpty()) { log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, + * componentGroup.getName())); } } } } + * + * Either associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); + * + * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); + * + * } + * + * result = Either.left(updatedGroups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } + * + * } + */ + + /* + * public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * List groups = new ArrayList<>(); org.openecomp.sdc.be.model.Component component = null; try { + * + * if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + * + * if (shouldLockComp && inTransaction) { BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of + * another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Either validateUserExists = validateUserExists(userId, CREATE_GROUP, true); if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } + * + * User user = validateUserExists.left().value(); + * + * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); + * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); + * + * Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + * + * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * Either canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } + * + * for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); if (createGroup.isRight()) { + * log.debug("Failed to create group {}." , groupDefinition ); result = Either.right(createGroup.right().value()); return result; } GroupDefinition createdGroup = createGroup.left().value(); groups.add(createdGroup); } } + * + * result = Either.left(groups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } + * + * } + * + * public Either createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { + * + * Either result = null; + * + * log.trace("Going to create group {}" , groupDefinition); + * + * try { + * + * // 3. verify group not already exist List groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) { + * + * GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); + * + * found = existGroupDef != null; } + * + * if (true == found) { String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), + * componentTypeForResponse)); return result; } + * + * // 4. verify type of group exist String groupType = groupDefinition.getType(); if (groupType == null || groupType.isEmpty()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, + * groupDefinition.getName())); return result; } Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); if (getGroupType.isRight()) { StorageOperationStatus status = + * getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); result = + * Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); return result; } else { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } } + * + * // 6. verify the component instances type are allowed according to // the member types in the group type GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); + * + * Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); + * + * if (areValidMembers.isRight()) { ResponseFormat responseFormat = areValidMembers.right().value(); result = Either.right(responseFormat); return result; } + * + * // 7. verify the artifacts belongs to the component Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); if (areValidArtifacts.isRight()) { + * ResponseFormat responseFormat = areValidArtifacts.right().value(); result = Either.right(responseFormat); return result; } + * + * NodeTypeEnum nodeTypeEnum = componentType.getNodeType(); + * + * // add invariantUUID String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); groupDefinition.setInvariantUUID(invariantUUID); + * + * // add groupUUID String groupUUID = UniqueIdBuilder.generateUUID(); groupDefinition.setGroupUUID(groupUUID); + * + * // add version groupDefinition.setVersion(INITIAL_VERSION); + * + * // set groupType uid groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + * + * Either addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true); + * + * if (addGroupToGraph.isRight()) { StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); result = + * Either.right(componentsUtils.getResponseFormat(actionStatus)); log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); } else { GroupDefinition + * groupDefinitionCreated = addGroupToGraph.left().value(); result = Either.left(groupDefinitionCreated); } + * + * return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } + * + * } + * + * public Either, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List groups, boolean inTransaction) { List updatedGroups = new ArrayList<>(); + * Either, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); Either updateGroupNameRes; Either validateGenerateGroupNameRes; int counter; for + * (GroupDefinition group : groups) { if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { continue; } counter = + * Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); if (validateGenerateGroupNameRes.isRight()) { + * updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); break; } updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); if + * (updateGroupNameRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); break; } + * updatedGroups.add(updateGroupNameRes.left().value()); } return updateGroupNamesRes; } + */ - private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, - GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { + private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { Either, ResponseFormat> result; - Either, StorageOperationStatus> eitherUpdate = groupsOperation - .updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); + Either, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); if (eitherUpdate.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); @@ -1661,7 +1349,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } return result; } - + public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, int startGroupCounter) { Either validateGenerateGroupNamesRes = Either.left(true); Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); @@ -1768,53 +1456,38 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } newGroupName = newGroupNameRes.left().value(); group.setName(newGroupName); - + } updatedGroups.add(group); - + } result = Either.left(updatedGroups); return result; } - /*public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { - - List generatedGroups = new ArrayList<>(); - Either, ResponseFormat> result = Either.left(generatedGroups); - - try { - - if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { - for (GroupDefinition groupDefinition : groupDefinitions) { - Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); - if (createGroup.isRight()) { - result = Either.right(createGroup.right().value()); - return result; - } - GroupDefinition generatedGroup = createGroup.left().value(); - generatedGroups.add(generatedGroup); - } - } - - return result; - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - - }*/ + /* + * public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { + * + * List generatedGroups = new ArrayList<>(); Either, ResponseFormat> result = Either.left(generatedGroups); + * + * try { + * + * if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, + * groupDefinition, true); if (createGroup.isRight()) { result = Either.right(createGroup.right().value()); return result; } GroupDefinition generatedGroup = createGroup.left().value(); generatedGroups.add(generatedGroup); } } + * + * return result; } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } + * + * } + */ public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { Either result = null; @@ -1833,7 +1506,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { try { ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); + componentParametersView.disableAll(); componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreArtifacts(false); @@ -1845,7 +1518,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } component = validateComponent.left().value(); Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); - + if (findComponentInstanceAndGroupInstanceRes.isRight()) { log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); @@ -1855,7 +1528,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft(); - + Boolean isBase = null;// Constants.IS_BASE; List props = group.convertToGroupInstancesProperties(); if (props != null && !props.isEmpty()) { @@ -1871,30 +1544,33 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - + List artifacts = new ArrayList<>(); - List artifactsFromComponent = new ArrayList<>(); List artifactsIds = group.getArtifacts(); if (artifactsIds != null && !artifactsIds.isEmpty()) { - - for(String id: artifactsIds){ - Either artifactEither = artifactsOperation.getArtifactById(componentInstance.getComponentUid(), id); - if (artifactEither.isRight()) { - log.debug("Failed to get artifact {} . Status is {} ", id, artifactEither.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactEither.right().value())); - result = Either.right(responseFormat); - return result; - } - artifactsFromComponent.add(artifactEither.left().value()); - } - if (!artifactsFromComponent.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { - ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); - artifacts.add(artifactDefinitionInfo); + + List instances = component.getComponentInstances(); + if (instances != null) { + Optional findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance ci = findFirst.get(); + Map deploymentArtifacts = ci.getDeploymentArtifacts(); + for (String id : artifactsIds) { + Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } + List instArtifactsIds = group.getGroupInstanceArtifacts(); + for (String id : instArtifactsIds) { + Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } } + } - - } GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); resultInfo.setIsBase(isBase); @@ -1905,7 +1581,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; - } finally { if (false == inTransaction) { @@ -1922,250 +1597,230 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - + private Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { - - Either, StorageOperationStatus> result = null; - if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ + + Either, StorageOperationStatus> result = null; + if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { Optional foundGroup; Optional foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); - if(foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())){ + if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) { foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); - if(foundGroup.isPresent()){ + if (foundGroup.isPresent()) { result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); } } } - if(result == null){ + if (result == null) { result = Either.right(StorageOperationStatus.NOT_FOUND); } return result; } - private int getLatestIntProperty(Map newValues, Map parentValues, - PropertyNames propertyKey) { + private int getLatestIntProperty(Map newValues, Map parentValues, PropertyNames propertyKey) { String value; - if( newValues.containsKey(propertyKey) ){ + if (newValues.containsKey(propertyKey)) { value = newValues.get(propertyKey); - } - else{ + } else { value = parentValues.get(propertyKey); } return Integer.valueOf(value); } - private boolean isPropertyChanged(Map newValues, Map parentValues, - final PropertyNames minInstances) { + private boolean isPropertyChanged(Map newValues, Map parentValues, final PropertyNames minInstances) { return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); } - private Either validateMinMaxAndInitialCountPropertyLogicVF( - Map newValues, Map parentValues) { - + private Either validateMinMaxAndInitialCountPropertyLogicVF(Map newValues, Map parentValues) { + int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); Either result = Either.left(true); - + if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) { if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) { - result = Either.right( - componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, - PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), - String.valueOf(latestMaxInstances))); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances))); } } if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) { if (latestMaxInstances < latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, - PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); } } if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) { if (latestMinInstances > latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, - PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); } } return result; } + private Either validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, Map parentValues) { - + Either result; - for(Entry entry : newValues.entrySet()){ + for (Entry entry : newValues.entrySet()) { PropertyNames currPropertyName = entry.getKey(); - if(currPropertyName == PropertyNames.MIN_INSTANCES){ + if (currPropertyName == PropertyNames.MIN_INSTANCES) { String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), - new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if(result.isRight()){ + if (result.isRight()) { return result; } - } - else if(currPropertyName == PropertyNames.INITIAL_COUNT){ + } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), - new ImmutablePair(PropertyNames.MIN_INSTANCES,minValue), + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if(result.isRight()){ + if (result.isRight()) { return result; } - } - else if(currPropertyName == PropertyNames.MAX_INSTANCES){ + } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), - new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if(result.isRight()){ + if (result.isRight()) { return result; } } } - return Either.left(true); + return Either.left(true); } - private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { + private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { Either result; final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); int minInt = parseIntValue(min.getValue(), min.getKey()); int maxInt = parseIntValue(max.getValue(), max.getKey()); - if(newValueInt < 0 || minInt < 0 || maxInt < 0){ + if (newValueInt < 0 || minInt < 0 || maxInt < 0) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); - } - else if (newValueInt < minInt || newValueInt > maxInt) { + } else if (newValueInt < minInt || newValueInt > maxInt) { log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); - result = Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, - newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); - }else{ + result = Either + .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); + } else { result = Either.left(true); } return result; } - - private int parseIntValue(String value, PropertyNames propertyName) { + + private int parseIntValue(String value, PropertyNames propertyName) { int result; - if(propertyName == PropertyNames.MAX_INSTANCES ){ + if (propertyName == PropertyNames.MAX_INSTANCES) { result = convertIfUnboundMax(value); } else if (NumberUtils.isNumber(value)) { result = Integer.parseInt(value); - } else{ + } else { result = -1; } return result; } -/** - * validates received new property values and updates group instance in case of success - * @param oldGroupInstance - * @param groupInstanceId - * @param newProperties - * @param inTransaction - * @return - */ + /** + * validates received new property values and updates group instance in case of success + * + * @param oldGroupInstance + * @param groupInstanceId + * @param newProperties + * @param inTransaction + * @return + */ public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties, boolean inTransaction) { - + Either actionResult = null; Either updateGroupInstanceResult = null; Either, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); - if(validateRes.isRight()){ + if (validateRes.isRight()) { log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); - actionResult = Either.right(validateRes.right().value()); + actionResult = Either.right(validateRes.right().value()); } - if(actionResult == null){ + if (actionResult == null) { List validatedReducedNewProperties = validateRes.left().value(); updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); - if(updateGroupInstanceResult.isRight()){ + if (updateGroupInstanceResult.isRight()) { log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); } } - if(actionResult == null){ + if (actionResult == null) { actionResult = Either.left(updateGroupInstanceResult.left().value()); } return actionResult; } - + private Either, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List newProperties) { - + Either validationRes = null; Either, ResponseFormat> actionResult; - Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(),p->p)); + Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); Map newPropertyValues = new EnumMap<>(PropertyNames.class); List reducedProperties = new ArrayList<>(); String currPropertyName; - try{ - for(GroupInstanceProperty currNewProperty : newProperties){ + try { + for (GroupInstanceProperty currNewProperty : newProperties) { currPropertyName = currNewProperty.getName(); validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); - if(validationRes.isRight()){ + if (validationRes.isRight()) { log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); break; } } - if(validationRes == null || validationRes.isLeft()){ + if (validationRes == null || validationRes.isLeft()) { Map existingPropertyValues = new EnumMap<>(PropertyNames.class); Map parentPropertyValues = new EnumMap<>(PropertyNames.class); fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); } - if(validationRes.isLeft()){ + if (validationRes.isLeft()) { actionResult = Either.left(reducedProperties); } else { actionResult = Either.right(validationRes.right().value()); } - } catch( Exception e){ + } catch (Exception e) { log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } return actionResult; } - private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, - Map propertyValues, Map parentPropertyValues) { + private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, Map propertyValues, Map parentPropertyValues) { PropertyNames[] allPropertyNames = PropertyNames.values(); - for(PropertyNames name : allPropertyNames){ - if(isUpdatable(name)){ + for (PropertyNames name : allPropertyNames) { + if (isUpdatable(name)) { propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); } } } - private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, - GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { + private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { Either validationRes = null; String currPropertyName = currNewProperty.getName(); PropertyNames propertyName = PropertyNames.findName(currPropertyName); - try{ - if(currExistingProperty == null){ + try { + if (currExistingProperty == null) { log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); - } - else if(isUpdatable(propertyName)){ + } else if (isUpdatable(propertyName)) { validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); - if(validationRes.isRight()){ - log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue() , currPropertyName); + if (validationRes.isRight()) { + log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); } else { addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); } - } - else{ + } else { validateImmutableProperty(currExistingProperty, currNewProperty); } - if(validationRes == null){ + if (validationRes == null) { validationRes = Either.left(true); } - } catch( Exception e){ + } catch (Exception e) { log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -2173,76 +1828,73 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private boolean isUpdatable(PropertyNames updatablePropertyName) { - return updatablePropertyName != null && - updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); + return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); } - private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, - GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - - String newValue = newProperty.getValue(); - if(!newValue.equals(String.valueOf(existingProperty.getValue()))){ + private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + String newValue = newProperty.getValue(); + if (!newValue.equals(String.valueOf(existingProperty.getValue()))) { newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); reducedProperties.add(newProperty); } - if(!isEmptyMinInitialCountValue(propertyName, newValue)){ + if (!isEmptyMinInitialCountValue(propertyName, newValue)) { newPropertyValues.put(propertyName, newValue); } } - + private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { boolean result = false; - if((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)){ + if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) { result = true; } return result; } private int convertIfUnboundMax(String value) { - + int result; - if(!NumberUtils.isNumber(value)){ + if (!NumberUtils.isNumber(value)) { result = Integer.MAX_VALUE; - } - else{ + } else { result = Integer.parseInt(value); } return result; } private Either validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - + Either validationRes = null; String parentValue = existingProperty.getParentValue(); - + newProperty.setParentValue(parentValue); - if(StringUtils.isEmpty(newProperty.getValue())){ + if (StringUtils.isEmpty(newProperty.getValue())) { newProperty.setValue(parentValue); } - if(StringUtils.isEmpty(existingProperty.getValue())){ + if (StringUtils.isEmpty(existingProperty.getValue())) { existingProperty.setValue(parentValue); } - StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); - if(status != StorageOperationStatus.OK){ + StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); + if (status != StorageOperationStatus.OK) { log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); } - if(validationRes == null){ + if (validationRes == null) { validationRes = Either.left(true); } return validationRes; } private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { - if(oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue()!=null && !oldProperty.getValue().equals(newProperty.getValue())){ - log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ",oldProperty.getName(), newProperty.getValue()); + if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) { + log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue()); } } public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - Map groups = new HashMap<>(); - //Map groupsPropertiesMap = new HashMap<>(); + Map groups = new HashMap<>(); + // Map groupsPropertiesMap = new HashMap<>(); Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); @@ -2253,38 +1905,37 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } - //handle groups and convert to tosca data + // handle groups and convert to tosca data if (groupDefinitions != null && !groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { - Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); + Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); if (handleGroupRes.isRight()) { result = Either.right(handleGroupRes.right().value()); break; } GroupDefinition handledGroup = handleGroupRes.left().value(); groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); - + } } - if(result == null){ + if (result == null) { createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups); - if(createGroupsResult.isRight()){ + if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } } - if(result == null){ + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + public Either, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; List groups = new ArrayList<>(); - + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { TitanOperationStatus status = allDataTypes.right().value(); @@ -2293,10 +1944,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } - //handle groups and convert to tosca data + // handle groups and convert to tosca data if (groupDefinitions != null && !groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { - Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); + Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); if (handleGroupRes.isRight()) { result = Either.right(handleGroupRes.right().value()); break; @@ -2305,35 +1956,34 @@ public class GroupBusinessLogic extends BaseBusinessLogic { groups.add(new GroupDataDefinition(handledGroup)); } } - if(result == null){ + if (result == null) { createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups); - if(createGroupsResult.isRight()){ + if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } } - if(result == null){ + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + public Either, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList())); - if(createGroupsResult.isRight()){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if(result == null){ + + createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + /** * Update specific group version * @@ -2341,34 +1991,34 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List groupDefinitions) { + public Either, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List groupDefinitions) { Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList())); - if(createGroupsResult.isRight()){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if(result == null){ + + createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + public Either handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map allDAtaTypes) { - + Either result = null; - - log.trace("Going to create group {}" , groupDefinition); + + log.trace("Going to create group {}", groupDefinition); // 3. verify group not already exist List groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) { - + GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - + found = existGroupDef != null; } if (true == found) { @@ -2413,7 +2063,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } List groupTypeProperties = groupTypeDefinition.getProperties(); - + List properties = groupDefinition.convertToGroupProperties(); List updatedGroupTypeProperties = new ArrayList<>(); if (properties != null && false == properties.isEmpty()) { @@ -2429,20 +2079,20 @@ public class GroupBusinessLogic extends BaseBusinessLogic { int i = 1; for (GroupProperty prop : properties) { addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes); - if(addPropertyResult.isRight()){ + if (addPropertyResult.isRight()) { BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); } updatedGroupTypeProperties.add(addPropertyResult.left().value()); - + i++; } } - if(groupDefinition.getUniqueId() == null){ + if (groupDefinition.getUniqueId() == null) { String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName()); groupDefinition.setUniqueId(uid); } - groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); + groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); groupDefinition.setVersion(INITIAL_VERSION); @@ -2450,9 +2100,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return Either.left(groupDefinition); } - - - + public Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes) { if (prop == null) { @@ -2471,7 +2119,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { String innerType = checkInnerType.left().value(); - log.debug("Before validateAndUpdatePropertyValue"); Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); @@ -2490,24 +2137,19 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index); - + groupProperty.setUniqueId(uniqueId); groupProperty.setValue(newValue); - groupProperty.setType(prop.getType()); + groupProperty.setType(prop.getType()); groupProperty.setDefaultValue(prop.getDefaultValue()); groupProperty.setDescription(prop.getDescription()); groupProperty.setSchema(prop.getSchema()); groupProperty.setPassword(prop.isPassword()); groupProperty.setParentUniqueId(prop.getUniqueId()); - log.debug("Before adding property value to graph {}", groupProperty); - return Either.left(groupProperty); } - - - - + } 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 33390e7e98..1ff22dd17f 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 @@ -33,7 +33,6 @@ import java.util.function.Function; import org.apache.commons.lang3.StringEscapeUtils; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; @@ -103,7 +102,7 @@ public final class ImportUtils { } public enum ResultStatusEnum { - ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE + ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME } public enum ToscaElementTypeEnum { @@ -346,9 +345,9 @@ public final class ImportUtils { return inputDef; } - public static AttributeDefinition createModuleAttribute(Map attributeMap) { + public static PropertyDefinition createModuleAttribute(Map attributeMap) { - AttributeDefinition attributeDef = new AttributeDefinition(); + PropertyDefinition attributeDef = new PropertyDefinition(); ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type)); ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc)); ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status)); @@ -374,7 +373,7 @@ public final class ImportUtils { } - private static void setAttributeFieldStatus(Map propertyValue, AttributeDefinition propertyDef) { + private static void setAttributeFieldStatus(Map propertyValue, PropertyDefinition propertyDef) { Either propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS); if (propertyFieldIsStatus.isLeft()) { propertyDef.setStatus(propertyFieldIsStatus.left().value()); @@ -392,7 +391,7 @@ public final class ImportUtils { } - private static void setAttributeScheme(Map propertyValue, AttributeDefinition propertyDefinition) { + private static void setAttributeScheme(Map propertyValue, PropertyDefinition propertyDefinition) { Either eitherSchema = getSchema(propertyValue); if (eitherSchema.isLeft()) { SchemaDefinition schemaDef = new SchemaDefinition(); @@ -465,7 +464,7 @@ public final class ImportUtils { return ResultStatusEnum.OK; } - private static ResultStatusEnum setAttributeFieldDefaultValue(Map propertyValue, AttributeDefinition dataDefinition) { + private static ResultStatusEnum setAttributeFieldDefaultValue(Map propertyValue, PropertyDefinition dataDefinition) { Either propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); Gson gson = GsonFactory.getGson(); if (propertyFieldDefaultValue.isLeft()) { @@ -519,7 +518,7 @@ public final class ImportUtils { } } - private static void setAttributeFieldType(Map propertyValue, AttributeDefinition dataDefinition) { + private static void setAttributeFieldType(Map propertyValue, PropertyDefinition dataDefinition) { Either propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); if (propertyFieldType.isLeft()) { dataDefinition.setType(propertyFieldType.left().value()); @@ -533,7 +532,7 @@ public final class ImportUtils { } } - private static void setAttributeFieldDescription(Map propertyValue, AttributeDefinition dataDefinition) { + private static void setAttributeFieldDescription(Map propertyValue, PropertyDefinition dataDefinition) { Either propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); if (propertyFieldDescription.isLeft()) { dataDefinition.setDescription(propertyFieldDescription.left().value()); @@ -556,9 +555,9 @@ public final class ImportUtils { } - public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { - Function elementGenByName = elementName -> createAttribute(elementName); - Function, AttributeDefinition> func = map -> createModuleAttribute(map); + public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { + Function elementGenByName = elementName -> createAttribute(elementName); + Function, PropertyDefinition> func = map -> createModuleAttribute(map); return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); } @@ -595,8 +594,8 @@ public final class ImportUtils { } - private static AttributeDefinition createAttribute(String name) { - AttributeDefinition attribute = new AttributeDefinition(); + private static PropertyDefinition createAttribute(String name) { + PropertyDefinition attribute = new PropertyDefinition(); attribute.setName(name); return attribute; 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 8ffee1fd34..a2809b44cf 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 @@ -50,6 +50,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstInputsMap; @@ -551,7 +552,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return result; } - Either>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(inputsValueToCreateMap, component.getUniqueId()); + Either>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(component, inputsValueToCreateMap); if(addciInputsEither.isRight()){ log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); @@ -621,6 +622,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { input.setImmutable(oldInput.isImmutable()); input.setDefinition(oldInput.isDefinition()); input.setRequired(oldInput.isRequired()); + input.setOwnerId(null); + input.setParentUniqueId(null); inputsToCreate.put(input.getName(), input); @@ -739,7 +742,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } if (resourceProperties != null) { Map generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); - Either, String> mergeEither = PropertyDataDefinition.mergeProperties(generatedInputs, inputs, false); + Either, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); if(mergeEither.isRight()){ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); } @@ -808,6 +811,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (!optionalInput.isPresent()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); } + + InputDefinition inputForDelete = optionalInput.get(); // Lock component Either lockResultEither = lockComponent(componentId, component, "deleteInput"); @@ -818,8 +823,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } // Delete input operations - - InputDefinition inputForDelete = optionalInput.get(); try { StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); if(status != StorageOperationStatus.OK){ @@ -863,7 +866,9 @@ public class InputsBusinessLogic extends BaseBusinessLogic { resetInputName(mappedToscaTemplate, inputForDelete.getName()); - value = gson.toJson(mappedToscaTemplate); + value = ""; + if(!mappedToscaTemplate.isEmpty()) + value = gson.toJson(mappedToscaTemplate); propertyValue.setValue(value); String compInstId = propertyValue.getComponentInstanceId(); propertyValue.setRules(null); @@ -1159,6 +1164,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (properties != null && !properties.isEmpty()) { for (ComponentInstancePropInput propInput : properties) { + propInput.setOwnerId(null); + propInput.setParentUniqueId(null); Either createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, dataTypes, inputName, propInput); if (createInputRes.isRight()) { @@ -1260,6 +1267,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { inputsToCreate.put(input.getName(), input); + List propertiesList = new ArrayList<>(); // adding the property with the new value for UI + propertiesList.add(prop); + input.setProperties(propertiesList); + return Either.left(input); } 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 ffcb87c99c..587be4d169 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 @@ -74,7 +74,6 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.info.MergedArtifactInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; @@ -542,8 +541,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { try { Either, ResponseFormat> prepareForUpdate = null; Resource preparedResource = null; - - Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true); + Either uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user); + if (uploadComponentInstanceInfoMap.isRight()) { + ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); + componentsUtils.auditResource(responseFormat, user, newRresource, "", "", updateResource, null); + result = Either.right(responseFormat); + return result; + } + Map instances = uploadComponentInstanceInfoMap.left().value().getInstances(); + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(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()); @@ -571,14 +577,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - Either uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, preparedResource, yamlFileContents, user); - if (uploadComponentInstanceInfoMap.isRight()) { - ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); - componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - Map inputs = uploadComponentInstanceInfoMap.left().value().getInputs(); Either createInputsOnResource = createInputsOnResource(preparedResource, user, inputs, true); if (createInputsOnResource.isRight()) { @@ -590,7 +588,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } preparedResource = createInputsOnResource.left().value(); - Map instances = uploadComponentInstanceInfoMap.left().value().getInstances(); Either createResourcesInstancesEither = createResourceInstances(user, yamlFileName, preparedResource, instances, true, false, parseNodeTypeInfoYamlEither.left().value()); if (createResourcesInstancesEither.isRight()) { log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value()); @@ -677,7 +674,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map csar, String csarUUID, String yamlFileName, Resource oldResource, User user, - boolean inTransaction) { + boolean inTransaction, Map uploadComponentInstanceInfoMap) { Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); Map>> nodeTypesArtifactsToHandle = new HashMap<>(); @@ -685,7 +682,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { try { nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); - List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName()); + List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap); validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames); Either>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null; EnumMap> curNodeTypeArtifactsToHandle = null; @@ -913,7 +910,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return handleNodeTypeArtifactsRes; } - private List>, String>> extractVfcToscaNames(Map csar, String yamlFileName, String vfResourceName) { + @SuppressWarnings("unchecked") + private List>, String>> extractVfcToscaNames(Map csar, String yamlFileName, String vfResourceName, Map uploadComponentInstanceInfoMap) { List>, String>> vfcToscaNames = new ArrayList<>(); Map nodeTypes; if (csar != null) { @@ -921,12 +919,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { putNodeTypesFromYaml(csar, yamlFileName, nodeTypes); putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes); putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes); - + Map nestedServiceTemplatesMap = new HashMap<>(); + for(UploadComponentInstanceInfo ci : uploadComponentInstanceInfoMap.values()){ + if(ci.getProperties() != null && ci.getProperties().containsKey("service_template_filter")){ + String tempName = CsarUtils.DEFINITIONS_PATH + ((Map)ci.getProperties().get("service_template_filter").get(0).getValue()).get("substitute_service_template"); + putNodeTypesFromYaml(csar,tempName, nodeTypes); + nestedServiceTemplatesMap.put(ci.getType(), tempName); + } + } + if (!nodeTypes.isEmpty()) { Iterator> nodesNameEntry = nodeTypes.entrySet().iterator(); while (nodesNameEntry.hasNext()) { Entry nodeType = nodesNameEntry.next(); - addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey()); + addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey(), nestedServiceTemplatesMap); } } } @@ -947,20 +953,23 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private void addVfcToscaNameFindSubstitutes(Map csar, String vfResourceName, List>, String>> vfcToscaNames, String nodeTypeFullName) { + private void addVfcToscaNameFindSubstitutes(Map csar, String vfResourceName, List>, String>> vfcToscaNames, String nodeTypeFullName, Map nestedServiceTemplatesMap) { String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName); - String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName); + String nodeTypeTemplateYamlName =null; + if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){ + nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName); + } List relatedVfcsToscaNameSpaces = new ArrayList<>(); relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName)); - if (csar.containsKey(nodeTypeTemplateYamlName)) { - addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces); + if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) { + addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces, nestedServiceTemplatesMap); } ImmutablePair> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces); vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName)); } - private void addSubstituteToscaNamespacesRecursively(Map csar, String yamlFileName, List toscaNameSpaces) { + private void addSubstituteToscaNamespacesRecursively(Map csar, String yamlFileName, List toscaNameSpaces, Map nestedServiceTemplatesMap) { Map nodeTypes = new HashMap<>(); @@ -978,10 +987,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } toscaNameSpaces.add(toscaNameSpace); - String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName); + String nodeTypeTemplateYamlName =null; + if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){ + nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName); + } - if (csar.containsKey(nodeTypeTemplateYamlName)) { - addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces); + if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) { + addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces, nestedServiceTemplatesMap); } } } @@ -1651,7 +1663,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either result; Either createResourcesInstancesEither; - Map>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource); + Map>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource, uploadComponentInstanceInfoMap); log.debug("************* Going to create all nodes {}", yamlName); Either, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts); @@ -1694,10 +1706,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - private Map>> findNodeTypeArtifactsToCreate(Map csar, String yamlName, Resource resource) { + private Map>> findNodeTypeArtifactsToCreate(Map csar, String yamlName, Resource resource, Map uploadComponentInstanceInfoMap) { Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); - List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName()); + List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName(), uploadComponentInstanceInfoMap); validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames); Map>> nodeTypesArtifactsToHandle = null; if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) { @@ -3429,7 +3441,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map>> instCapabilties = new HashMap<>(); Map>> instRequirements = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); List relations = new ArrayList<>(); @@ -4321,7 +4333,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List getInputList = (List) getInput; getInputInfo.setPropName(propName); getInputInfo.setInputName((String) getInputList.get(0)); - if (getInputList.size() >= 1) { + if (getInputList.size() > 1) { Object indexObj = getInputList.get(1); if (indexObj instanceof Integer) { getInputInfo.setIndexValue((Integer) indexObj); @@ -5838,7 +5850,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - // Tal G for extending inheritance US815447 + // for extending inheritance US815447 private Either validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) { // If updated resource is not deriving, should fail validation /* @@ -6633,12 +6645,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return toscaResourceName; } - private String buildNestedSubstituteYamlName(String nodeTypeFullName) { - String[] nodeTypeFullNameParsed = nodeTypeFullName.split("\\."); - String nodeTypeActualName = nodeTypeFullNameParsed[nodeTypeFullNameParsed.length - 1]; - return CsarUtils.DEFINITIONS_PATH + nodeTypeActualName + Constants.SERVICE_TEMPLATE_FILE_POSTFIX; - } - public ICacheMangerOperation getCacheManagerOperation() { return cacheManagerOperation; } @@ -6726,6 +6732,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); if (resourceResultEither.isRight()) { + 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)); + } + log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); } 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 f35515f8fe..b157b635b4 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 @@ -31,6 +31,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.servlet.ServletContext; @@ -46,12 +47,12 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InterfaceDefinition; @@ -101,7 +102,9 @@ public class ResourceImportManager { @Autowired protected ResourceOperation resourceOperation; - + + public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern + .compile("[\\w\\-\\_\\d\\:]+"); @Autowired protected CapabilityTypeOperation capabilityTypeOperation; @Autowired @@ -289,7 +292,9 @@ public class ResourceImportManager { eitherResult = setCapabilities(toscaJson, resource, parentResource); if (eitherResult.isRight()) return eitherResult; - setProperties(toscaJson, resource); + eitherResult = setProperties(toscaJson, resource); + if (eitherResult.isRight()) + return eitherResult; eitherResult = setRequirements(toscaJson, resource, parentResource); if (eitherResult.isRight()) return eitherResult; @@ -467,10 +472,10 @@ public class ResourceImportManager { return result; } - private ResultStatusEnum setProperties(Map toscaJson, Resource resource) { + private Either setProperties(Map toscaJson, Resource resource) { Map reducedToscaJson = new HashMap<>(toscaJson); ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - ResultStatusEnum result = ResultStatusEnum.OK; + Either result = Either.left(true); Either, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); if (properties.isLeft()) { List propertiesList = new ArrayList<>(); @@ -478,28 +483,32 @@ public class ResourceImportManager { if (value != null) { for (Entry entry : value.entrySet()) { String name = entry.getKey(); + if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){ + log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); + } PropertyDefinition propertyDefinition = entry.getValue(); propertyDefinition.setName(name); propertiesList.add(propertyDefinition); } } resource.setProperties(propertiesList); - } else { - result = properties.right().value(); + } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); } return result; } private ResultStatusEnum setAttributes(Map toscaJson, Resource resource) { ResultStatusEnum result = ResultStatusEnum.OK; - Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); + Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); if (attributes.isLeft()) { - List attributeList = new ArrayList<>(); - Map value = attributes.left().value(); + List attributeList = new ArrayList<>(); + Map value = attributes.left().value(); if (value != null) { - for (Entry entry : value.entrySet()) { + for (Entry entry : value.entrySet()) { String name = entry.getKey(); - AttributeDefinition attributeDef = entry.getValue(); + PropertyDefinition attributeDef = entry.getValue(); attributeDef.setName(name); attributeList.add(attributeDef); } 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 1f481a7b5a..bc1c6e5910 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 @@ -1390,7 +1390,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); // Update Payload With Heat Env - vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); +// vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @@ -1436,7 +1436,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); } if (responseWrapper.isEmpty() && vfModuleAertifact != null) { - vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper); + vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper, service); } Either result; @@ -1449,21 +1449,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return result; } - private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper) { + private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper, Service service) { ArtifactDefinition result = null; - final Either eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); - if (eitherResource.isRight()) { - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); - } else if (!payloadWrapper.isEmpty()) { - Resource resource = eitherResource.left().value(); - Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, resource.getComponentType(), resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), +// final Either eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); +// if (eitherResource.isRight()) { +// responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); +// } else if (!payloadWrapper.isEmpty()) { +// Resource resource = eitherResource.left().value(); + Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); if (eitherPayload.isLeft()) { result = eitherPayload.left().value(); } else { responseWrapper.setInnerElement(eitherPayload.right().value()); } - } +// } if (result == null) { result = vfModuleArtifact; } @@ -1962,13 +1962,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return result; } - public Either getUiComponentDataTransferByComponentId(String resourceId, List dataParamsToReturn) { + public Either getUiComponentDataTransferByComponentId(String serviceId, List dataParamsToReturn) { ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); - Either serviceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); + Either serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen); if (serviceResultEither.isRight()) { - log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); + if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found service with id {} ", serviceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); + } + + log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString()); return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java index d6cbd3663c..14f54e4c19 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java @@ -21,7 +21,10 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; +import java.util.Collection; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -29,16 +32,22 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -97,6 +106,7 @@ public class CheckoutTransition extends LifeCycleTransition { ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); result = Either.right(responseFormat); } else { + Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); result = Either.left(clonedComponent); Either upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); @@ -132,7 +142,7 @@ public class CheckoutTransition extends LifeCycleTransition { private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { - StorageOperationStatus updateStatus = null; + StorageOperationStatus updateStatus = StorageOperationStatus.OK; Either updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); if (updateEither.isRight()) updateStatus = updateEither.right().value(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java index 46505b843e..6edfe81fee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java @@ -11,6 +11,7 @@ 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.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiComponentMetadata; import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer; import org.openecomp.sdc.be.ui.model.UiResourceMetadata; import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; @@ -215,4 +216,20 @@ public class UiComponentDataConverter { return dataTransfer; } + + public static UiComponentMetadata convertToUiComponentMetadata(Component component) { + + UiComponentMetadata uiComponentMetadata = null; + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource)component; + uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + break; + case SERVICE: + uiComponentMetadata = new UiServiceMetadata(component.getCategories(), (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()); + default: + + } + return uiComponentMetadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java index 7b49d3fcea..c88ec87d58 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java @@ -26,7 +26,7 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; import org.openecomp.portalsdk.core.restful.domain.EcompRole; import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -37,6 +37,7 @@ import org.openecomp.sdc.be.ecomp.converters.EcompUserConverter; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -378,4 +379,28 @@ public class EcompIntImpl implements IPortalRestAPIService { UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic"); return userBusinessLogic; } + + /** + * Gets and returns the userId for the logged-in user based on the request. + * If any error occurs, the method should throw PortalApiException with an + * appropriate message. The FW library will catch the exception and send an + * appropriate response to Portal. + * + * As a guideline for AT&T specific implementation, see the sample apps + * repository + * https://codecloud.web.att.com/projects/EP_SDK/repos/ecomp_portal_sdk_third_party/ + * for a sample implementation for on-boarded applications using EPSDK-FW. + * However, the app can always choose to have a custom implementation of + * this method. For Open-source implementation, for example, the app will + * have a totally different implementation for this method. + * + * @param request + * @return true if the request contains appropriate credentials, else false. + * @throws PortalAPIException + * If an unexpected error occurs while processing the request. + */ + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + return request.getHeader(Constants.USER_ID_HEADER); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java new file mode 100644 index 0000000000..2e94dfc554 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java @@ -0,0 +1,391 @@ +/*- + * ============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.ecomp.converters; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; +import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetDetailedMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceInstanceMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetDetailedMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; + +@org.springframework.stereotype.Component("asset-metadata-utils") +public class AssetMetadataConverter { + private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + /* + * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() + */ + public Either, ResponseFormat> convertToAssetMetadata(List componentList, String serverBaseURL, boolean detailed) { + if (componentList == null || componentList.isEmpty()) { + return Either.left(new LinkedList<>()); + } + List retResList = new LinkedList<>(); + + for (Component curr : componentList) { + Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + retResList.add(resMetaData.left().value()); + } + + return Either.left(retResList); + + } + + public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { + ComponentTypeEnum componentType = component.getComponentType(); + Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); + + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + else{ + return Either.left(resMetaData.left().value()); + } + + } + + private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { + + switch (componentType) { + + case RESOURCE: + + return generateResourceMeatdata(serverBaseURL, detailed, curr); + + case SERVICE: + + return generateServiceMetadata(serverBaseURL, detailed, curr); + + // For future US's that include product + /* + * case PRODUCT: if (component instanceof Product) { List retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return + * Either.left(retResList); + */ + default: + + ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); + return Either.right(responseFormat); + } + } + + private Either generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData; + metaData = createMetadaObject(detailed, curr.getComponentType()); + metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); + + if (detailed) { + Either converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { + AssetMetadata metaData = null; + switch (type) { + case SERVICE: + if (!detailed) { + metaData = new ServiceAssetMetadata(); + } else { + metaData = new ServiceAssetDetailedMetadata(); + } + break; + case RESOURCE: + if (!detailed) { + metaData = new ResourceAssetMetadata(); + } else { + metaData = new ResourceAssetDetailedMetadata(); + } + break; + default: + break; + } + return metaData; + } + + private Either generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); + + metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); + + if (detailed) { + Either converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { + asset.setUuid(component.getUUID()); + asset.setInvariantUUID(component.getInvariantUUID()); + asset.setName(component.getName()); + asset.setVersion(component.getVersion()); + if (!detailed) { + asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); + } else { + String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); + asset.setToscaModelURL(toscaModelUrl); + } + + return asset; + } + + private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); + CategoryDefinition categoryDefinition; + if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ + categoryDefinition = resource.getCategories().iterator().next(); + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName()); + } + assetToPopulate.setResourceType(resource.getResourceType().name()); + assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); + + return (T) assetToPopulate; + } + + private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); + + CategoryDefinition categoryDefinition = service.getCategories().iterator().next(); + + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setLifecycleState(service.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); + assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); + + return (T) assetToPopulate; + } + + private Either convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { + + List componentInstances = resource.getComponentInstances(); + + if (componentInstances != null) { + Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); + assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); + assetToPopulate.setDescription(resource.getDescription()); + return Either.left(assetToPopulate); + } + + private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { + + List componentInstances = service.getComponentInstances(); + + if (componentInstances != null) { + Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map deploymentArtifacts = service.getDeploymentArtifacts(); + assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); + + return Either.left(assetToPopulate); + } + + private T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map artifacts) { + + List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { + + List artifactMetaList = populateAssetWithArtifacts(service, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private List populateAssetWithArtifacts(Component component, Map artifacts) { + List artifactMetaList = new LinkedList<>(); + if (artifacts != null) { + Collection artefactDefList = artifacts.values(); + + for (ArtifactDefinition artifactDefinition : artefactDefList) { + if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { + ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); + artifactMetaList.add(convertedArtifactMetadata); + } + } + } + return artifactMetaList.isEmpty() ? null : artifactMetaList; + } + + private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { + // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} + final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; + + // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} + final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; + + ArtifactMetadata metadata = new ArtifactMetadata(); + + metadata.setArtifactName(artifact.getArtifactName()); + metadata.setArtifactType(artifact.getArtifactType()); + + if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { + metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); + } else { + metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); + } + + metadata.setArtifactDescription(artifact.getDescription()); + metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); + metadata.setArtifactChecksum(artifact.getArtifactChecksum()); + metadata.setArtifactUUID(artifact.getArtifactUUID()); + metadata.setArtifactVersion(artifact.getArtifactVersion()); + metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); + metadata.setArtifactLabel(artifact.getArtifactLabel()); + metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); + return metadata; + } + + private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { + List retList = new LinkedList<>(); + Map> uuidDuplicatesMap = new HashMap<>(); + + for (ComponentInstance componentInstance : componentInstances) { + ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); + String componentUid = componentInstance.getComponentUid(); + String invariantUUID, resourceUUID; + + if (!uuidDuplicatesMap.containsKey(componentUid)) { + Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); + if (eitherResource.isRight()) { + log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); + return Either.right(eitherResource.right().value()); + } else { + final Resource resource = eitherResource.left().value(); + invariantUUID = resource.getInvariantUUID(); + resourceUUID = resource.getUUID(); + ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); + uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); + } + } else { + invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); + resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); + } + + metadata.setResourceInvariantUUID(invariantUUID); + metadata.setResourceUUID(resourceUUID); + metadata.setResourceInstanceName(componentInstance.getName()); + metadata.setResourceName(componentInstance.getComponentName()); + metadata.setResourceVersion(componentInstance.getComponentVersion()); + metadata.setResoucreType(componentInstance.getOriginType().getValue()); + + if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ + LinkedList artifactMetaList = new LinkedList<>(); + Collection values = componentInstance.getDeploymentArtifacts().values(); + for (ArtifactDefinition artifactDefinition : values) { + ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); + artifactMetaList.add(converted); + } + metadata.setArtifacts(artifactMetaList); + } + retList.add(metadata); + } + return Either.left(retList); + } + + // For future US to support Product + /* + * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); + * + * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); + * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); + * + * List categories = product.getCategories(); List categoryMetadataList = new LinkedList<>(); + * + * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List subcategories = + * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List groups = product.getGroups(); for (GroupDefinition + * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); + * return retProdAsset; } } + */ +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java deleted file mode 100644 index 2c7de7032c..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java +++ /dev/null @@ -1,392 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.externalapi.servlet; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; -import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceInstanceMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import fj.data.Either; - -@org.springframework.stereotype.Component("asset-metadata-utils") -public class AssetMetadataConverter { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - - @Autowired - private ComponentsUtils componentsUtils; - - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - /* - * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() - */ - public Either, ResponseFormat> convertToAssetMetadata(List componentList, String serverBaseURL, boolean detailed) { - if (componentList == null || componentList.isEmpty()) { - return Either.left(new LinkedList<>()); - } - List retResList = new LinkedList<>(); - - for (Component curr : componentList) { - Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - retResList.add(resMetaData.left().value()); - } - - return Either.left(retResList); - - } - - public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { - ComponentTypeEnum componentType = component.getComponentType(); - Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); - - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - else{ - return Either.left(resMetaData.left().value()); - } - - } - - private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { - - switch (componentType) { - - case RESOURCE: - - return generateResourceMeatdata(serverBaseURL, detailed, curr); - - case SERVICE: - - return generateServiceMetadata(serverBaseURL, detailed, curr); - - // For future US's that include product - /* - * case PRODUCT: if (component instanceof Product) { List retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return - * Either.left(retResList); - */ - default: - - ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); - return Either.right(responseFormat); - } - } - - private Either generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData; - metaData = createMetadaObject(detailed, curr.getComponentType()); - metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); - - if (detailed) { - Either converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { - AssetMetadata metaData = null; - switch (type) { - case SERVICE: - if (!detailed) { - metaData = new ServiceAssetMetadata(); - } else { - metaData = new ServiceAssetDetailedMetadata(); - } - break; - case RESOURCE: - if (!detailed) { - metaData = new ResourceAssetMetadata(); - } else { - metaData = new ResourceAssetDetailedMetadata(); - } - break; - default: - break; - } - return metaData; - } - - private Either generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); - - metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); - - if (detailed) { - Either converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { - asset.setUuid(component.getUUID()); - asset.setInvariantUUID(component.getInvariantUUID()); - asset.setName(component.getName()); - asset.setVersion(component.getVersion()); - if (!detailed) { - asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); - } else { - String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); - asset.setToscaModelURL(toscaModelUrl); - } - - return asset; - } - - private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); - CategoryDefinition categoryDefinition; - if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ - categoryDefinition = resource.getCategories().iterator().next(); - assetToPopulate.setCategory(categoryDefinition.getName()); - assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName()); - } - assetToPopulate.setResourceType(resource.getResourceType().name()); - assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); - - return (T) assetToPopulate; - } - - private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); - - CategoryDefinition categoryDefinition = service.getCategories().iterator().next(); - - assetToPopulate.setCategory(categoryDefinition.getName()); - assetToPopulate.setLifecycleState(service.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); - assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); - - return (T) assetToPopulate; - } - - private Either convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { - - List componentInstances = resource.getComponentInstances(); - - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map deploymentArtifacts = resource.getDeploymentArtifacts(); - assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); - assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); - assetToPopulate.setDescription(resource.getDescription()); - return Either.left(assetToPopulate); - } - - private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { - - List componentInstances = service.getComponentInstances(); - - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map deploymentArtifacts = service.getDeploymentArtifacts(); - assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); - - return Either.left(assetToPopulate); - } - - private T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map artifacts) { - - List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { - - List artifactMetaList = populateAssetWithArtifacts(service, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private List populateAssetWithArtifacts(Component component, Map artifacts) { - List artifactMetaList = new LinkedList<>(); - if (artifacts != null) { - Collection artefactDefList = artifacts.values(); - - for (ArtifactDefinition artifactDefinition : artefactDefList) { - if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { - ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); - artifactMetaList.add(convertedArtifactMetadata); - } - } - } - return artifactMetaList.isEmpty() ? null : artifactMetaList; - } - - private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { - // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} - final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; - - // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} - final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; - - ArtifactMetadata metadata = new ArtifactMetadata(); - - metadata.setArtifactName(artifact.getArtifactName()); - metadata.setArtifactType(artifact.getArtifactType()); - - if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { - metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); - } else { - metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); - } - - metadata.setArtifactDescription(artifact.getDescription()); - metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); - metadata.setArtifactChecksum(artifact.getArtifactChecksum()); - metadata.setArtifactUUID(artifact.getArtifactUUID()); - metadata.setArtifactVersion(artifact.getArtifactVersion()); - metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); - metadata.setArtifactLabel(artifact.getArtifactLabel()); - metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); - return metadata; - } - - private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { - List retList = new LinkedList<>(); - Map> uuidDuplicatesMap = new HashMap<>(); - - for (ComponentInstance componentInstance : componentInstances) { - ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); - String componentUid = componentInstance.getComponentUid(); - String invariantUUID, resourceUUID; - - if (!uuidDuplicatesMap.containsKey(componentUid)) { - Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); - if (eitherResource.isRight()) { - log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); - return Either.right(eitherResource.right().value()); - } else { - final Resource resource = eitherResource.left().value(); - invariantUUID = resource.getInvariantUUID(); - resourceUUID = resource.getUUID(); - ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); - uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); - } - } else { - invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); - resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); - } - - metadata.setResourceInvariantUUID(invariantUUID); - metadata.setResourceUUID(resourceUUID); - metadata.setResourceInstanceName(componentInstance.getName()); - metadata.setResourceName(componentInstance.getComponentName()); - metadata.setResourceVersion(componentInstance.getComponentVersion()); - metadata.setResoucreType(componentInstance.getOriginType().getValue()); - - if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ - LinkedList artifactMetaList = new LinkedList<>(); - Collection values = componentInstance.getDeploymentArtifacts().values(); - for (ArtifactDefinition artifactDefinition : values) { - ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); - artifactMetaList.add(converted); - } - metadata.setArtifacts(artifactMetaList); - } - retList.add(metadata); - } - return Either.left(retList); - } - - // For future US to support Product - /* - * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); - * - * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); - * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); - * - * List categories = product.getCategories(); List categoryMetadataList = new LinkedList<>(); - * - * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List subcategories = - * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List groups = product.getGroups(); for (GroupDefinition - * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); - * return retProdAsset; } } - */ -} 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 552ad163ec..b0947c67f9 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 @@ -68,6 +68,7 @@ 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.ResourceTypeEnum; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java index ea2582cd1b..a6415dc9b9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java @@ -37,12 +37,14 @@ import org.codehaus.jackson.map.JsonDeserializer; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.module.SimpleModule; import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; @@ -1254,6 +1256,31 @@ public class ComponentsUtils { log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); return responseEnum; } + + public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + switch (resultStatus) { + case OK: + responseEnum = ActionStatus.OK; + break; + case ELEMENT_NOT_FOUND: + if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ + responseEnum = ActionStatus.PROPERTY_NOT_FOUND; + } + break; + case INVALID_PROPERTY_DEFAULT_VALUE: + case INVALID_PROPERTY_TYPE: + case INVALID_PROPERTY_VALUE: + case INVALID_PROPERTY_NAME: + case MISSING_ENTRY_SCHEMA_TYPE: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + return responseEnum; + } public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index 38629ab7a1..436b2319e9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -29,11 +29,7 @@ import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; -import org.openecomp.portalsdk.core.onboarding.ueb.UebException; -import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.operations.api.IResourceOperation; @@ -49,9 +45,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; private static Logger log = LoggerFactory.getLogger(BEAppContextListener.class.getName()); - - private static UebManager uebManager = null; - + public void contextInitialized(ServletContextEvent context) { super.contextInitialized(context); @@ -73,34 +67,10 @@ public class BEAppContextListener extends AppContextListener implements ServletC BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); - initUebManager(); - log.debug("After executing {}", this.getClass()); } - - private void initUebManager() { - try { - if (uebManager == null) { - uebManager = UebManager.getInstance(); - uebManager.initListener(null); - } - } catch (UebException ex) { - log.debug("Failed to initialize UebManager", ex); - BeEcompErrorManager.getInstance().logInternalConnectionError("InitUebManager", "Failed to initialize listener of UebManager", ErrorSeverity.ERROR); - } - log.debug("After init listener of UebManager"); - } - - public void contextDestroyed(ServletContextEvent context) { - if (uebManager != null) { - uebManager.shutdown(); - uebManager = null; - } - super.contextDestroyed(context); - - } - + private IResourceOperation getResourceOperationManager(Class clazz, WebApplicationContext webContext) { return webContext.getBean(clazz); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java index d8f834c970..6b16e71e82 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java @@ -278,7 +278,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } else { if (!resourceAuthorityEnum.isBackEndImport()) { isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); - //Tal only resource name is checked + //only resource name is checked } else { isValid = true; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java index c7bc481119..0c5961daeb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java @@ -38,7 +38,7 @@ import javax.ws.rs.core.Response; import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; @@ -96,13 +96,13 @@ public class AttributeServlet extends AbstractValidationsServlet { try { Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); // convert json to AttributeDefinition buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); + Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); if (createAttribute.isRight()) { errorWrapper.setInnerElement(createAttribute.right().value()); } else { @@ -115,7 +115,7 @@ public class AttributeServlet extends AbstractValidationsServlet { log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); response = buildErrorResponse(errorWrapper.getInnerElement()); } else { - AttributeDefinition createdAttDef = attributesWrapper.getInnerElement(); + PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); @@ -165,14 +165,14 @@ public class AttributeServlet extends AbstractValidationsServlet { try { // convert json to PropertyDefinition Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); // convert json to AttributeDefinition buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); + Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); // update property if (eitherUpdateAttribute.isRight()) { errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); @@ -186,7 +186,7 @@ public class AttributeServlet extends AbstractValidationsServlet { log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); response = buildErrorResponse(errorWrapper.getInnerElement()); } else { - AttributeDefinition updatedAttribute = attributesWrapper.getInnerElement(); + PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); @@ -232,12 +232,12 @@ public class AttributeServlet extends AbstractValidationsServlet { // delete the property AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); + Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); return buildErrorResponse(eitherAttribute.right().value()); } - AttributeDefinition attributeDefinition = eitherAttribute.left().value(); + PropertyDefinition attributeDefinition = eitherAttribute.left().value(); String name = attributeDefinition.getName(); log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); @@ -253,11 +253,11 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { + private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final AttributeDefinition attribute = gson.fromJson(data, AttributeDefinition.class); + final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); if (attribute == null) { log.info("Attribute content is invalid - {}", data); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index 2d5402f709..4278378bbc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -49,7 +49,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.api.IElementDAO; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.externalapi.servlet.AssetMetadataConverter; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.User; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index 6a7ecbb5fe..e509078c5c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -51,7 +51,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; @@ -191,7 +190,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } - // TODO Tal New Multiple Instance API @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") @Consumes(MediaType.APPLICATION_JSON) @@ -618,13 +616,13 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Wrapper errorWrapper = new Wrapper<>(); Wrapper dataWrapper = new Wrapper<>(); - Wrapper attributeWrapper = new Wrapper<>(); + Wrapper attributeWrapper = new Wrapper<>(); Wrapper blWrapper = new Wrapper<>(); validateInputStream(request, dataWrapper, errorWrapper); if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceAttribute.class, errorWrapper); + validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper); } if (errorWrapper.isEmpty()) { @@ -635,7 +633,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement(); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement()); - Either eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); + Either eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); if (eitherAttribute.isRight()) { errorWrapper.setInnerElement(eitherAttribute.right().value()); } else { 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 b28700ace4..3a40e9626e 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 @@ -87,12 +87,12 @@ public class ComponentServlet extends BeGenericServlet { private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName()); @GET - @Path("/{componentType}/{componentId}/conformanceLevelValidation") + @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", 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 conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Response response; ServletContext context = request.getSession().getServletContext(); @@ -103,7 +103,7 @@ public class ComponentServlet extends BeGenericServlet { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum != null) { ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either eitherConformanceLevel = compBL.validateConformanceLevel(componentId, componentTypeEnum, userId); + Either eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId); if (eitherConformanceLevel.isRight()) { response = buildErrorResponse(eitherConformanceLevel.right().value()); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java index 019a6ba8fd..d8b0a0ec39 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java @@ -39,11 +39,13 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.ui.model.UiComponentMetadata; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; @@ -138,7 +140,8 @@ public class LifecycleServlet extends BeGenericServlet { } log.debug("change state successful !!!"); - Object value = RepresentationUtils.toRepresentation(actionResponse.left().value()); + UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); + Object value = RepresentationUtils.toRepresentation(componentMetatdata); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); return response; } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java index a477bcf4fb..d1e3d02907 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java @@ -43,7 +43,6 @@ import javax.ws.rs.core.Response; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; @@ -474,41 +473,4 @@ public class UserAdminServlet extends BeGenericServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - - @GET - @Path("/{userId}/functionalmenu") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getFunctionalMenu(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either functionalMenuResp = userAdminManager.getFunctionalMenu(userId); - - if (functionalMenuResp.isRight()) { - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(functionalMenuResp.right().value(), userId)); - } else { - FunctionalMenuInfo functionalMenuInfo = functionalMenuResp.left().value(); - if (functionalMenuInfo != null && functionalMenuInfo.getFunctionalMenu() != null) { - log.debug("Functional menu fetched is {}", functionalMenuInfo.getFunctionalMenu()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), functionalMenuInfo.getFunctionalMenu()); - } else { - log.debug("Functional menu is null"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); - log.debug("get user failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } 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 3c0c80666c..b18cbc9adc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -20,16 +20,12 @@ package org.openecomp.sdc.be.tosca; -import java.io.File; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; -import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -41,13 +37,11 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -79,7 +73,7 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; import org.openecomp.sdc.be.resources.data.ESArtifactData; -import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import org.openecomp.sdc.be.tosca.model.ToscaTemplate; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; @@ -143,8 +137,9 @@ public class CsarUtils { private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; private static final String TOSCA_META_VERSION = "1.0"; private static final String CSAR_VERSION = "1.1"; - - public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s\\/]+)"; + private static String versionFirstThreeOctates; + + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\d\\w\\_\\-\\.\\s]+)(/)([\\d\\w\\_\\-\\.\\s]+)(/)([\\d\\w\\_\\-\\.\\s\\/]+)"; public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + // Artifact Group (i.e Deployment/Informational) @@ -155,6 +150,16 @@ public class CsarUtils { "([\\w\\_\\-\\.\\s]+)"; public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; + public CsarUtils() { + if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + versionFirstThreeOctates = matcher.group(0); + } else { + versionFirstThreeOctates = ""; + } + } + /** * * @param component @@ -301,39 +306,40 @@ public class CsarUtils { } //add inner components to CSAR - innerComponentsCache.forEach((childUid, innerComponentTriple) -> { - Component innerComponent = innerComponentTriple.getRight(); - String icFileName = innerComponentTriple.getMiddle(); - - try { - //add component to zip - Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); - byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); - zip.write(content); - - } catch (IOException e) { + + for (Entry> innerComponentTripleEntry : innerComponentsCache.entrySet()) { + + ImmutableTriple innerComponentTriple = innerComponentTripleEntry.getValue(); - } + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); - //add component interface to zip - if(!ToscaUtils.isAtomicType(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName); - } - }); + // add component to zip + Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + // add component interface to zip + if (!ToscaUtils.isAtomicType(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + } } - /*Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + //retrieve SDC.zip from Cassandra + Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); if(latestSchemaFilesFromCassandra.isRight()){ - return null; - }*/ + log.error("Error retrieving SDC Schema files from cassandra" ); + return Either.right(latestSchemaFilesFromCassandra.right().value()); + } - //TODO Tal G this is quick solution until Cassandra US is alligned - Either addSchemaFilesFromConfig = addSchemaFilesFromConfig(zip); + //add files from retireved SDC.zip to Definitions folder in CSAR + Either addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); - if(addSchemaFilesFromConfig.isRight()){ - return addSchemaFilesFromConfig; + if(addSchemaFilesFromCassandra.isRight()){ + return addSchemaFilesFromCassandra; } // Artifact Generation @@ -371,36 +377,47 @@ public class CsarUtils { return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); } - - private Either addSchemaFilesFromConfig(ZipOutputStream zip) throws ZipException, IOException { - final String pathAndFile = "config/SDC.zip"; + + private Either addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ - File file = new File(pathAndFile); - if(!file.exists()){ - log.debug("SDC.zip schema files archive not found"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } + final int initSize = 2048; - try(ZipFile zipFile = new ZipFile(new File(pathAndFile));){ - Enumeration entries = zipFile.entries(); + log.debug("Starting coppy from Schema file zip to CSAR zip"); + + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { - while(entries.hasMoreElements()){ - ZipEntry nextElement = entries.nextElement(); - InputStream inputStream = zipFile.getInputStream(nextElement); - byte[] byteArray = IOUtils.toByteArray(inputStream); - - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + nextElement.getName())); - zip.write(byteArray); + ZipEntry entry = null; + + while ((entry = zipStream.getNextEntry()) != null) { + + String entryName = entry.getName(); + int readSize = initSize; + byte[] entryData = new byte[initSize]; + + while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { + bos.write(entryData, 0, readSize); + } + + bos.flush(); + out.flush(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); + zip.write(out.toByteArray()); + zip.flush(); + out.reset(); } - zipFile.close(); - }catch (Exception e) { - log.debug("Error in writing SDC.zip schema files to CSAR"); + } catch (IOException e) { + log.error("Error while writing the SDC schema file to the CSAR {}", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } + log.debug("Finished coppy from Schema file zip to CSAR zip"); + return Either.left(zip); } + private void insertInnerComponentsToCache(Map> componentCache, Component childComponent) { @@ -705,25 +722,24 @@ public class CsarUtils { return Either.left(content); } - private Either getLatestSchemaFilesFromCassandra() { - Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); - matcher.find(); - final String VERSION_FIRST_THREE_OCTATES = matcher.group(0); - Either, ActionStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); + private Either getLatestSchemaFilesFromCassandra() { + Either, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); - if(specificSchemaFiles.isRight()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); - return Either.right(specificSchemaFiles.right().value()); + if(specificSchemaFiles.isRight()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); } - List listOfSchemas = specificSchemaFiles.left().value(); + List listOfSchemas = specificSchemaFiles.left().value(); if(listOfSchemas.isEmpty()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); - return Either.right(ActionStatus.GENERAL_ERROR); + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); } - ESSdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); return Either.left(schemaFile.getPayloadAsArray()); } 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 072861ba3a..8be5b0b4b3 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 @@ -336,10 +336,9 @@ public class ToscaExportHandler { Resource resource = (Resource) component; toscaMetadata.setType(resource.getResourceType().name()); toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); - if (!isInstance) { - toscaMetadata.setResourceVendor(resource.getVendorName()); - toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); - } + toscaMetadata.setResourceVendor(resource.getVendorName()); + toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); + break; case SERVICE: toscaMetadata.setType(component.getComponentType().getValue()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java index 54ba9bf571..6bec3fa938 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java @@ -25,7 +25,6 @@ import java.util.List; import javax.servlet.ServletContext; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.exception.ResponseFormat; @@ -50,7 +49,4 @@ public interface IUserBusinessLogic { public Either deActivateUser(User modifier, String userUniuqeIdToDeactive); public Either authorize(User authUser); - - public Either getFunctionalMenu(String userId); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java index c90cc6118f..7135bfb62e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java @@ -28,18 +28,14 @@ import java.util.Map; import javax.annotation.Resource; import javax.servlet.ServletContext; -import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.portalsdk.core.onboarding.ueb.FunctionalMenu; -import org.openecomp.portalsdk.core.onboarding.ueb.UebException; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; @@ -249,16 +245,17 @@ public class UserBusinessLogic implements IUserBusinessLogic { // comment until admin will be able to do do check-in/check-out from the // UI - Either, StorageOperationStatus> userPendingTasksReq = getPandingUserPandingTasksWithCommit(userToUpdate); + Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate); if (userPendingTasksReq.isRight()) { - log.debug("updateUserRole method - failed to get user pending tasks list", userIdToUpdate); + log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); } List userPendingTasks = userPendingTasksReq.left().value(); - if (userPendingTasks.size() > 0) { - log.debug("updateUserRole method - User canot be updated, user have panding projects", userIdToUpdate); - String userTasksStatusForErrorMessage = getUserPandingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); + if (!userPendingTasks.isEmpty()) { + log.debug("updateUserRole method - User canot be updated, user have pending projects userId {}", userIdToUpdate); + + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); handleAuditing(modifier, userToUpdate, userToUpdate, responseFormat, AuditingActionEnum.UPDATE_USER); @@ -413,7 +410,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { return Either.right(responseFormat); } - Either, StorageOperationStatus> userPendingTasksReq = getPandingUserPandingTasksWithCommit(userToDeactivate); + Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToDeactivate); if (userPendingTasksReq.isRight()) { log.debug("deActivateUser method - failed to get user pending tasks list", userUniuqeIdToDeactive); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); @@ -421,9 +418,9 @@ public class UserBusinessLogic implements IUserBusinessLogic { List userPendingTasks = userPendingTasksReq.left().value(); if (userPendingTasks.size() > 0) { - log.debug("deActivateUser method - User canot be deleted, user have panding projects", userUniuqeIdToDeactive); + log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive); - String userTasksStatusForErrorMessage = getUserPandingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); handleAuditing(modifier, userToDeactivate, userToDeactivate, responseFormat, AuditingActionEnum.DELETE_USER); @@ -589,7 +586,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { return Either.left(updatedUser); } - private Either, StorageOperationStatus> getPandingUserPandingTasksWithCommit(User user) { + private Either, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) { Either, StorageOperationStatus> result = null; @@ -601,21 +598,21 @@ public class UserBusinessLogic implements IUserBusinessLogic { case PRODUCT_STRATEGIST: case PRODUCT_MANAGER: properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPandingTasksList(user, properties); + return userAdminOperation.getUserPendingTasksList(user, properties); case TESTER: properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - return userAdminOperation.getUserPandingTasksList(user, properties); + return userAdminOperation.getUserPendingTasksList(user, properties); case ADMIN: properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPandingTasksList(user, properties); + return userAdminOperation.getUserPendingTasksList(user, properties); default: return Either.left(new ArrayList<>()); } } finally { // commit will be perform outside!!! if (result == null || result.isRight()) { - log.debug("getUserPandingTasksList failed to perform fetching"); + log.debug("getUserPendingTasksList failed to perform fetching"); titanDao.rollback(); } else { titanDao.commit(); @@ -623,7 +620,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { } } - private String getUserPandingTaskStatusByRole(UserRoleEnum role) { + private String getUserPendingTaskStatusByRole(UserRoleEnum role) { switch (role) { case DESIGNER: @@ -639,77 +636,4 @@ public class UserBusinessLogic implements IUserBusinessLogic { return ""; } } - - /** - * return the functional menu of a given user - * - * @param userId - * @param inTransaction - * @return - */ - public Either getFunctionalMenu(String userId) { - - boolean toCommit = false; - - FunctionalMenuInfo functionalMenuInfo = new FunctionalMenuInfo(); - - try { - - Either, ActionStatus> userResult = userAdminOperation.getUserDataWithFunctionalMenu(userId); - if (userResult.isRight()) { - ActionStatus actionStatus = userResult.right().value(); - if (actionStatus == ActionStatus.USER_NOT_FOUND) { - actionStatus = ActionStatus.INVALID_USER_ID; - } - return Either.right(actionStatus); - } - - ImmutablePair immutablePair = userResult.left().value(); - FunctionalMenuInfo currentFunctionalMenu = immutablePair.right; - String currentMenuStr = currentFunctionalMenu != null ? currentFunctionalMenu.getFunctionalMenu() : null; - - String functionalMenu = getFunctionalMenuFromUeb(userId); - - // functionalMenu can be null or since we catch UebException - if (functionalMenu != null && false == functionalMenu.isEmpty()) { - functionalMenuInfo.setFunctionalMenu(functionalMenu); - if (false == functionalMenu.equals(currentMenuStr)) { - log.debug("Going to update functional menu of user {}. Functional menu is {}", userId, functionalMenu); - userAdminOperation.createOrUpdateFunctionalMenu(userId, functionalMenu); - } - } else { - String menu = currentMenuStr; - if (menu == null) { - menu = "[]"; - } - log.debug("Fetch functional menu from old request. Functional menu is {}", menu); - functionalMenuInfo.setFunctionalMenu(menu); - } - - toCommit = true; - - } finally { - if (toCommit) { - titanDao.commit(); - } else { - titanDao.rollback(); - } - } - - return Either.left(functionalMenuInfo); - } - - private String getFunctionalMenuFromUeb(String userId) { - String functionalMenu = null; - try { - log.debug("Before calling to FunctionalMenu method for user {}", userId); - functionalMenu = FunctionalMenu.get(userId); - log.debug("Functional menu fetched is {}", functionalMenu); - - } catch (UebException e) { - log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB)", userId, e); - BeEcompErrorManager.getInstance().logInternalFlowError("FetchFunctionalMenu", "Failed to fetch 'functional menu'", ErrorSeverity.ERROR); - } - return functionalMenu; - } } diff --git a/catalog-be/src/main/resources/application-context.xml b/catalog-be/src/main/resources/application-context.xml index 702c63ea81..6c44b270c2 100644 --- a/catalog-be/src/main/resources/application-context.xml +++ b/catalog-be/src/main/resources/application-context.xml @@ -57,7 +57,7 @@ - + diff --git a/catalog-be/src/main/resources/config/SDC.zip b/catalog-be/src/main/resources/config/SDC.zip index dfb4be85fb..674f6f86b4 100644 Binary files a/catalog-be/src/main/resources/config/SDC.zip and b/catalog-be/src/main/resources/config/SDC.zip differ diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml index ef7a885678..0fb4e146d4 100644 --- a/catalog-be/src/main/resources/config/error-configuration.yaml +++ b/catalog-be/src/main/resources/config/error-configuration.yaml @@ -1765,7 +1765,7 @@ errors: # %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------------------------------ @@ -1776,3 +1776,11 @@ errors: 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" + } \ No newline at end of file diff --git a/catalog-be/src/main/resources/config/logback.xml b/catalog-be/src/main/resources/config/logback.xml index 8ba0a31944..ba16783536 100644 --- a/catalog-be/src/main/resources/config/logback.xml +++ b/catalog-be/src/main/resources/config/logback.xml @@ -1,8 +1,8 @@ - - + + 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 b4c442f3df..63d70c699e 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 @@ -21,6 +21,19 @@ map: json: derived_from: tosca.datatypes.Root + +scalar-unit: + derived_from: tosca.datatypes.Root + +scalar-unit.size: + derived_from: scalar-unit + +scalar-unit.time: + derived_from: scalar-unit + +scalar-unit.frequency: + derived_from: scalar-unit + tosca.datatypes.Credential: derived_from: tosca.datatypes.Root 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 4f3e269c69..9c5964df1d 100644 Binary files a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip and b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip differ diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index 5bda32495b..6cb90d0920 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -40,8 +40,10 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -96,7 +98,7 @@ public class ArtifactBusinessLogicTest { public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); public static final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class); public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - + // public static final InformationDeployedArtifactsBusinessLogic // informationDeployedArtifactsBusinessLogic = // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java new file mode 100644 index 0000000000..fd7717a769 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.impl; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; + + +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + + +public class ArtifactResolverTest { + + private ArtifactResolverImpl testInstance = new ArtifactResolverImpl(); + private Service service, noArtifactsService; + private Resource resource, noArtifactsResource; + private ComponentInstance componentInstance, noArtifactsInstance; + + @Before + public void setUp() throws Exception { + noArtifactsService = new Service(); + noArtifactsResource = new Resource(); + resource = new Resource(); + service = new Service(); + componentInstance = new ComponentInstance(); + noArtifactsInstance = new ComponentInstance(); + + ArtifactDefinition artifact1 = new ArtifactDefinition(); + artifact1.setUniqueId("a1"); + + ArtifactDefinition artifact2 = new ArtifactDefinition(); + artifact2.setUniqueId("a2"); + + ArtifactDefinition artifact3 = new ArtifactDefinition(); + artifact3.setUniqueId("a3"); + + Map artifact1Map = Collections.singletonMap("key1", artifact1); + Map artifact2Map = Collections.singletonMap("key1", artifact2); + Map artifact3Map = Collections.singletonMap("key1", artifact3); + + resource.setDeploymentArtifacts(artifact1Map); + resource.setArtifacts(artifact2Map); + + service.setDeploymentArtifacts(artifact1Map); + service.setArtifacts(artifact2Map); + service.setServiceApiArtifacts(artifact3Map); + + componentInstance.setDeploymentArtifacts(artifact1Map); + componentInstance.setArtifacts(artifact2Map); + } + + @Test + public void findArtifactOnComponent_noArtifactsOnComponent() throws Exception { + assertNull(testInstance.findArtifactOnComponent(noArtifactsResource, ComponentTypeEnum.RESOURCE, "someId")); + assertNull(testInstance.findArtifactOnComponent(noArtifactsService, ComponentTypeEnum.SERVICE, "someId")); + } + + @Test + public void findArtifactOnComponent_resource() throws Exception { + assertNull(testInstance.findArtifactOnComponent(resource, ComponentTypeEnum.RESOURCE, "someId")); + assertNotNull(testInstance.findArtifactOnComponent(resource, ComponentTypeEnum.RESOURCE, "a1")); + assertNotNull(testInstance.findArtifactOnComponent(resource, ComponentTypeEnum.RESOURCE, "a2")); + } + + @Test + public void findArtifactOnComponent_service() throws Exception { + assertNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "someId")); + assertNotNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "a1")); + assertNotNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "a2")); + assertNotNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "a3")); + } + + @Test + public void findArtifactOnInstance_instanceHasNoArtifacts() throws Exception { + assertNull(testInstance.findArtifactOnComponentInstance(noArtifactsInstance, "someId")); + } + + @Test + public void findArtifactOnInstance() throws Exception { + assertNull(testInstance.findArtifactOnComponentInstance(componentInstance, "someId")); + assertNotNull(testInstance.findArtifactOnComponentInstance(componentInstance, "a1")); + assertNotNull(testInstance.findArtifactOnComponentInstance(componentInstance, "a2")); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index 6dd19cce57..59d49de3a3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -42,7 +42,6 @@ import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; @@ -300,7 +299,7 @@ public class ImportUtilsTest { public void testGetAttributesFromYml() throws IOException { Map toscaJson = (Map) loadJsonFromFile("importToscaWithAttribute.yml"); - Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); assertTrue(actualAttributes.isLeft()); Map> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); compareAttributes(expectedAttributes, actualAttributes.left().value()); @@ -318,10 +317,10 @@ public class ImportUtilsTest { } - private void compareAttributes(Map> expected, Map actual) { + private void compareAttributes(Map> expected, Map actual) { Map singleExpectedAttribute; - AttributeDefinition actualAttribute, expectedAttributeModel; + PropertyDefinition actualAttribute, expectedAttributeModel; // attributes of resource for (Map.Entry> expectedAttribute : expected.entrySet()) { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java index 2aa061a890..d6808da5d6 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java @@ -52,6 +52,7 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; 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 acd8563878..ee74a468fc 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 @@ -71,7 +71,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, + 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, // 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, diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java index e6843eab2f..1168bf4edf 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java @@ -1,6 +1,6 @@ package org.openecomp.sdc.be.dao.cassandra; -import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; @@ -10,5 +10,5 @@ import com.datastax.driver.mapping.annotations.Query; @Accessor public interface SdcSchemaFilesAccessor { @Query("SELECT * FROM sdcartifact.sdcschemafiles WHERE SDCRELEASENUM = :sdcreleasenum AND CONFORMANCELEVEL = :conformancelevel") - Result getSpecificSdcSchemaFiles(@Param("sdcreleasenum") String sdcreleasenum, @Param("conformancelevel") String conformancelevel); + Result getSpecificSdcSchemaFiles(@Param("sdcreleasenum") String sdcreleasenum, @Param("conformancelevel") String conformancelevel); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java index 1bb0f05898..d292c1ddeb 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java @@ -1,13 +1,11 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.LinkedList; import java.util.List; import javax.annotation.PostConstruct; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,33 +48,41 @@ public class SdcSchemaFilesCassandraDao extends CassandraDao { } } - public CassandraOperationStatus saveArtifact(ESSdcSchemaFilesData artifact) { - return client.save(artifact, ESSdcSchemaFilesData.class, manager); + public CassandraOperationStatus saveSchemaFile(SdcSchemaFilesData schemaFileData) { + return client.save(schemaFileData, SdcSchemaFilesData.class, manager); } - public Either getArtifact(String artifactId) { - return client.getById(artifactId, ESSdcSchemaFilesData.class, manager); + public Either getSchemaFile(String schemaFileId) { + return client.getById(schemaFileId, SdcSchemaFilesData.class, manager); } - public CassandraOperationStatus deleteArtifact(String artifactId) { - return client.delete(artifactId, ESSdcSchemaFilesData.class, manager); + public CassandraOperationStatus deleteSchemaFile(String schemaFileId) { + return client.delete(schemaFileId, SdcSchemaFilesData.class, manager); } - public Either, ActionStatus> getSpecificSchemaFiles(String sdcreleasenum, String conformancelevel) { - Result specificSdcSchemaFiles = sdcSchemaFilesAccessor.getSpecificSdcSchemaFiles(sdcreleasenum, conformancelevel); + public Either, CassandraOperationStatus> getSpecificSchemaFiles(String sdcreleasenum, String conformancelevel) { + + Result specificSdcSchemaFiles = null; + try { + specificSdcSchemaFiles = sdcSchemaFilesAccessor.getSpecificSdcSchemaFiles(sdcreleasenum, conformancelevel); + } catch (Exception e) { + logger.debug("getSpecificSchemaFiles failed with exception {}", e); + return Either.right(CassandraOperationStatus.GENERAL_ERROR); + } if(specificSdcSchemaFiles == null) { logger.debug("not found specific SdcSchemaFiles for sdcreleasenum {}, conformancelevel {}", sdcreleasenum, conformancelevel); - return Either.left(new LinkedList()); + return Either.right(CassandraOperationStatus.NOT_FOUND); } + List list = specificSdcSchemaFiles.all(); if(logger.isDebugEnabled()){ - for (ESSdcSchemaFilesData esSdcSchemaFilesData : specificSdcSchemaFiles) { - logger.debug(esSdcSchemaFilesData.toString()); + for (SdcSchemaFilesData esSdcSchemaFilesData : list) { + logger.trace(esSdcSchemaFilesData.toString()); } } - return Either.left(specificSdcSchemaFiles.all()); + return Either.left(list); } /** diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java index c485b238f4..cb9c7207d2 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java @@ -16,7 +16,7 @@ public enum VertexTypeEnum { CAPABILTIES ("capabilities", ListCapabilityDataDefinition.class), CAPABILITIES_PROPERTIES ("capabilities_properties", MapPropertiesDataDefinition.class), REQUIREMENTS ("requirements", ListRequirementDataDefinition.class), - ATTRIBUTES ("attributes", AttributeDataDefinition.class), + ATTRIBUTES ("attributes", PropertyDataDefinition.class), RESOURCE_CATEGORY ("resourceNewCategory", null), RESOURCE_SUBCATEGORY ("resourceSubcategory", null), SERVICE_CATEGORY ("serviceNewCategory", null), @@ -24,7 +24,7 @@ public enum VertexTypeEnum { USER ("user", null), INPUTS ("inputs", PropertyDataDefinition.class), GROUPS ("groups", GroupDataDefinition.class), - INST_ATTRIBUTES ("instAttributes", MapAttributesDataDefinition.class), + INST_ATTRIBUTES ("instAttributes", MapPropertiesDataDefinition.class), INST_PROPERTIES ("instProperties", MapPropertiesDataDefinition.class), INST_INPUTS ("instInputs", MapPropertiesDataDefinition.class), INST_GROUPS ("instGroups", MapGroupsDataDefinition.class), diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java index 3ec9d0d3b9..2ff1567928 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java @@ -29,6 +29,7 @@ public enum GraphPropertiesDictionary { CONTACT_ID ("contactId", String.class, false, false), VENDOR_NAME ("vendorName", String.class, false, false), VENDOR_RELEASE ("vendorRelease", String.class, false, false), + CONFORMANCE_LEVEL ("conformanceLevel", String.class, false, false), ICON ("icon", String.class, false, false), TAGS ("tags", String.class, false, false), UUID ("uuid", String.class, false, true), diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java index 16a8c8be60..a99529d950 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java @@ -27,21 +27,21 @@ import java.util.Map; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; +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 com.google.gson.reflect.TypeToken; public class AttributeData extends GraphNode { - AttributeDataDefinition attributeDataDefinition; + PropertyDataDefinition attributeDataDefinition; public AttributeData() { super(NodeTypeEnum.Attribute); - attributeDataDefinition = new AttributeDataDefinition(); + attributeDataDefinition = new PropertyDataDefinition(); } - public AttributeData(AttributeDataDefinition attributeDataDefinition) { + public AttributeData(PropertyDataDefinition attributeDataDefinition) { super(NodeTypeEnum.Attribute); this.attributeDataDefinition = attributeDataDefinition; } @@ -56,11 +56,11 @@ public class AttributeData extends GraphNode { return attributeDataDefinition.getUniqueId(); } - public AttributeDataDefinition getAttributeDataDefinition() { + public PropertyDataDefinition getAttributeDataDefinition() { return attributeDataDefinition; } - public void setAttributeDataDefinition(AttributeDataDefinition attributeDataDefinition) { + public void setAttributeDataDefinition(PropertyDataDefinition attributeDataDefinition) { this.attributeDataDefinition = attributeDataDefinition; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java index 0ad081832f..7e084eb021 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java @@ -51,6 +51,7 @@ public abstract class ComponentMetadataData extends GraphNode { metadataDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty())); metadataDataDefinition.setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty())); metadataDataDefinition.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty())); + metadataDataDefinition.setConformanceLevel((String) properties.get(GraphPropertiesDictionary.CONFORMANCE_LEVEL.getProperty())); metadataDataDefinition.setIcon((String) properties.get(GraphPropertiesDictionary.ICON.getProperty())); metadataDataDefinition.setHighestVersion((Boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty())); metadataDataDefinition.setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty())); @@ -87,6 +88,7 @@ public abstract class ComponentMetadataData extends GraphNode { addIfExists(map, GraphPropertiesDictionary.VERSION, metadataDataDefinition.getVersion()); addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, metadataDataDefinition.getCreationDate()); addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, metadataDataDefinition.getDescription()); + addIfExists(map, GraphPropertiesDictionary.CONFORMANCE_LEVEL, metadataDataDefinition.getConformanceLevel()); addIfExists(map, GraphPropertiesDictionary.ICON, metadataDataDefinition.getIcon()); addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, metadataDataDefinition.isHighestVersion()); addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, metadataDataDefinition.getLastUpdateDate()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java deleted file mode 100644 index c6ab13bb3d..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESSdcSchemaFilesData.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.openecomp.sdc.be.resources.data; - -import java.nio.ByteBuffer; -import java.util.Date; - -import com.datastax.driver.mapping.annotations.Column; -import com.datastax.driver.mapping.annotations.Table; - -@Table(keyspace = "sdcartifact", name = "sdcschemafiles") -public class ESSdcSchemaFilesData { - - @Column(name = "sdcreleasenum") - private String sdcReleaseNum; - - @Column(name = "timestamp") - private Date timestamp; - - @Column(name = "conformanceLevel") - private String conformanceLevel; - - @Column(name = "fileName") - private String fileName; - - @Column(name = "payload") - private ByteBuffer payload; - - @Column(name = "checksum") - private String checksum; - - public ESSdcSchemaFilesData() { - - } - - public ESSdcSchemaFilesData(String sdcReleaseNum, String conformanceLevel, String fileName, byte[] payload){ - this.sdcReleaseNum = sdcReleaseNum; - this.conformanceLevel = conformanceLevel; - this.fileName = fileName; - if(payload != null) { - this.payload = ByteBuffer.wrap(payload.clone()); - } - } - - public String getSdcReleaseNum() { - return sdcReleaseNum; - } - - public void setSdcReleaseNum(String sdcReleaseNum) { - this.sdcReleaseNum = sdcReleaseNum; - } - - public String getConformanceLevel() { - return conformanceLevel; - } - - public void setConformanceLevel(String conformanceLevel) { - this.conformanceLevel = conformanceLevel; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public ByteBuffer getPayload() { - return payload; - } - - public void setPayload(ByteBuffer payload) { - if(payload != null){ - this.payload = payload.duplicate(); - } - } - - public void setPayloadAsArray(byte[] payload) { - if(payload != null){ - this.payload = ByteBuffer.wrap(payload.clone()); - } - } - - public byte[] getPayloadAsArray() { - return payload != null ? payload.array() : null; - } - - public Date getTimestamp() { - return timestamp; - } - - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - public String getChecksum() { - return checksum; - } - - public void setChecksum(String checksum) { - this.checksum = checksum; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java new file mode 100644 index 0000000000..96ab5aedc8 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java @@ -0,0 +1,114 @@ +package org.openecomp.sdc.be.resources.data; + +import java.nio.ByteBuffer; +import java.util.Date; + +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; + +@Table(keyspace = "sdcartifact", name = "sdcschemafiles") +public class SdcSchemaFilesData { + @PartitionKey(0) + @Column(name = "sdcreleasenum") + private String sdcReleaseNum; + + @ClusteringColumn + @Column(name = "timestamp") + private Date timestamp; + + @PartitionKey(1) + @Column(name = "conformanceLevel") + private String conformanceLevel; + + @Column(name = "fileName") + private String fileName; + + @Column(name = "payload") + private ByteBuffer payload; + + @Column(name = "checksum") + private String checksum; + + public SdcSchemaFilesData() { + + } + + public SdcSchemaFilesData(String sdcReleaseNum, Date timestamp, String conformanceLevel, String fileName, byte[] payload, String checksum){ + this.sdcReleaseNum = sdcReleaseNum; + this.timestamp = timestamp; + this.conformanceLevel = conformanceLevel; + this.fileName = fileName; + if(payload != null) { + this.payload = ByteBuffer.wrap(payload.clone()); + } + this.checksum = checksum; + } + + public String getSdcReleaseNum() { + return sdcReleaseNum; + } + + public void setSdcReleaseNum(String sdcReleaseNum) { + this.sdcReleaseNum = sdcReleaseNum; + } + + public String getConformanceLevel() { + return conformanceLevel; + } + + public void setConformanceLevel(String conformanceLevel) { + this.conformanceLevel = conformanceLevel; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public ByteBuffer getPayload() { + return payload; + } + + public void setPayload(ByteBuffer payload) { + if(payload != null){ + this.payload = payload.duplicate(); + } + } + + public void setPayloadAsArray(byte[] payload) { + if(payload != null){ + this.payload = ByteBuffer.wrap(payload.clone()); + } + } + + public byte[] getPayloadAsArray() { + return payload != null ? payload.array() : null; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public String getChecksum() { + return checksum; + } + + public void setChecksum(String checksum) { + this.checksum = checksum; + } + + @Override + public String toString() { + return "SdcSchemaFilesData [sdcReleaseNum=" + sdcReleaseNum + ", timestamp=" + timestamp + ", conformanceLevel=" + + conformanceLevel + ", fileName=" + fileName + ", checksum=" + checksum + "]"; + } +} diff --git a/catalog-fe/pom.xml b/catalog-fe/pom.xml index a3acabb41f..e5d4bdaf83 100644 --- a/catalog-fe/pom.xml +++ b/catalog-fe/pom.xml @@ -246,7 +246,7 @@ org.openecomp.ecompsdkos - ecompFW + epsdk-fw ${ecomp.version} compile diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java index 4eba2e5eb5..a743f98b18 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java @@ -34,7 +34,9 @@ import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; -import org.openecomp.portalsdk.core.onboarding.crossapi.ECOMPSSO; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.impl.MutableHttpServletRequest; import org.openecomp.sdc.fe.Constants; @@ -95,9 +97,8 @@ public class PortalServlet extends HttpServlet { if (null == userId) { // Authentication via ecomp portal try { - String valdiateECOMPSSO = ECOMPSSO.valdiateECOMPSSO(request); - String userIdFromCookie = ECOMPSSO.getUserIdFromCookie(request); - if (valdiateECOMPSSO == null || ("").equals(userIdFromCookie)) { + String userIdFromCookie = getUserIdFromCookie(request); + if (("").equals(userIdFromCookie)) { // This is probably a webseal request, so missing header in request should be printed. response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG); } @@ -275,5 +276,20 @@ public class PortalServlet extends HttpServlet { } return newHeaderIsSet; } + + private static String getUserIdFromCookie(HttpServletRequest request) throws Exception { + String userId = ""; + Cookie[] cookies = request.getCookies(); + Cookie userIdcookie = null; + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(Constants.USER_ID)) + userIdcookie = cookie; + if (userIdcookie != null) { + userId = CipherUtil.decrypt(userIdcookie.getValue(), + PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key)); + } + return userId; + } } diff --git a/catalog-fe/src/main/resources/config/logback.xml b/catalog-fe/src/main/resources/config/logback.xml index fd2e13ca43..d1e1c613d1 100644 --- a/catalog-fe/src/main/resources/config/logback.xml +++ b/catalog-fe/src/main/resources/config/logback.xml @@ -1,8 +1,8 @@ - - + + diff --git a/catalog-fe/src/test/resources/CI/originalResources/images/network.png b/catalog-fe/src/test/resources/CI/originalResources/images/network.png index c8bf18f31a..c98eef324e 100644 Binary files a/catalog-fe/src/test/resources/CI/originalResources/images/network.png and b/catalog-fe/src/test/resources/CI/originalResources/images/network.png differ diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java deleted file mode 100644 index 120a87c610..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model; - -import java.io.Serializable; - -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; - -public class AttributeDefinition extends AttributeDataDefinition implements IComplexDefaultValue, Serializable { - - /** - * - */ - private static final long serialVersionUID = -6306111879714097811L; - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((parentUniqueId == null) ? 0 : parentUniqueId.hashCode()); - return result; - } - - /** - * The resource id which this property belongs to - */ - private String parentUniqueId; - - public AttributeDefinition(AttributeDefinition hpdd) { - super(hpdd); - } - - public AttributeDefinition() { - super(); - } - - public AttributeDefinition(AttributeDataDefinition p) { - super(p); - } - - public String getParentUniqueId() { - return parentUniqueId; - } - - public void setParentUniqueId(String parentUniqueId) { - this.parentUniqueId = parentUniqueId; - } - - @Override - public String toString() { - return super.toString() + " [ parentUniqueId=" + parentUniqueId + "]"; - } -} 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 6ccb49a4b3..036108e81f 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 @@ -54,7 +54,7 @@ public abstract class Component implements Serializable { private Map> componentInstancesProperties; - private Map> componentInstancesAttributes; + private Map> componentInstancesAttributes; private Map> capabilities; @@ -609,12 +609,12 @@ public abstract class Component implements Serializable { } } - public Map> getComponentInstancesAttributes() { + public Map> getComponentInstancesAttributes() { return componentInstancesAttributes; } public void setComponentInstancesAttributes( - Map> componentInstancesAttributes) { + Map> componentInstancesAttributes) { this.componentInstancesAttributes = componentInstancesAttributes; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java deleted file mode 100644 index 4e55152526..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model; - -import java.io.Serializable; - -public class ComponentInstanceAttribute extends AttributeDefinition - implements IComponentInstanceConnectedElement, Serializable { - - /** - * - */ - private static final long serialVersionUID = -496828411269235795L; - - private Boolean hidden; - - /** - * The unique id of the attribute value on graph - */ - private String valueUniqueUid; - - public ComponentInstanceAttribute() { - super(); - } - - public ComponentInstanceAttribute(AttributeDefinition pd, Boolean hidden, String valueUniqueUid) { - super(pd); - - this.hidden = hidden; - this.valueUniqueUid = valueUniqueUid; - setParentUniqueId(pd.getParentUniqueId()); - } - - public ComponentInstanceAttribute(AttributeDefinition attributeDefinition) { - super(attributeDefinition); - } - - public String getValueUniqueUid() { - return valueUniqueUid; - } - - public void setValueUniqueUid(String valueUniqueUid) { - this.valueUniqueUid = valueUniqueUid; - } - - @Override - public String toString() { - return "ComponentInstanceAttribute [ " + super.toString() + " , value=" + hidden + ", valueUniqueUid = " - + valueUniqueUid + " ]"; - } - - public Boolean isHidden() { - return hidden; - } - - public void setHidden(Boolean hidden) { - this.hidden = hidden; - } - -} 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 ca53db69d9..9347f326d1 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 @@ -32,10 +32,6 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen */ private static final long serialVersionUID = -3937554584759816724L; - /** - * Value of property - */ - private String value; /** * The unique id of the property value on graph @@ -58,14 +54,14 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen String valueUniqueUid) { super(curPropertyDef); this.inputId = inputId; - this.value = value; + setValue(value); this.valueUniqueUid = valueUniqueUid; } public ComponentInstanceInput(InputDefinition pd, String value, String valueUniqueUid) { super(pd); - this.value = value; + setValue(value); this.valueUniqueUid = valueUniqueUid; } @@ -100,14 +96,6 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen this.inputId = inputId; } - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - public String getValueUniqueUid() { return valueUniqueUid; } @@ -142,7 +130,7 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen @Override public String toString() { - return "ComponentInstanceInput [ " + super.toString() + " , value=" + value + ", valueUniqueUid = " + return "ComponentInstanceInput [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]"; } 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 17eb045630..8bd3a9c809 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 @@ -87,6 +87,14 @@ public class ComponentInstanceProperty extends PropertyDefinition implements ICo this.setValue(value); this.valueUniqueUid = valueUniqueUid; } + + public ComponentInstanceProperty(Boolean hidden, PropertyDefinition pd, String valueUniqueUid) { + super(pd); + + this.hidden = hidden; + this.valueUniqueUid = valueUniqueUid; + setParentUniqueId(pd.getParentUniqueId()); + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java index b315d5c7fd..34ecdbf06d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java @@ -104,7 +104,7 @@ public class PropertyDefinition extends PropertyDataDefinition private List constraints; // private Schema schema; - private String status; + // private String status; @@ -120,7 +120,7 @@ public class PropertyDefinition extends PropertyDataDefinition public PropertyDefinition(PropertyDefinition pd) { super(pd); this.setConstraints(pd.getConstraints()); - status = pd.status; + //status = pd.status; } @@ -149,13 +149,13 @@ public class PropertyDefinition extends PropertyDataDefinition // return schema; // } - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } +// public String getStatus() { +// return status; +// } +// +// public void setStatus(String status) { +// this.status = status; +// } @@ -174,7 +174,7 @@ public class PropertyDefinition extends PropertyDataDefinition int result = super.hashCode(); result = prime * result + ((constraints == null) ? 0 : constraints.hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); + //result = prime * result + ((status == null) ? 0 : status.hashCode()); return result; } @@ -197,11 +197,11 @@ public class PropertyDefinition extends PropertyDataDefinition return false; } else if (!getName().equals(other.getName())) return false; - if (status == null) { - if (other.status != null) - return false; - } else if (!status.equals(other.status)) - return false; +// if (status == null) { +// if (other.status != null) +// return false; +// } else if (!status.equals(other.status)) +// return false; return true; } 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 5e7983acea..a9c6b44324 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 @@ -52,7 +52,7 @@ public class Resource extends Component implements Serializable { private List properties; - private List attributes; + private List attributes; // Later private Map interfaces; @@ -98,11 +98,11 @@ public class Resource extends Component implements Serializable { this.properties = properties; } - public List getAttributes() { + public List getAttributes() { return attributes; } - public void setAttributes(List attributes) { + public void setAttributes(List attributes) { this.attributes = attributes; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java index 7c6c207f74..c1b4129afc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java @@ -3,11 +3,11 @@ package org.openecomp.sdc.be.model.jsontitan.datamodel; import java.util.List; import java.util.Map; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; public class NodeType extends ToscaElement{ @@ -18,7 +18,7 @@ public class NodeType extends ToscaElement{ private List derivedFrom; private List derivedList; - private Map attributes; + private Map attributes; private Map capabilties; private Map capabiltiesProperties; private Map requirements; @@ -45,11 +45,11 @@ public class NodeType extends ToscaElement{ this.derivedFrom = derivedFrom; } - public Map getAttributes() { + public Map getAttributes() { return attributes; } - public void setAttributes(Map attributes) { + public void setAttributes(Map attributes) { this.attributes = attributes; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java index 74c4c30aa5..5b236e4b84 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java @@ -9,7 +9,6 @@ import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; @@ -28,7 +27,7 @@ public class TopologyTemplate extends ToscaElement{ private Map inputs; private Map instInputs; private Map heatParameters; - private Map instAttributes; + private Map instAttributes; private Map instProperties; private Map groups; private Map instGroups; @@ -64,10 +63,10 @@ public class TopologyTemplate extends ToscaElement{ public void setHeatParameters(Map heatParameters) { this.heatParameters = heatParameters; } - public Map getInstAttributes() { + public Map getInstAttributes() { return instAttributes; } - public void setInstAttributes(Map instAttributes) { + public void setInstAttributes(Map instAttributes) { this.instAttributes = instAttributes; } public Map getInstProperties() { @@ -163,7 +162,7 @@ public class TopologyTemplate extends ToscaElement{ getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances().put(componentInstance.getUniqueId(), componentInstance); } /** - * Returns map of component inctances from composition + * Returns map of component instances from composition * @return */ public Map getComponentInstances() { 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 55853479d2..a3cb41f1c0 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 @@ -30,6 +30,7 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.slf4j.Logger; @@ -45,7 +46,7 @@ public class ArtifactsOperations extends BaseOperation { public Either addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) { - Either status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactInfo.getUniqueId(), instanceId); + Either status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactInfo.getUniqueId(), instanceId, false); if (status.isRight()) { log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value()); @@ -64,7 +65,7 @@ public class ArtifactsOperations extends BaseOperation { public Either updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { - Either status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId); + Either status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true); if (status.isRight()) { log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value()); @@ -211,11 +212,14 @@ public class ArtifactsOperations extends BaseOperation { } - public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) { + public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate) { if (oldVesrion == null || oldVesrion.isEmpty()) oldVesrion = "0"; String currentChecksum = artifactData.getArtifactChecksum(); + if(isUpdate && artifactData.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())){ + generateUUID(artifactData, oldVesrion); + } if (oldChecksum == null || oldChecksum.isEmpty()) { if (currentChecksum != null) { generateUUID(artifactData, oldVesrion); @@ -259,7 +263,7 @@ public class ArtifactsOperations extends BaseOperation { } Map artifacts = artifactsEither.left().value(); - List envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); + List envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId()!= null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); if (envList != null && !envList.isEmpty()) { envList.forEach(a -> { a.setGeneratedFromId(newArtifactId); @@ -409,7 +413,7 @@ public class ArtifactsOperations extends BaseOperation { } - public Either updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId) { + public Either updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate) { Either res = null; ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo); ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); @@ -479,7 +483,7 @@ public class ArtifactsOperations extends BaseOperation { } } } - updateUUID(artifactToUpdate, oldChecksum, oldVersion); + updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate); if (artifactInfo.getPayloadData() == null) { if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) { 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 629d9ecdd4..ed14bac8bb 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 @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; @@ -23,17 +24,24 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -948,7 +956,7 @@ public abstract class BaseOperation { if (result == null) { currMap.put(key, toscaDataBlock); } - return null; + return result; } @SuppressWarnings("unchecked") @@ -1248,9 +1256,9 @@ public abstract class BaseOperation { return result; } - private StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map mergedToscaDataMap) { + protected StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map mergedToscaDataMap) { - StorageOperationStatus result = null; + StorageOperationStatus result = StorageOperationStatus.OK; if (toscaDataVertex == null) { Either createRes = assosiateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap); @@ -1312,5 +1320,41 @@ public abstract class BaseOperation { // } // return StorageOperationStatus.OK; // } + + protected GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDataDefinition group, ComponentInstanceDataDefinition componentInstance) { + + String componentInstanceName = componentInstance.getName(); + Long creationDate = System.currentTimeMillis(); + GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition(); + String groupUid = group.getUniqueId(); + + groupInstance.setGroupUid(groupUid); + groupInstance.setType(group.getType()); + groupInstance.setCustomizationUUID(generateCustomizationUUID()); + groupInstance.setCreationTime(creationDate); + groupInstance.setModificationTime(creationDate); + groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName())); + groupInstance.setGroupName(group.getName()); + groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName())); + groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName())); + groupInstance.setArtifacts(group.getArtifacts()); + groupInstance.setArtifactsUuid(group.getArtifactsUuid()); + groupInstance.setProperties(group.getProperties()); + groupInstance.setInvariantUUID(group.getInvariantUUID()); + groupInstance.setGroupUUID(group.getGroupUUID()); + groupInstance.setVersion(group.getVersion()); + + return groupInstance; + } + + protected String buildGroupInstanceName(String instanceName, String groupName) { + int groupNameIndex = groupName.indexOf(".."); + //turn group name from VFName..heatfile..module-n to VFiName..heatfile..module-n + return ValidationUtils.normaliseComponentName(instanceName) + groupName.substring(groupNameIndex); + } + + protected String generateCustomizationUUID() { + return UUID.randomUUID().toString(); + } } 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 a20f85ad7b..58ee914046 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 @@ -30,11 +30,11 @@ import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; @@ -343,7 +343,7 @@ public class NodeTemplateOperation extends BaseOperation { CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()); if (composition != null) { Map relations = composition.getRelations(); - if (relations != null) { + if (MapUtils.isNotEmpty(relations)) { Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); if (capResult.isRight()) { return capResult.right().value(); @@ -397,6 +397,11 @@ public class NodeTemplateOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); return status; } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); @@ -414,12 +419,12 @@ public class NodeTemplateOperation extends BaseOperation { } status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); return status; } status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); return status; } status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId); @@ -433,6 +438,11 @@ public class NodeTemplateOperation extends BaseOperation { return status; } status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); return status; @@ -440,7 +450,7 @@ public class NodeTemplateOperation extends BaseOperation { return StorageOperationStatus.OK; } - private Either addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { + protected Either addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { Either result; StorageOperationStatus status; @@ -561,7 +571,7 @@ public class NodeTemplateOperation extends BaseOperation { return status; } - MapAttributesDataDefinition instAttributes = new MapAttributesDataDefinition(originNodeType.getAttributes()); + MapPropertiesDataDefinition instAttributes = new MapPropertiesDataDefinition(originNodeType.getAttributes()); status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId()); @@ -775,7 +785,7 @@ public class NodeTemplateOperation extends BaseOperation { return null; } - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groups, Map> groupInstancesArtifacts) { + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List groups, Map> groupInstancesArtifacts) { StorageOperationStatus result = null; Map groupInstanceToCreate = new HashMap<>(); @@ -783,7 +793,7 @@ public class NodeTemplateOperation extends BaseOperation { for (Map.Entry> groupArtifacts : groupInstancesArtifacts.entrySet()) { Optional groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst(); if (groupOptional.isPresent()) { - GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(groupOptional.get(), componentInstance); + GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition)groupOptional.get(), (ComponentInstanceDataDefinition)componentInstance); groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(a -> a.getUniqueId()).collect(Collectors.toList())); groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(a -> a.getArtifactUUID()).collect(Collectors.toList())); groupInstanceToCreate.put(groupInstance.getName(), groupInstance); @@ -799,31 +809,7 @@ public class NodeTemplateOperation extends BaseOperation { return result; } - private GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDefinition group, ComponentInstance componentInstance) { - - String componentInstanceName = componentInstance.getName(); - Long creationDate = System.currentTimeMillis(); - GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition(); - String groupUid = group.getUniqueId(); - - groupInstance.setGroupUid(groupUid); - groupInstance.setType(group.getType()); - groupInstance.setCustomizationUUID(generateCustomizationUUID()); - groupInstance.setCreationTime(creationDate); - groupInstance.setModificationTime(creationDate); - groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName())); - groupInstance.setGroupName(groupInstance.getName()); - groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName())); - groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName())); - groupInstance.setArtifacts(group.getArtifacts()); - groupInstance.setArtifactsUuid(group.getArtifactsUuid()); - groupInstance.setProperties(group.getProperties()); - groupInstance.setInvariantUUID(group.getInvariantUUID()); - groupInstance.setGroupUUID(group.getGroupUUID()); - groupInstance.setVersion(group.getVersion()); - - return groupInstance; - } + private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) { String ciOriginComponentUid = resourceInstance.getComponentUid(); @@ -892,15 +878,9 @@ public class NodeTemplateOperation extends BaseOperation { return isUniqueName; } - private String buildGroupInstanceName(String instanceName, String groupName) { - int groupNameIndex = groupName.indexOf(".."); - //turn group name from VFName..heatfile..module-n to VFiName..heatfile..module-n - return ValidationUtils.normaliseComponentName(instanceName) + groupName.substring(groupNameIndex); - } + - private String generateCustomizationUUID() { - return UUID.randomUUID().toString(); - } + private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) { return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber); @@ -1525,7 +1505,7 @@ public class NodeTemplateOperation extends BaseOperation { RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair); - relationshipTypeData.setType(type); + relationshipTypeData.setType(requirementForRelation.getRelationship()); return Either.left(relationshipTypeData); } @@ -1716,7 +1696,8 @@ public class NodeTemplateOperation extends BaseOperation { pathKeys.add(componentInstanceId); return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); } - + + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { List pathKeys = new ArrayList<>(); pathKeys.add(componentInstanceId); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java index 1eb67e5c51..985870b5e3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java @@ -2,16 +2,17 @@ package org.openecomp.sdc.be.model.jsontitan.operations; import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; @@ -20,11 +21,11 @@ import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; @@ -32,6 +33,22 @@ 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.AttributeData; +import org.openecomp.sdc.be.resources.data.AttributeValueData; +import org.openecomp.sdc.be.resources.data.CapabilityData; +import org.openecomp.sdc.be.resources.data.CapabilityTypeData; +import org.openecomp.sdc.be.resources.data.DataTypeData; +import org.openecomp.sdc.be.resources.data.GroupData; +import org.openecomp.sdc.be.resources.data.GroupTypeData; +import org.openecomp.sdc.be.resources.data.InputValueData; +import org.openecomp.sdc.be.resources.data.InputsData; +import org.openecomp.sdc.be.resources.data.PolicyTypeData; +import org.openecomp.sdc.be.resources.data.PropertyData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; +import org.openecomp.sdc.be.resources.data.RelationshipInstData; +import org.openecomp.sdc.be.resources.data.RelationshipTypeData; +import org.openecomp.sdc.be.resources.data.RequirementData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.slf4j.Logger; @@ -44,6 +61,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.function.Function; import java.util.regex.Pattern; @org.springframework.stereotype.Component("node-type-operation") @@ -152,7 +170,7 @@ public class NodeTypeOperation extends ToscaElementOperation { private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, InterfaceDataDefinition.class, EdgeLabelEnum.INTERFACE_ARTIFACTS); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.INTERFACE_ARTIFACTS); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } @@ -377,7 +395,7 @@ public class NodeTypeOperation extends ToscaElementOperation { } private TitanOperationStatus setResourceAttributesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES); + Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES); if (result.isLeft()) { toscaElement.setAttributes(result.left().value()); } else { @@ -413,7 +431,7 @@ public class NodeTypeOperation extends ToscaElementOperation { private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, AdditionalInfoParameterDataDefinition.class, EdgeLabelEnum.ADDITIONAL_INFORMATION); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ADDITIONAL_INFORMATION); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } @@ -421,7 +439,7 @@ public class NodeTypeOperation extends ToscaElementOperation { Map addInformation = nodeType.getAdditionalInformation(); if (addInformation != null) { - addInformationAll.putAll(addInformation); + ToscaDataDefinition.mergeDataMaps(addInformationAll, addInformation); } if (!addInformationAll.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll); @@ -434,7 +452,7 @@ public class NodeTypeOperation extends ToscaElementOperation { private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, ListCapabilityDataDefinition.class, EdgeLabelEnum.CAPABILITIES); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } @@ -452,9 +470,7 @@ public class NodeTypeOperation extends ToscaElementOperation { }); }); - for (Entry entry : capabilties.entrySet()) { - capabiltiesAll.merge(entry.getKey(), entry.getValue(), (list1, list2) -> list1.mergeListItemsByName(list2)); - } + ToscaDataDefinition.mergeDataMaps(capabiltiesAll, capabilties); } if (!capabiltiesAll.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILTIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll); @@ -467,7 +483,7 @@ public class NodeTypeOperation extends ToscaElementOperation { private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, ListRequirementDataDefinition.class, EdgeLabelEnum.REQUIREMENTS); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.REQUIREMENTS); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } @@ -485,9 +501,8 @@ public class NodeTypeOperation extends ToscaElementOperation { }); }); - for (Entry entry : requirements.entrySet()) { - requirementsAll.merge(entry.getKey(), entry.getValue(), (list1, list2) -> list1.mergeListItemsByName(list2)); - } + ToscaDataDefinition.mergeDataMaps(requirementsAll, requirements); + } if (!requirementsAll.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll); @@ -500,19 +515,19 @@ public class NodeTypeOperation extends ToscaElementOperation { private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, AttributeDataDefinition.class, EdgeLabelEnum.ATTRIBUTES); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ATTRIBUTES); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } - Map attributesAll = dataFromDerived.left().value(); + Map attributesAll = dataFromDerived.left().value(); - Map attributes = nodeType.getAttributes(); + Map attributes = nodeType.getAttributes(); if (attributes != null) { attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { String uid = UniqueIdBuilder.buildAttributeUid(nodeTypeVertex.getUniqueId(), p.getName()); p.setUniqueId(uid); }); - attributesAll.putAll(attributes); + ToscaDataDefinition.mergeDataMaps(attributesAll, attributes); } if (!attributesAll.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll); @@ -526,7 +541,7 @@ public class NodeTypeOperation extends ToscaElementOperation { // TODO get from derived private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { // // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, MapPropertiesDataDefinition.class, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES_PROPERTIES); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } @@ -542,9 +557,9 @@ public class NodeTypeOperation extends ToscaElementOperation { }); } }); - propertiesAll.putAll(capabiltiesProps); + ToscaDataDefinition.mergeDataMaps(propertiesAll, capabiltiesProps); } - if (propertiesAll != null) { + if (!propertiesAll.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); @@ -657,7 +672,7 @@ public class NodeTypeOperation extends ToscaElementOperation { protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) { NodeType nodeType = (NodeType) toscaElementToUpdate; - List derivedResources = null; + List derivedResources = new ArrayList<>(); List derivedFromResources = nodeType.getDerivedFrom(); @@ -691,7 +706,8 @@ public class NodeTypeOperation extends ToscaElementOperation { } // must be only one GraphVertex newDerived = getParentResources.left().value().get(0); - StorageOperationStatus updateStatus = updateDataFromNewDerived(newDerived, nodeTypeV); + derivedResources.add(newDerived); + StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType)toscaElementToUpdate); if (updateStatus != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerived.getUniqueId(), updateStatus); return updateStatus; @@ -704,44 +720,70 @@ public class NodeTypeOperation extends ToscaElementOperation { return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteError); } - titanDao.createEdge(nodeTypeV, newDerived, EdgeLabelEnum.DERIVED_FROM, null); + titanDao.createEdge(nodeTypeV, newDerived, EdgeLabelEnum.DERIVED_FROM, new HashMap<>()); } } return StorageOperationStatus.OK; } + + private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate, List newDerived) { + + switch (edgeLabel) { + case CAPABILITIES: + return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived); + case REQUIREMENTS: + return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived); + case PROPERTIES: + return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); + case ATTRIBUTES: + return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived); + case ADDITIONAL_INFORMATION: + return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived); + case CAPABILITIES_PROPERTIES: + return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); + default: + return StorageOperationStatus.OK; + } + + } - private StorageOperationStatus updateDataFromNewDerived(GraphVertex newDerived, GraphVertex nodeTypeV) { - StorageOperationStatus status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.CAPABILITIES, CapabilityDataDefinition.class); + private StorageOperationStatus updateDataFromNewDerived(List newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate) { + + StorageOperationStatus status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.CAPABILITIES, nodeToUpdate); if (status != StorageOperationStatus.OK) { return status; } - status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.REQUIREMENTS, RequirementDefinition.class); + + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.REQUIREMENTS, nodeToUpdate); if (status != StorageOperationStatus.OK) { return status; } - status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.PROPERTIES, PropertyDataDefinition.class); + + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.PROPERTIES, nodeToUpdate); if (status != StorageOperationStatus.OK) { return status; } - status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ATTRIBUTES, AttributeDataDefinition.class); + + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ATTRIBUTES, nodeToUpdate); + if (status != StorageOperationStatus.OK) { + return status; + } + + status = updateDataByType(newDerived, nodeTypeV,EdgeLabelEnum.CAPABILITIES_PROPERTIES, nodeToUpdate); if (status != StorageOperationStatus.OK) { return status; } - // TODO - // status = updateDataByType(newDerived, nodeTypeV, - // EdgeLabelEnum.CAPABILITIES_PROPERTIES, capa); - // if ( status != StorageOperationStatus.OK){ - // return status; - // } - status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ADDITIONAL_INFORMATION, AdditionalInfoParameterDataDefinition.class); + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ADDITIONAL_INFORMATION, nodeToUpdate); return status; } - private StorageOperationStatus updateDataByType(GraphVertex newDerived, GraphVertex nodeTypeV, EdgeLabelEnum label, Class clazz) { + private StorageOperationStatus updateDataByType(List newDerivedList, GraphVertex nodeTypeV, EdgeLabelEnum label, NodeType nodeElement) { log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label); Either dataFromGraph = getDataVertex(nodeTypeV, label); if (dataFromGraph.isRight()) { + if (TitanOperationStatus.NOT_FOUND == dataFromGraph.right().value()) + return associateDerivedDataByType(label, nodeTypeV, nodeElement, newDerivedList); return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); } GraphVertex dataV = dataFromGraph.left().value(); @@ -749,16 +791,19 @@ public class NodeTypeOperation extends ToscaElementOperation { Map mapFromGraph = (Map) dataV.getJson(); mapFromGraph.entrySet().removeIf(e -> e.getValue().getOwnerId() != null); - List derivedList = new ArrayList<>(); - derivedList.add(newDerived); - - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedList, clazz, EdgeLabelEnum.CAPABILITIES); + + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(newDerivedList, label); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } - Map capabiltiesAll = dataFromDerived.left().value(); - capabiltiesAll.putAll(mapFromGraph); - + Map dataFromDerivedAll = dataFromDerived.left().value(); + + Either, String> merged = ToscaDataDefinition.mergeDataMaps(dataFromDerivedAll, mapFromGraph); + if(merged.isRight()){ + log.debug("property {} cannot be overriden", merged.right().value()); + return StorageOperationStatus.INVALID_PROPERTY; + } + dataV.setJson(dataFromDerivedAll); Either updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label); if (updateDataV.isRight()) { return DaoStatusConverter.convertTitanStatusToStorageStatus(updateDataV.right().value()); 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 62d04edf4f..0389c2739a 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 @@ -6,6 +6,8 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.Map.Entry; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -20,7 +22,6 @@ import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; @@ -31,6 +32,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DistributionStatusEnum; import org.openecomp.sdc.be.model.User; @@ -117,6 +119,12 @@ public class TopologyTemplateOperation extends ToscaElementOperation { result = Either.right(associateInstInputs); return result; } + StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstProperties != StorageOperationStatus.OK) { + result = Either.right(associateInstInputs); + return result; + } + StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate); if (associateRequirements != StorageOperationStatus.OK) { result = Either.right(associateRequirements); @@ -251,6 +259,12 @@ public class TopologyTemplateOperation extends ToscaElementOperation { Map instProps = topologyTemplate.getInstInputs(); return associateInstInputsToComponent(nodeTypeVertex, instProps); } + + public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map instGroups = topologyTemplate.getInstGroups(); + return associateInstGroupsToComponent(nodeTypeVertex, instGroups); + } + public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map instProps) { if (instProps != null && !instProps.isEmpty()) { @@ -271,21 +285,18 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } return StorageOperationStatus.OK; } - - public StorageOperationStatus addInstInputsToComponent(GraphVertex nodeTypeVertex, Map instInputs) { - - if (instInputs != null && !instInputs.isEmpty()) { - instInputs.entrySet().forEach(i -> { - StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, i.getValue(), i.getKey()); - if (status != StorageOperationStatus.OK) { - return; - } - }); + + public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map instGroups) { + if (instGroups != null && !instGroups.isEmpty()) { + Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } } - return StorageOperationStatus.OK; } + public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map instInputs) { if (instInputs != null && !instInputs.isEmpty()) { @@ -361,11 +372,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map instAttr = topologyTemplate.getInstAttributes(); + Map instAttr = topologyTemplate.getInstAttributes(); return associateInstAttributeToComponent(nodeTypeVertex, instAttr); } - public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map instAttr) { + public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map instAttr) { if (instAttr != null && !instAttr.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr); if (assosiateElementToData.isRight()) { @@ -953,6 +964,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { if (instances != null && instances.getComponentInstances() != null && !instances.getComponentInstances().isEmpty()) { for (ComponentInstanceDataDefinition ci : instances.getComponentInstances().values()) { if (ci.getComponentUid().equals(elementV.getUniqueId())) { + log.debug("The resource {} failed to delete cause in use as component instance UniqueID = {} in {} with UniqueID {}", elementV.getUniqueId(), ci.getUniqueId(), containerV.getType(), containerV.getUniqueId()); return true; } } 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 be995089a9..1397e81f9c 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 @@ -1,10 +1,13 @@ package org.openecomp.sdc.be.model.jsontitan.operations; +import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; 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; @@ -14,7 +17,9 @@ 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; @@ -24,20 +29,39 @@ import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.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; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.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; @@ -46,20 +70,19 @@ import fj.data.Either; @org.springframework.stereotype.Component("tosca-element-lifecycle-operation") /** - * Allows to perform lifecycle operations: - * checkin, checkout, submit for testing, start certification and certification process - * for tosca element + * Allows to perform lifecycle operations: checkin, checkout, submit for testing, start certification and certification process for tosca element */ public class ToscaElementLifecycleOperation extends BaseOperation { - + private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. "; public static final String VERSION_DELIMETER = "."; public static final String VERSION_DELIMETER_REGEXP = "\\."; - + private static Logger logger = LoggerFactory.getLogger(ToscaElementLifecycleOperation.class.getName()); /** - * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in" + * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in" + * * @param currState * @param toscaElementId * @param modifierId @@ -72,109 +95,115 @@ public class ToscaElementLifecycleOperation extends BaseOperation { Map vertices = null; ToscaElementOperation operation; try { - Either, TitanOperationStatus> getVerticesRes = - titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId)); - if(getVerticesRes.isRight()){ + Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); } else { vertices = getVerticesRes.left().value(); updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); } - if(updateResult.isLeft()) { + if (updateResult.isLeft()) { ComponentParametersView componentParametersView = buildComponentParametersViewAfterCheckin(); operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel()); result = operation.getToscaElement(updateResult.left().value().getUniqueId(), componentParametersView); - if(result.isRight()){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value()); + if (result.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value()); } } else { result = Either.right(updateResult.right().value()); } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage()); } return result; } + /** * Returns vertex presenting owner of tosca element specified by uniqueId + * * @param toscaElement * @return */ public Either getToscaElementOwner(String toscaElementId) { - Either result = null; + Either result = null; GraphVertex toscaElement = null; Either getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); - if(getToscaElementRes.isRight()){ + if (getToscaElementRes.isRight()) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); } - if(result == null){ + if (result == null) { toscaElement = getToscaElementRes.left().value(); Iterator vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); - if(vertices == null || !vertices.hasNext()){ + if (vertices == null || !vertices.hasNext()) { result = Either.right(StorageOperationStatus.NOT_FOUND); } else { result = Either.left(convertToUser(vertices.next())); } } - return result; - } + return result; + } + /** * Returns vertex presenting owner of tosca element specified by uniqueId + * * @param toscaElement * @return */ public Either getToscaElementOwner(GraphVertex toscaElement) { - Either result = null; + Either result = null; Iterator vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); - if(vertices == null || !vertices.hasNext()){ + if (vertices == null || !vertices.hasNext()) { result = Either.right(StorageOperationStatus.NOT_FOUND); } else { result = Either.left(convertToUser(vertices.next())); } - return result; - } + return result; + } -/** - * Performs checkout of a tosca element - * @param toscaElementId - * @param modifierId - * @param ownerId - * @param currState - * @return - */ + /** + * Performs checkout of a tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @param currState + * @return + */ public Either checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) { Either result = null; Map vertices = null; - try{ - Either, TitanOperationStatus> getVerticesRes = - titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId)); - if(getVerticesRes.isRight()){ + try { + Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(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){ + if (result == null) { vertices = getVerticesRes.left().value(); // update previous component if not certified StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId)); - if(status != StorageOperationStatus.OK){ + if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status); result = Either.right(status); } } - if(result == null){ + if (result == null) { result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId)); if (result.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value()); } + } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage()); } return result; } + /** * Performs undo checkout for tosca element + * * @param toscaElementId * @return */ @@ -185,44 +214,45 @@ public class ToscaElementLifecycleOperation extends BaseOperation { ToscaElementOperation operation; try { getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata); - if(getToscaElementRes.isRight()){ + if (getToscaElementRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); } - if(result == null && hasPreviousVersion(getToscaElementRes.left().value())){ + if (result == null && hasPreviousVersion(getToscaElementRes.left().value())) { // find previous version nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if(nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", - getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); - result = Either.right(StorageOperationStatus.NOT_FOUND); + if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); + result = Either.right(StorageOperationStatus.NOT_FOUND); } - if(result == null){ + if (result == null) { StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex()); if (updateOldResourceResult != StorageOperationStatus.OK) { result = Either.right(updateOldResourceResult); } } } - if(result == null){ + if (result == null) { operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel()); result = operation.deleteToscaElement(getToscaElementRes.left().value()); } - } catch(Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); } - return result; + return result; } - + private boolean hasPreviousVersion(GraphVertex toscaElementVertex) { boolean hasPreviousVersion = true; String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION); - if(StringUtils.isEmpty(version) || version.equals("0.1")) + if (StringUtils.isEmpty(version) || version.equals("0.1")) hasPreviousVersion = false; return hasPreviousVersion; } + /** * Performs request certification for tosca element + * * @param toscaElementId * @param modifierId * @param ownerId @@ -235,49 +265,48 @@ public class ToscaElementLifecycleOperation extends BaseOperation { GraphVertex modifier = null; GraphVertex owner; try { - Either, TitanOperationStatus> getVerticesRes = - titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if(getVerticesRes.isRight()){ + Either, 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){ + if (result == null) { toscaElement = getVerticesRes.left().value().get(toscaElementId); modifier = getVerticesRes.left().value().get(modifierId); owner = getVerticesRes.left().value().get(ownerId); - + StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner); - if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations on certification request for tosca element {}. Status is {}. ", - toscaElement.getUniqueId(), status); + 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){ + if (result == null) { LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; - + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + 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){ + 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()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); } return result; } - + /** * Starts certification of tosca element + * * @param toscaElementId * @param modifierId * @param ownerId @@ -290,45 +319,43 @@ public class ToscaElementLifecycleOperation extends BaseOperation { GraphVertex modifier = null; GraphVertex owner; try { - Either, TitanOperationStatus> getVerticesRes = - titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if(getVerticesRes.isRight()){ + Either, 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){ + if (result == null) { toscaElement = getVerticesRes.left().value().get(toscaElementId); modifier = getVerticesRes.left().value().get(modifierId); owner = getVerticesRes.left().value().get(ownerId); - + StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner); - if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations during certification of tosca element {}. Status is {}. ", - toscaElement.getUniqueId(), status); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); } } - if(result == null){ + if (result == null) { LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; - + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); result = Either.right(resultUpdate.right().value()); } } - if(result == null){ + if (result == null) { ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); result = operation.getToscaElement(toscaElement.getUniqueId()); } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); } return result; } - + public Either certifyToscaElement(String toscaElementId, String modifierId, String ownerId) { Either result = null; Either cloneRes = null; @@ -339,53 +366,52 @@ public class ToscaElementLifecycleOperation extends BaseOperation { StorageOperationStatus status; try { - Either, TitanOperationStatus> getVerticesRes = - titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if(getVerticesRes.isRight()){ + Either, 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){ + if (result == null) { toscaElement = getVerticesRes.left().value().get(toscaElementId); modifier = getVerticesRes.left().value().get(modifierId); majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION)); status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion); - if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", - toscaElement.getUniqueId(), status); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status); } } - if(result == null){ + if (result == null) { cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion); if (cloneRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. "); result = Either.right(cloneRes.right().value()); } } - if(result == null){ + if (result == null) { certifiedToscaElement = cloneRes.left().value(); status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); - if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations of newest certified tosca element {}. Status is {}. ", - certifiedToscaElement.getUniqueId(), status); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); } } - if(result == null){ - return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId()); + if (result == null) { + return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId()); } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage()); } return result; } -/** - * Deletes (marks as deleted) all tosca elements according received name and uuid - * @param vertexType - * @param componentType - * @param componentName - * @param uuid - * @return - */ + + /** + * Deletes (marks as deleted) all tosca elements according received name and uuid + * + * @param vertexType + * @param componentType + * @param componentName + * @param uuid + * @return + */ public Either deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) { Either result = null; @@ -395,29 +421,31 @@ public class ToscaElementLifecycleOperation extends BaseOperation { Map properties = new EnumMap<>(GraphPropertyEnum.class); properties.put(GraphPropertyEnum.UUID, uuid); properties.put(GraphPropertyEnum.NAME, componentName); - Either, TitanOperationStatus> getToscaElementsRes= titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); + Either, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); if (getToscaElementsRes.isRight()) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); } - if(result == null){ + if (result == null) { result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); } - if(result == null){ + if (result == null) { result = Either.left(true); } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); } return result; } -/** - * Performs cancelation or failure of certification for received tosca element - * @param toscaElementId - * @param modifierId - * @param ownerId - * @param nextState - * @return - */ + + /** + * Performs cancelation or failure of certification for received tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @param nextState + * @return + */ public Either cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) { Either result = null; StorageOperationStatus status; @@ -425,60 +453,56 @@ public class ToscaElementLifecycleOperation extends BaseOperation { GraphVertex toscaElement = null; GraphVertex modifier = null; try { - Either, TitanOperationStatus> getVerticesRes = - titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if(getVerticesRes.isRight()){ + Either, 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){ + if (result == null) { toscaElement = getVerticesRes.left().value().get(toscaElementId); modifier = getVerticesRes.left().value().get(modifierId); operation = getToscaElementOperation(toscaElement.getLabel()); toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId()); toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - + Either updateVertexRes = titanDao.updateVertex(toscaElement); - if(updateVertexRes.isRight()){ + if (updateVertexRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value())); } } - if(result == null){ - // cancel certification process + if (result == null) { + // cancel certification process status = handleRelationsUponCancelCertification(toscaElement, nextState); - if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations upon cancel certification {}. Status is {}. ", - toscaElement.getUniqueId(), status); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status); } } - if(result == null){ - // fail certification + if (result == null) { + // fail certification status = handleRelationsUponFailCertification(toscaElement, nextState); - if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to handle relations upon fail certification {}. Status is {}. ", - toscaElement.getUniqueId(), status); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status); } - } + } if (result == null) { result = operation.getToscaElement(toscaElementId); } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during cancel or fail certification of tosca element {}. {}. ", - toscaElementId, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage()); } return result; } - + public Either findUser(String userId) { return findUserVertex(userId); } - - private Either markToscaElementsAsDeleted(ToscaElementOperation operation, List toscaElements) { + + private Either markToscaElementsAsDeleted(ToscaElementOperation operation, List toscaElements) { Either result = Either.left(true); for (GraphVertex resourceToDelete : toscaElements) { - if(!((String)resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())){ + if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) { Either deleteElementRes = operation.markComponentToDelete(resourceToDelete); if (deleteElementRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value()); @@ -489,7 +513,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } return result; } - private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { StorageOperationStatus result = null; @@ -498,46 +521,53 @@ public class ToscaElementLifecycleOperation extends BaseOperation { // add rfc relation to preserve follower information // get user of certification request certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name()); - if(certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()){ + if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); result = StorageOperationStatus.NOT_FOUND; } + if (result == null) { + TitanOperationStatus createVersionEdgeStatus = titanDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); + if (createVersionEdgeStatus != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(),certifiedToscaElement.getUniqueId(), createVersionEdgeStatus); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(createVersionEdgeStatus); + } + } if(result == null){ - - while(certReqUserEdgeIter.hasNext()){ + + while (certReqUserEdgeIter.hasNext()) { Edge edge = certReqUserEdgeIter.next(); - if(((String)titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name()) ){ + if (((String) titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) { foundEdge = edge; break; } - + } - if(foundEdge == null){ + if (foundEdge == null) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); result = StorageOperationStatus.NOT_FOUND; } } - if(result == null){ + if (result == null) { TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge); if (createEdgeRes != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes); result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } return result; } - + private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { StorageOperationStatus result = null; TitanOperationStatus status = null; Edge originEdge; Vertex user = null; - if(nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN){ - // fail certification - // delete relation CERTIFICATION_IN_PROGRESS + if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) { + // fail certification + // delete relation CERTIFICATION_IN_PROGRESS Map properties = new EnumMap<>(GraphPropertyEnum.class); properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); @@ -547,29 +577,29 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status); result = StorageOperationStatus.INCONSISTENCY; } - if(result == null){ - // delete relation READY_FOR_CERTIFICATION + if (result == null) { + // delete relation READY_FOR_CERTIFICATION properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if(deleteResult.isRight()){ + if (deleteResult.isRight()) { status = deleteResult.right().value(); CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status); result = StorageOperationStatus.INCONSISTENCY; } } - if(result == null){ - // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) + if (result == null) { + // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if(deleteResult.isRight()){ + if (deleteResult.isRight()) { status = deleteResult.right().value(); CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status); result = StorageOperationStatus.INCONSISTENCY; } } - if(result == null){ + if (result == null) { // create new STATE relation NOT_CERTIFIED_CHECKIN - originEdge = deleteResult.left().value(); + originEdge = deleteResult.left().value(); user = originEdge.outVertex(); status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); if (status != TitanOperationStatus.OK) { @@ -577,17 +607,17 @@ public class ToscaElementLifecycleOperation extends BaseOperation { result = StorageOperationStatus.INCONSISTENCY; } } - if(result == null){ - // delete relation LAST_MODIFIER (in order to change tester to designer) + if (result == null) { + // delete relation LAST_MODIFIER (in order to change tester to designer) deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); result = StorageOperationStatus.INCONSISTENCY; } } - if(result == null){ + if (result == null) { // create new LAST_MODIFIER relation - originEdge = deleteResult.left().value(); + originEdge = deleteResult.left().value(); status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); @@ -595,7 +625,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } return result; @@ -604,27 +634,27 @@ public class ToscaElementLifecycleOperation extends BaseOperation { private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { StorageOperationStatus result = null; Edge originEdge; - if(nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION){ - // delete relation CERTIFICATION_IN_PROGRESS + if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { + // delete relation CERTIFICATION_IN_PROGRESS Map properties = new EnumMap<>(GraphPropertyEnum.class); properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); Either deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - + if (deleteResult.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value()); result = StorageOperationStatus.INCONSISTENCY; } - if(result == null){ + if (result == null) { // delete relation READY_FOR_CERTIFICATION (LAST_STATE) properties.put(GraphPropertyEnum.STATE, nextState); deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - + if (deleteResult.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", deleteResult.right().value()); result = StorageOperationStatus.INCONSISTENCY; } } - if(result == null){ + if (result == null) { // create relation READY_FOR_CERTIFICATION (STATE) originEdge = deleteResult.left().value(); TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); @@ -633,43 +663,43 @@ public class ToscaElementLifecycleOperation extends BaseOperation { result = StorageOperationStatus.INCONSISTENCY; } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } } return result; } - private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { + private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { StorageOperationStatus result = null; if (majorVersion > 0) { Either findRes = findLastCertifiedToscaElementVertex(toscaElement); - if(findRes.isRight()){ + if (findRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value()); result = findRes.right().value(); } - if(result == null){ + if (result == null) { Vertex lastCertifiedVertex = findRes.left().value(); Map properties = new EnumMap<>(GraphPropertyEnum.class); properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties); if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status); result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } return result; } - + private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { TitanOperationStatus status; StorageOperationStatus result = null; - - if (((String)toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + + if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { // remove CHECKOUT relation Either deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE); if (deleteRes.isRight()) { @@ -677,7 +707,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status); result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } - if(result == null){ + if (result == null) { // create CHECKIN relation Map properties = new EnumMap<>(EdgePropertyEnum.class); properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); @@ -693,54 +723,54 @@ public class ToscaElementLifecycleOperation extends BaseOperation { result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } } - if(result == null){ + if (result == null) { // create RFC relation Map properties = new EnumMap<>(EdgePropertyEnum.class); properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } return result; } - - private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + + private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { StorageOperationStatus result = null; TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); if (status != TitanOperationStatus.OK) { result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } - if(result == null){ + if (result == null) { Map properties = new EnumMap<>(EdgePropertyEnum.class); properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"failed to create edge. Status is {}", status); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } return result; } - + private Either findLastCertifiedToscaElementVertex(GraphVertex toscaElement) { return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex()); } private Either findLastCertifiedToscaElementVertexRecursively(Vertex vertex) { - if(isCertifiedVersion((String)vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())){ + if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) { return Either.left(vertex); } Iterator edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if(!edgeIter.hasNext()){ + if (!edgeIter.hasNext()) { return Either.right(StorageOperationStatus.NOT_FOUND); } return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex()); @@ -748,131 +778,350 @@ public class ToscaElementLifecycleOperation extends BaseOperation { private boolean isCertifiedVersion(String version) { String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); - if(Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0){ + if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) { return true; } return false; } private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) { - + StorageOperationStatus result = StorageOperationStatus.OK; String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value(); if (!previousVersion.endsWith(".0")) { - try{ - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", - previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); - + try { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); + Map propertiesToUpdate = new HashMap<>(); propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); - Map jsonMetadataMap = - JsonParserUtils.parseToJson((String)previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); + Map jsonMetadataMap = JsonParserUtils.parseToJson((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap)); - + titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate); - + Iterator edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name()); - if(!edgesIter.hasNext()){ + if (!edgesIter.hasNext()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); result = StorageOperationStatus.NOT_FOUND; } else { Edge lastStateEdge = edgesIter.next(); Vertex lastModifier = lastStateEdge.outVertex(); - TitanOperationStatus replaceRes = - titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); + TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); if (replaceRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); - result = StorageOperationStatus.INCONSISTENCY; + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); + result = StorageOperationStatus.INCONSISTENCY; if (replaceRes != TitanOperationStatus.INVALID_ID) { result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes); } } } - } catch (Exception e){ + } catch (Exception e) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage()); } } return result; } + private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) { StorageOperationStatus result = null; String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID); String toscaElementId = toscaElementVertex.getUniqueId(); - if(!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())){ + if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); Either updateVertexRes = titanDao.updateVertex(toscaElementVertex); if (updateVertexRes.isRight()) { TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); } Either deleteEdgeRes = null; - if(result == null){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE,"Going to replace edge with label {} to label {} from {} to {}. ", - EdgeLabelEnum.STATE , EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId); - + if (result == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId); + deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); - if(deleteEdgeRes.isRight()){ + if (deleteEdgeRes.isRight()) { TitanOperationStatus titanStatus = deleteEdgeRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to delete edge with label {} from {} to {}. Status is {} ", - EdgeLabelEnum.STATE , EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus); if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) { result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } else{ + } else { result = StorageOperationStatus.INCONSISTENCY; } } } - if(result == null){ + if (result == null) { TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value()); - if(createEdgeRes != TitanOperationStatus.OK){ + if (createEdgeRes != TitanOperationStatus.OK) { result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); } } } - if(result == null){ + if (result == null) { result = StorageOperationStatus.OK; } return result; } - - private Either cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { - + + private Either cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { + Either result = null; Either cloneResult = null; ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); // check if component with the next version doesn't exist. Iterator nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); - if(nextVersionComponentIter != null && nextVersionComponentIter.hasNext()){ + if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) { String fetchedVersion = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.VERSION.getProperty()).value(); String fetchedName = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ", toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion); result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); } - if(result == null){ + if (result == null) { cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex); - if(cloneResult.isRight()){ + if (cloneResult.isRight()) { result = Either.right(cloneResult.right().value()); } } + GraphVertex clonedVertex = null; if (result == null) { + clonedVertex = cloneResult.left().value(); TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), - cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, + toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if(result == null){ + if (result == null) { result = operation.getToscaElement(cloneResult.left().value().getUniqueId()); + if (result.isRight()) { + return result; + } + + ToscaElement toscaElement = result.left().value(); + if (toscaElement.getToscaType() == ToscaElementTypeEnum.TopologyTemplate) { + result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement); + } + } + return result; + } + + private Either handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either result, ToscaElementOperation operation, GraphVertex clonedVertex, + ToscaElement toscaElement) { + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + Map instInputs = topologyTemplate.getInstInputs(); + Map instGroups = topologyTemplate.getInstGroups(); + Map instArtifactsMap = topologyTemplate.getInstanceArtifacts(); + Map origCompMap = new HashMap<>(); + if (instInputs == null) { + instInputs = new HashMap<>(); + } + if (instGroups == null) { + instGroups = new HashMap<>(); + } + if (instArtifactsMap == null) { + instArtifactsMap = new HashMap<>(); + } + Map instancesMap = topologyTemplate.getComponentInstances(); + boolean isAddInstGroup = instGroups == null || instGroups.isEmpty(); + boolean needUpdateComposition = false; + + if (instancesMap != null && !instancesMap.isEmpty()) { + for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType()); + if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { + collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex); + } + needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap); + if(needUpdateComposition){ + instancesMap.put(vfInst.getUniqueId(), vfInst); + } + } + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition); + if (!instInputs.isEmpty()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size()); + GraphVertex toscaDataVertex = null; + Either instInpVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson); + if (instInpVertexEither.isLeft()) { + toscaDataVertex = instInpVertexEither.left().value(); + } + + StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status); + result = Either.right(status); + return result; + } + + } + if (!instGroups.isEmpty()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size()); + GraphVertex toscaDataVertex = null; + Either instGrVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson); + if (instGrVertexEither.isLeft()) { + toscaDataVertex = instGrVertexEither.left().value(); + } + + StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status); + result = Either.right(status); + return result; + } + + } + if (needUpdateComposition) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before update Instances "); + Map jsonComposition = (Map) clonedVertex.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + compositionDataDefinition.setComponentInstances(instancesMap); + Either updateElement = titanDao.updateVertex(clonedVertex); + if (updateElement.isRight()) { + TitanOperationStatus status = updateElement.right().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + } + + result = operation.getToscaElement(clonedVertex.getUniqueId()); + + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId()); } return result; } + private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { + if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) { + String ciUid = vfInst.getUniqueId(); + String origCompUid = vfInst.getComponentUid(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType()); + ToscaElement origComp = null; + if (!origCompMap.containsKey(origCompUid)) { + Either origCompEither; + if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { + origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); + }else{ + origCompEither = nodeTypeOperation.getToscaElement(origCompUid); + } + if (origCompEither.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); + return false; + } + origComp = origCompEither.left().value(); + origCompMap.put(origCompUid, origComp); + } else { + origComp = origCompMap.get(origCompUid); + } + String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName); + vfInst.setToscaComponentName(toscaName); + return true; + } + return false; + } + + private void collectInstanceInputAndGroups(Map instInputs, Map instGroups, Map instArtifactsMap, Map origCompMap, + boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) { + String ciUid = vfInst.getUniqueId(); + String origCompUid = vfInst.getComponentUid(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid); + TopologyTemplate origComp = null; + if (!origCompMap.containsKey(origCompUid)) { + Either origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); + if (origCompEither.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); + return; + } + origComp = (TopologyTemplate) origCompEither.left().value(); + origCompMap.put(origCompUid, origComp); + } else { + origComp = (TopologyTemplate) origCompMap.get(origCompUid); + } + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId()); + + Map origInputs = origComp.getInputs(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size()); + if (origInputs != null) { + if (!instInputs.containsKey(ciUid)) { + MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs); + instInputs.put(ciUid, instProperties); + } else { + + MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid); + Map instProp = instInputMap.getMapToscaDataDefinition(); + origInputs.forEach((propName, propMap) -> { + if (!instProp.containsKey(propName)) { + instProp.put(propName, propMap); + } + }); + } + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid)); + } + + if (isAddInstGroup) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before create group instance. "); + List filteredGroups = null; + + + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) { + filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + } + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + if (CollectionUtils.isNotEmpty(filteredGroups)) { + MapArtifactDataDefinition instArifacts = null; + if(!instArtifactsMap.containsKey(ciUid)){ + + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "istance artifacts not found "); + + Map deploymentArtifacts = origComp.getDeploymentArtifacts(); + + + instArifacts = new MapArtifactDataDefinition(deploymentArtifacts); + addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid); + + instArtifactsMap.put(ciUid, instArifacts); + + }else{ + instArifacts = instArtifactsMap.get(ciUid); + } + + if(instArifacts != null){ + Map instDeplArtifMap = instArifacts.getMapToscaDataDefinition(); + + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size()); + Map groupInstanceToCreate = new HashMap<>(); + for(GroupDataDefinition group:filteredGroups){ + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName()); + GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst); + List artifactsUid = new ArrayList<>(); + List artifactsId = new ArrayList<>(); + for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) { + //CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", artifact.getA); + Optional op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + artifactsUid.add(artifact.getArtifactUUID()); + artifactsId.add(artifact.getUniqueId()); + + } + } + groupInstance.setGroupInstanceArtifacts(artifactsId); + groupInstance.setGroupInstanceArtifactsUuid(artifactsUid); + groupInstanceToCreate.put(groupInstance.getName(), groupInstance); + } + if (MapUtils.isNotEmpty(groupInstanceToCreate)) { + instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate)); + + } + } + } + } + } + private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { GraphVertex nextVersionToscaElementVertex = new GraphVertex(); String uniqueId = UniqueIdBuilder.buildComponentUniqueId(); @@ -881,11 +1130,11 @@ public class ToscaElementLifecycleOperation extends BaseOperation { nextVersionToscaElementVertex.setUniqueId(uniqueId); nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); - + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION)); - if(isFirstCheckoutAfterCertification(nextVersion)){ + if (isFirstCheckoutAfterCertification(nextVersion)) { nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID()); } nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion); @@ -895,7 +1144,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue()); } - if(!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())){ + if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { nextVersionToscaElementVertex.setMetadataJson(new HashMap(toscaElementVertex.getMetadataJson())); nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); } @@ -904,73 +1153,70 @@ public class ToscaElementLifecycleOperation extends BaseOperation { nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime); nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); - if(toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); } - - if(!MapUtils.isEmpty(toscaElementVertex.getJson())){ + + if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { nextVersionToscaElementVertex.setJson(new HashMap(toscaElementVertex.getJson())); } return nextVersionToscaElementVertex; } - + private Either cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { Either result; Either, StorageOperationStatus> deleteResult = null; GraphVertex clonedToscaElement = null; result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex); - if(result.isRight()){ + if (result.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value()); - } - else{ + } else { clonedToscaElement = result.left().value(); deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex); - if(deleteResult.isRight()){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", - toscaElementVertex.getUniqueId(), deleteResult.right().value()); + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value()); result = Either.right(deleteResult.right().value()); } } - if(result.isLeft()){ + if (result.isLeft()) { result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion); } return result; } - + private Either handlePreviousVersionRelation(GraphVertex clonedToscaElement, List deletedVersions, Integer majorVersion) { Either result = null; Vertex previousCertifiedToscaElement = null; - if(majorVersion > 0){ - List firstMinorVersionVertex = deletedVersions.stream() - .filter(gv->getMinorVersion((String)gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList()); - - if(CollectionUtils.isEmpty(firstMinorVersionVertex)){ + if (majorVersion > 0) { + List firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(firstMinorVersionVertex)) { result = Either.right(StorageOperationStatus.NOT_FOUND); } else { previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0)); - if(previousCertifiedToscaElement == null){ + if (previousCertifiedToscaElement == null) { result = Either.right(StorageOperationStatus.NOT_FOUND); } } - if(result == null){ + if (result == null) { TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - clonedToscaElement.getUniqueId(), status); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, + previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } } - if(result == null){ + if (result == null) { result = Either.left(clonedToscaElement); } return result; } private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) { - + Iterator edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if(edges.hasNext()){ + if (edges.hasNext()) { return edges.next().outVertex(); } return null; @@ -978,7 +1224,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { private Either, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) { Either, StorageOperationStatus> result = null; - + ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); List previosVersions = null; Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID); @@ -987,28 +1233,28 @@ public class ToscaElementLifecycleOperation extends BaseOperation { Map properties = new HashMap<>(); properties.put(GraphPropertyEnum.UUID, uuid); properties.put(GraphPropertyEnum.NAME, componentName); - Either, TitanOperationStatus> getToscaElementsRes= titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata); + Either, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata); if (getToscaElementsRes.isRight()) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); } - if(result == null){ + if (result == null) { previosVersions = getToscaElementsRes.left().value(); Either deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); - if(deleteResult.isRight()){ + if (deleteResult.isRight()) { result = Either.right(deleteResult.right().value()); } } - if(result == null){ + if (result == null) { result = Either.left(previosVersions); } - } catch (Exception e){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); } return result; } private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { - + GraphVertex nextVersionToscaElementVertex = new GraphVertex(); String uniqueId = IdBuilderUtils.generateUniqueId(); Map metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); @@ -1016,7 +1262,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { nextVersionToscaElementVertex.setUniqueId(uniqueId); nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); - + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMETER + "0"); @@ -1026,20 +1272,20 @@ public class ToscaElementLifecycleOperation extends BaseOperation { nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null); nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); - + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) { nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue()); } - if(!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())){ + if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { nextVersionToscaElementVertex.setMetadataJson(new HashMap(toscaElementVertex.getMetadataJson())); nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); } - if(!MapUtils.isEmpty(toscaElementVertex.getJson())){ + if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { nextVersionToscaElementVertex.setJson(new HashMap(toscaElementVertex.getJson())); } return nextVersionToscaElementVertex; } - + private ComponentParametersView buildComponentParametersViewAfterCheckin() { ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); @@ -1050,141 +1296,141 @@ public class ToscaElementLifecycleOperation extends BaseOperation { private Either checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) { Either updateRelationsRes; Either result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex); - if(result.isLeft()) { + if (result.isLeft()) { toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex); } - if(result.isLeft()){ + if (result.isLeft()) { updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex); - if(updateRelationsRes.isRight()){ + if (updateRelationsRes.isRight()) { result = Either.right(updateRelationsRes.right().value()); } } return result; } - private Either updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex){ - + private Either updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) { + Either result; - + Either updateVertexRes = titanDao.updateVertex(toscaElementVertex); if (updateVertexRes.isRight()) { TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus)); } else { result = Either.left(updateVertexRes.left().value()); } return result; } - + private Either changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { Either result = null; LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}"; - + if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { - //In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN" + // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN" Map vertexProperties = new HashMap<>(); vertexProperties.put(GraphPropertyEnum.STATE, nextState); - Either deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); + Either deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"failed to update last state relation"); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to update last state relation"); result = Either.right(StorageOperationStatus.INCONSISTENCY); } } - if(result == null) { - //Remove CHECKOUT relation + if (result == null) { + // Remove CHECKOUT relation Either deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); if (deleteEdgeResult.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value())); } } - if(result == null) { - //Create CHECKIN relation + if (result == null) { + // Create CHECKIN relation Map edgeProperties = new HashMap<>(); edgeProperties.put(EdgePropertyEnum.STATE, nextState); TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties); if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); } } - if(result == null) { + if (result == null) { result = Either.left(toscaElementVertex); } return result; } - private Either updateLastModifierEdge( GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { + private Either updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { Either result = null; - if(!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))){ + if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) { Either deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER); - if(deleteEdgeRes.isRight()){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + if (deleteEdgeRes.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value())); } - if(result == null) { + if (result == null) { TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - - if(createEdgeRes != TitanOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,"Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + + if (createEdgeRes != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); - } else{ + } else { result = Either.left(modifierVertex); } } - } else{ + } else { result = Either.left(ownerVertex); } return result; } - private Map> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) { - Map> verticesToGetParameters = new HashMap<>(); + private Map> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) { + Map> verticesToGetParameters = new HashMap<>(); verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); return verticesToGetParameters; } - - private Map> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) { - Map> verticesToGetParameters = new HashMap<>(); + + private Map> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) { + Map> verticesToGetParameters = new HashMap<>(); verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); return verticesToGetParameters; } - - private Map> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) { - Map> verticesToGetParameters = new HashMap<>(); + + private Map> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) { + Map> verticesToGetParameters = new HashMap<>(); verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID,JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); return verticesToGetParameters; } - + private String getNextVersion(String currVersion) { String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP); Integer minorVersion = Integer.parseInt(versionParts[1]) + 1; return versionParts[0] + VERSION_DELIMETER + minorVersion; } - + private Integer getMinorVersion(String version) { String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); return Integer.parseInt(versionParts[1]); } - + private Integer getMajorVersion(String version) { String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); return Integer.parseInt(versionParts[0]); } - + private boolean isFirstCheckoutAfterCertification(String version) { - if(Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[1]) == 1){ + if (Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[1]) == 1) { return true; } return false; 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 95e65e1e82..699d9e0e9d 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 @@ -130,7 +130,7 @@ public abstract class ToscaElementOperation extends BaseOperation { Either result = null; GraphVertex createdToscaElementVertex = null; TitanOperationStatus status; - + Either createNextVersionRes = titanDao.createVertex(nextToscaElement); if (createNextVersionRes.isRight()) { status = createNextVersionRes.right().value(); @@ -182,7 +182,7 @@ public abstract class ToscaElementOperation extends BaseOperation { } } } - + if (result == null) { result = Either.left(createdToscaElementVertex); } else { @@ -203,6 +203,7 @@ public abstract class ToscaElementOperation extends BaseOperation { toscaElement.setLastUpdaterFullName(buildFullName(userV)); return TitanOperationStatus.OK; } + public String buildFullName(GraphVertex userV) { String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); @@ -217,6 +218,7 @@ public abstract class ToscaElementOperation extends BaseOperation { } return fullName; } + protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { Either parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); if (parentVertex.isRight()) { @@ -227,7 +229,7 @@ public abstract class ToscaElementOperation extends BaseOperation { String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); toscaElement.setCreatorUserId(creatorUserId); toscaElement.setCreatorFullName(buildFullName(userV)); - + return TitanOperationStatus.OK; } @@ -318,7 +320,7 @@ public abstract class ToscaElementOperation extends BaseOperation { toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); - + result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); if (!result.equals(TitanOperationStatus.OK)) { @@ -472,9 +474,9 @@ public abstract class ToscaElementOperation extends BaseOperation { return StorageOperationStatus.OK; } - private StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List derivedResources) { + protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List derivedResources) { // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, PropertyDataDefinition.class, EdgeLabelEnum.PROPERTIES); + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } @@ -488,13 +490,12 @@ public abstract class ToscaElementOperation extends BaseOperation { p.setUniqueId(uid); }); - Either, String> eitherMerged = PropertyDataDefinition.mergeProperties(propertiesAll, properties, false); + Either, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties); if (eitherMerged.isRight()) { // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property log.debug("property {} cannot be overriden", eitherMerged.right().value()); return StorageOperationStatus.INVALID_PROPERTY; } - } if (!propertiesAll.isEmpty()) { Either assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); @@ -516,7 +517,7 @@ public abstract class ToscaElementOperation extends BaseOperation { return StorageOperationStatus.OK; } - protected Either, StorageOperationStatus> getDataFromDerived(List derivedResources, Class clazz, EdgeLabelEnum edge) { + protected Either, StorageOperationStatus> getDataFromDerived(List derivedResources, EdgeLabelEnum edge) { Map propertiesAll = new HashMap<>(); if (derivedResources != null && !derivedResources.isEmpty()) { @@ -575,10 +576,11 @@ public abstract class ToscaElementOperation extends BaseOperation { Map allVersion = new HashMap<>(); allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); + ArrayList allChildrenAndParants = new ArrayList(); Either childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); while (childResourceRes.isLeft()) { GraphVertex child = childResourceRes.left().value(); - allVersion.put((String) child.getMetadataProperty(GraphPropertyEnum.VERSION), child.getUniqueId()); + allChildrenAndParants.add(child); childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); } TitanOperationStatus operationStatus = childResourceRes.right().value(); @@ -589,13 +591,18 @@ public abstract class ToscaElementOperation extends BaseOperation { Either parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); while (parentResourceRes.isLeft()) { GraphVertex parent = parentResourceRes.left().value(); - allVersion.put((String) parent.getMetadataProperty(GraphPropertyEnum.VERSION), parent.getUniqueId()); + allChildrenAndParants.add(parent); parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); } operationStatus = parentResourceRes.right().value(); if (operationStatus != TitanOperationStatus.NOT_FOUND) { return operationStatus; } else { + allChildrenAndParants.stream().filter(vertex -> { + Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + return (isDeleted == null || isDeleted == false); + }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); + toscaElement.setAllVersions(allVersion); return TitanOperationStatus.OK; } @@ -1047,98 +1054,113 @@ public abstract class ToscaElementOperation extends BaseOperation { return status; } - - public Either, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType , ToscaElementTypeEnum toscaElement) { - Either, TitanOperationStatus> listOfHighestAndAllCertifiedComponents = this.getListOfHighestAndAllCertifiedComponents(componentType , toscaElement); - if (listOfHighestAndAllCertifiedComponents.isRight() && listOfHighestAndAllCertifiedComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestAndAllCertifiedComponents.right().value())); + public Either, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement, boolean isHighestVersions) { + Either, TitanOperationStatus> listOfComponents; + if (isHighestVersions) { + listOfComponents = getListOfHighestComponents(componentType, toscaElement); + } else { + listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, toscaElement); + } + if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value())); } - List highestAndAllCertified = listOfHighestAndAllCertifiedComponents.left().value(); List result = new ArrayList<>(); - if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) { - for (GraphVertex vertexComponent : highestAndAllCertified) { - Either component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); - if (component.isRight()) { - log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); - return Either.right(component.right().value()); - } else { - result.add(component.left().value()); + if (listOfComponents.isLeft()) { + List highestAndAllCertified = listOfComponents.left().value(); + if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) { + for (GraphVertex vertexComponent : highestAndAllCertified) { + Either component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); + if (component.isRight()) { + log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); + return Either.right(component.right().value()); + } else { + result.add(component.left().value()); + } } } } return Either.left(result); } - - -public Either, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType , ToscaElementTypeEnum toscaElement) { - long startFetchAllStates = System.currentTimeMillis(); - Map propertiesToMatchCertified = 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); - } - Map propertiesHasNotToMatchCertified = new HashMap<>(); - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); - - - Either, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement) , propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); - if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(certifiedNodes.right().value()); - } - - Map 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); - } + private Either, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) { + Map propertiesToMatch = 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); + } - Map propertiesHasNotToMatchHighest = new HashMap<>(); - propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true); - propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - - Either, 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()); - } - - long endFetchAllStates = System.currentTimeMillis(); - - - List 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 (highestNode.isRight()){ - nonCertifiedSize = 0; - } else { - nonCertifiedSize = highestNode.left().value().size(); + Map propertiesHasNotToMatch = new HashMap<>(); + propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + return titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata); } - - - 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); -} + public Either, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) { + long startFetchAllStates = System.currentTimeMillis(); + Map propertiesToMatchCertified = 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); + } + + Map propertiesHasNotToMatchCertified = new HashMap<>(); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + + Either, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchCertified, propertiesHasNotToMatchCertified, + JsonParseFlagEnum.ParseMetadata); + if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(certifiedNodes.right().value()); + } + + Map 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 propertiesHasNotToMatchHighest = new HashMap<>(); + propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + Either, 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()); + } + + long endFetchAllStates = System.currentTimeMillis(); + + List 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 (highestNode.isRight()) { + nonCertifiedSize = 0; + } else { + nonCertifiedSize = highestNode.left().value().size(); + } + + 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); + } protected Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { 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 9c7f108a05..458bbbe226 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 @@ -24,14 +24,12 @@ 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.AttributeDataDefinition; 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.MapAttributesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; @@ -44,7 +42,6 @@ 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.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -100,12 +97,14 @@ public class ToscaOperationFacade { return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); } + public Either getToscaFullElement(String componentId) { ComponentParametersView filters = new ComponentParametersView(); filters.setIgnoreCapabiltyProperties(false); - + return getToscaElement(componentId, filters); } + public Either getToscaElement(String componentId, ComponentParametersView filters) { Either getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); @@ -657,25 +656,25 @@ public class ToscaOperationFacade { return getToscaElementByOperation(getResourceRes.left().value().get(0)); } - public Either, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType) { + public Either, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, boolean isHighestVersions) { List components = new ArrayList<>(); Either, StorageOperationStatus> catalogDataResult; List toscaElements; switch (componentType) { case RESOURCE: - catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE ,ToscaElementTypeEnum.NodeType); + catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.NodeType, isHighestVersions); if (catalogDataResult.isRight()) { return Either.right(catalogDataResult.right().value()); } toscaElements = catalogDataResult.left().value(); - Either, StorageOperationStatus> resourceCatalogData = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE ,ToscaElementTypeEnum.TopologyTemplate); + Either, 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); + catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions); if (catalogDataResult.isRight()) { return Either.right(catalogDataResult.right().value()); } @@ -1034,37 +1033,34 @@ public class ToscaOperationFacade { } - public Either>, StorageOperationStatus> addComponentInstanceInputsToComponent(Map> instProperties, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } + public Either>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map> instProperties) { - GraphVertex vertex = getVertexEither.left().value(); - Map instPropsMap = new HashMap<>(); + StorageOperationStatus status = StorageOperationStatus.OK; if (instProperties != null) { - MapPropertiesDataDefinition propertiesMap; for (Entry> 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); + List props = entry.getValue(); + String componentInstanseId = entry.getKey(); + if (props != null && !props.isEmpty()) { + for (ComponentInstanceInput property : props) { + List componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId); + Optional 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); + } + } + } } } - - StorageOperationStatus status = topologyTemplateOperation.addInstInputsToComponent(vertex, instPropsMap); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - return Either.left(instProperties); - } - return Either.right(status); - + return Either.left(instProperties); } public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map> instProperties, String componentId) { @@ -1148,7 +1144,7 @@ public class ToscaOperationFacade { } - public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, String componentId) { + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, String componentId) { Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { @@ -1158,13 +1154,13 @@ public class ToscaOperationFacade { } GraphVertex vertex = getVertexEither.left().value(); - Map instAttr = new HashMap<>(); + Map instAttr = new HashMap<>(); if (instArttributes != null) { - MapAttributesDataDefinition attributesMap; - for (Entry> entry : instArttributes.entrySet()) { - attributesMap = new MapAttributesDataDefinition(); - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new AttributeDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + MapPropertiesDataDefinition attributesMap; + for (Entry> 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); } } @@ -1184,9 +1180,10 @@ public class ToscaOperationFacade { GraphVertex vertex = getVertexEither.left().value(); Map calcRequirements = new HashMap<>(); - + Map calcCapabilty = new HashMap<>(); - Map calculatedCapabilitiesProperties = new HashMap<>();; + Map calculatedCapabilitiesProperties = new HashMap<>(); + ; if (instCapabilties != null) { for (Entry>> entry : instCapabilties.entrySet()) { @@ -1200,7 +1197,7 @@ public class ToscaOperationFacade { 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); } @@ -1226,8 +1223,7 @@ public class ToscaOperationFacade { return status; } - private Either, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, - VertexTypeEnum vertexType) { + private Either, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { Map hasProps = new EnumMap<>(GraphPropertyEnum.class); Map hasNotProps = new EnumMap<>(GraphPropertyEnum.class); @@ -1242,33 +1238,35 @@ public class ToscaOperationFacade { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); } } else { - List nonAbstractLatestComponents = new ArrayList<>(); - ComponentParametersView params = new ComponentParametersView(true); - params.setIgnoreAllVersions(false); - for (GraphVertex vertexComponent : getRes.left().value()) { - Either componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); - if (componentRes.isRight()) { - log.debug("Failed to fetch 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); - } - } + List nonAbstractLatestComponents = new ArrayList<>(); + ComponentParametersView params = new ComponentParametersView(true); + params.setIgnoreAllVersions(false); + for (GraphVertex vertexComponent : getRes.left().value()) { + Either componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); + if (componentRes.isRight()) { + log.debug("Failed to fetch 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 getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag) { + public Either getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { Either result; Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); hasProperties.put(GraphPropertyEnum.UUID, componentUuid); - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (isHighest != null) { + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); + } Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); @@ -1499,6 +1497,7 @@ public class ToscaOperationFacade { 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) { @@ -1533,21 +1532,21 @@ public class ToscaOperationFacade { return Either.left(result); } - + public Either, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); return getComponentListByUuid(componentUuid, propertiesToMatch); } - + public Either, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { - + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if(additionalPropertiesToMatch != null){ + + if (additionalPropertiesToMatch != null) { propertiesToMatch.putAll(additionalPropertiesToMatch); } - + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); @@ -1781,14 +1780,14 @@ public class ToscaOperationFacade { } public Either updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { - Either updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); - if ( updateDistributionStatus.isRight() ){ - return Either.right(updateDistributionStatus.right().value()); - } - GraphVertex serviceV = updateDistributionStatus.left().value(); - service.setDistributionStatus(distributionStatus); - service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); - return Either.left(service); + Either updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); + if (updateDistributionStatus.isRight()) { + return Either.right(updateDistributionStatus.right().value()); + } + GraphVertex serviceV = updateDistributionStatus.left().value(); + service.setDistributionStatus(distributionStatus); + service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + return Either.left(service); } public Either updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { @@ -1821,25 +1820,25 @@ public class ToscaOperationFacade { public TitanDao getTitanDao() { return titanDao; } - + public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set distStatus) { Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - + return getServicesWithDistStatus(distStatus, propertiesToMatch); } - + public Either, StorageOperationStatus> getServicesWithDistStatus(Set distStatus, Map additionalPropertiesToMatch) { List servicesAll = new ArrayList<>(); Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if(additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { + + if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { propertiesToMatch.putAll(additionalPropertiesToMatch); } - + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); @@ -1848,10 +1847,9 @@ public class ToscaOperationFacade { for (DistributionStatusEnum state : distStatus) { propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); Either, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - if ( fetchServicesByCriteria.isRight() ){ + if (fetchServicesByCriteria.isRight()) { return fetchServicesByCriteria; - } - else{ + } else { servicesAll = fetchServicesByCriteria.left().value(); } } @@ -1861,6 +1859,27 @@ public class ToscaOperationFacade { } } + // private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { + // Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + // if (getRes.isRight()) { + // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { + // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); + // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + // } + // } else { + // for (GraphVertex vertex : getRes.left().value()) { + // Either getServiceRes = 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, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); if (getRes.isRight()) { @@ -1870,12 +1889,14 @@ public class ToscaOperationFacade { } } else { for (GraphVertex vertex : getRes.left().value()) { - Either getServiceRes = getToscaElementByOperation(vertex); + // Either getServiceRes = getToscaElementByOperation(vertex); + Either getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); + if (getServiceRes.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); return Either.right(getServiceRes.right().value()); } else { - servicesAll.add((Service) getToscaElementByOperation(vertex).left().value()); + servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); } } } @@ -1942,7 +1963,7 @@ public class ToscaOperationFacade { 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); } @@ -1980,16 +2001,16 @@ public class ToscaOperationFacade { } return result; } - - public Either addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) { + + public Either addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { Either getUpdatedComponentRes = null; - Either result = null; - if(newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()){ + Either result = null; + if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); newAttributeDef.setUniqueId(attUniqueId); } - + StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); @@ -2005,7 +2026,7 @@ public class ToscaOperationFacade { } } if (result == null) { - Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); if (newAttribute.isPresent()) { result = Either.left(newAttribute.get()); } else { @@ -2015,11 +2036,11 @@ public class ToscaOperationFacade { } return result; } - - public Either updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) { + + public Either updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { Either getUpdatedComponentRes = null; - Either result = null; + Either result = null; StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); @@ -2035,7 +2056,7 @@ public class ToscaOperationFacade { } } if (result == null) { - Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); if (newProperty.isPresent()) { result = Either.left(newProperty.get()); } else { @@ -2045,7 +2066,7 @@ public class ToscaOperationFacade { } return result; } - + public Either updateInputOfComponent(Component component, InputDefinition newInputDefinition) { Either getUpdatedComponentRes = null; @@ -2103,7 +2124,7 @@ public class ToscaOperationFacade { 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); } 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 07845c8ea5..e6f9ff6f93 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 @@ -21,11 +21,9 @@ import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; 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.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DistributionStatusEnum; @@ -168,15 +166,15 @@ public class ModelConverter { } private static void convertAttributes(NodeType nodeType, Resource resource) { - Map attributes = nodeType.getAttributes(); + Map attributes = nodeType.getAttributes(); if (attributes != null) { - List attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); + List attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); resource.setAttributes(attrs); } } - private static AttributeDefinition fromDataDefinition(String resourceId, AttributeDataDefinition dataDefinition) { - AttributeDefinition attributeDefinition = new AttributeDefinition(dataDefinition); + private static PropertyDefinition fromDataDefinition(String resourceId, PropertyDataDefinition dataDefinition) { + PropertyDefinition attributeDefinition = new PropertyDefinition(dataDefinition); attributeDefinition.setParentUniqueId(resourceId); return attributeDefinition; } @@ -684,9 +682,9 @@ public class ModelConverter { } private static void convertAttributes(Resource component, NodeType nodeType) { - List attributes = component.getAttributes(); + List attributes = component.getAttributes(); if (attributes != null) { - Map attrsByName = attributes.stream().map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, Function.identity())); + Map attrsByName = attributes.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); nodeType.setAttributes(attrsByName); } } @@ -997,11 +995,11 @@ public class ModelConverter { private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { if (topologyTemplate.getInstAttributes() != null) { - Map> attributes = new HashMap<>(); - for (Map.Entry entry : topologyTemplate.getInstAttributes().entrySet()) { + Map> attributes = new HashMap<>(); + for (Map.Entry entry : topologyTemplate.getInstAttributes().entrySet()) { if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { String key = entry.getKey(); - List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue()))) + List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) .collect(Collectors.toList()); attributes.put(key, componentInstanceAttributes); } @@ -1206,11 +1204,11 @@ public class ModelConverter { if (component.getComponentInstancesAttributes() != null) { topologyTemplate.setInstAttributes(new HashMap<>()); - MapAttributesDataDefinition attributesMap; - for (Entry> entry : component.getComponentInstancesAttributes().entrySet()) { - attributesMap = new MapAttributesDataDefinition(); + MapPropertiesDataDefinition attributesMap; + for (Entry> entry : component.getComponentInstancesAttributes().entrySet()) { + attributesMap = new MapPropertiesDataDefinition(); - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new AttributeDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java index db2b988f5f..c5fc70eb38 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java @@ -25,10 +25,10 @@ import java.util.Map; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.resources.data.AttributeData; import org.openecomp.sdc.be.resources.data.AttributeValueData; @@ -39,23 +39,23 @@ import fj.data.Either; public interface IAttributeOperation { Either deleteAttribute(String attributeId); - TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map attributes, String resourceId, Map dataTypes); + TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map attributes, String resourceId, Map dataTypes); - Either, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance); + Either, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance); - TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List attributes); + TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List attributes); - Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId); + Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId); - TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List attributes); + TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List attributes); - Either addAttribute(AttributeDefinition attributeDefinition, String resourceId); + Either addAttribute(PropertyDefinition attributeDefinition, String resourceId); - Either addAttributeToGraph(AttributeDefinition attribute, String resourceId, Map dataTypes); + Either addAttributeToGraph(PropertyDefinition attribute, String resourceId, Map dataTypes); - AttributeDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId); + PropertyDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId); - Either updateAttribute(String attributeId, AttributeDefinition newAttDef, Map dataTypes); + Either updateAttribute(String attributeId, PropertyDefinition newAttDef, Map dataTypes); /** * Builds ComponentInstanceAttribute from AttributeValueData @@ -64,8 +64,8 @@ public interface IAttributeOperation { * @param resourceInstanceAttribute * @return */ - ComponentInstanceAttribute buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceAttribute resourceInstanceAttribute); + ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute); - TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, AttributeDefinition attribute, String resourceId, Map dataTypes); + TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, PropertyDefinition attribute, String resourceId, Map dataTypes); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java index 28e70ad127..f4cb13fa64 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java @@ -30,7 +30,6 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; @@ -196,7 +195,7 @@ public interface IComponentInstanceOperation { * * @param resourceInstanceId * @param index * @param inTransaction * @return **/ - public Either addAttributeValueToResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction); + public Either addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction); public Either updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction); @@ -208,9 +207,9 @@ public interface IComponentInstanceOperation { * @param inTransaction * @return */ - public Either updateAttributeValueInResourceInstance(ComponentInstanceAttribute attribute, String resourceInstanceId, boolean inTransaction); + public Either updateAttributeValueInResourceInstance(ComponentInstanceProperty attribute, String resourceInstanceId, boolean inTransaction); - public Either createOrUpdateAttributeOfResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId); + public Either createOrUpdateAttributeOfResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId); public Either addInputValueToResourceInstance(ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java index ed43b7ce1f..cab49fe47d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java @@ -24,6 +24,8 @@ import org.openecomp.sdc.be.resources.data.ConsumerData; import fj.data.Either; +import java.util.List; + public interface IConsumerOperation { /** @@ -95,4 +97,10 @@ public interface IConsumerOperation { */ Either getCredentials(String consumerName); + /** + * + * @return all consumers + */ + Either, StorageOperationStatus> getAll(); + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java index 01db3a5105..8d9994ba8a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java @@ -137,10 +137,5 @@ public interface IResourceOperation extends IComponentOperation { */ Either, StorageOperationStatus> getVFResources(); - /** - * - * @return all resources - */ - Either, StorageOperationStatus> getAll(); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java index 84413f7987..254432c682 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java @@ -50,7 +50,7 @@ public interface IUserAdminOperation { Either, ActionStatus> getAllUsers(); - public Either, StorageOperationStatus> getUserPandingTasksList(User user, Map properties); + public Either, StorageOperationStatus> getUserPendingTasksList(User user, Map properties); public Either, ActionStatus> getUserDataWithFunctionalMenu(String userId); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java index f82a2982b0..279aab667c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java @@ -35,12 +35,12 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -81,7 +81,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO * @param attributeDefinition * @return */ - private Either addAttributeToNodeType(AttributeDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) { + private Either addAttributeToNodeType(PropertyDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) { String attUniqueId = UniqueIdBuilder.buildAttributeUid(nodeUniqueId, attributeDefinition.getName()); Supplier dataBuilder = () -> buildAttributeData(attributeDefinition, attUniqueId); Supplier defNameGenerator = () -> "Attribute : " + attributeDefinition.getName(); @@ -90,7 +90,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } - private TitanOperationStatus addAttributeToNodeType(TitanVertex metadataVertex, AttributeDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) { + private TitanOperationStatus addAttributeToNodeType(TitanVertex metadataVertex, PropertyDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) { String attUniqueId = UniqueIdBuilder.buildAttributeUid(nodeUniqueId, attributeDefinition.getName()); Supplier dataBuilder = () -> buildAttributeData(attributeDefinition, attUniqueId); Supplier defNameGenerator = () -> "Attribute : " + attributeDefinition.getName(); @@ -99,7 +99,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } - private AttributeData buildAttributeData(AttributeDefinition attributeDefinition, String attUniqueId) { + private AttributeData buildAttributeData(PropertyDefinition attributeDefinition, String attUniqueId) { attributeDefinition.setUniqueId(attUniqueId); return new AttributeData(attributeDefinition); } @@ -115,14 +115,14 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { + public Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { Wrapper errorWrapper; - List attributes = new ArrayList<>(); + List attributes = new ArrayList<>(); TitanOperationStatus findAllResourceAttribues = findNodeNonInheretedAttribues(uniqueId, NodeTypeEnum.Resource, attributes); errorWrapper = (findAllResourceAttribues != TitanOperationStatus.OK) ? new Wrapper<>(findAllResourceAttribues) : new Wrapper<>(); if (errorWrapper.isEmpty()) { - for (AttributeDefinition attDef : attributes) { + for (PropertyDefinition attDef : attributes) { log.debug("Before deleting attribute from graph {}", attDef.getUniqueId()); Either deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attDef.getUniqueId(), AttributeData.class); if (deleteNode.isRight()) { @@ -133,7 +133,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } if (errorWrapper.isEmpty()) { - Map attributesMap = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); + Map attributesMap = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); return Either.left(attributesMap); } else { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(errorWrapper.getInnerElement())); @@ -147,9 +147,9 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map attributes, String resourceId, Map dataTypes) { + public TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map attributes, String resourceId, Map dataTypes) { TitanOperationStatus titanStatus = TitanOperationStatus.OK; - for (AttributeDefinition attribute : attributes.values()) { + for (PropertyDefinition attribute : attributes.values()) { TitanOperationStatus eitherAddAttribute = addAttributeToGraphByVertex(metadataVertex, attribute, resourceId, dataTypes); if (!eitherAddAttribute.equals(TitanOperationStatus.OK)) { titanStatus = eitherAddAttribute; @@ -160,9 +160,9 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public Either, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance) { + public Either, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance) { - Either, TitanOperationStatus> result; + Either, TitanOperationStatus> result; Either>, TitanOperationStatus> attributeImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), compInstance.getUniqueId(), GraphEdgeLabels.ATTRIBUTE_VALUE, NodeTypeEnum.AttributeValue, AttributeValueData.class); @@ -185,31 +185,31 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO return result; } - private Either, TitanOperationStatus> mergeAttributesResults(Either, TitanOperationStatus> eitherAttributesThatDoesNotExistOnRI, - Either, TitanOperationStatus> eitherAttributesThatExistOnRI) { + private Either, TitanOperationStatus> mergeAttributesResults(Either, TitanOperationStatus> eitherAttributesThatDoesNotExistOnRI, + Either, TitanOperationStatus> eitherAttributesThatExistOnRI) { - Either, TitanOperationStatus> result; + Either, TitanOperationStatus> result; if (eitherAttributesThatExistOnRI.isRight()) { result = Either.right(eitherAttributesThatExistOnRI.right().value()); } else if (eitherAttributesThatDoesNotExistOnRI.isRight()) { result = Either.right(eitherAttributesThatDoesNotExistOnRI.right().value()); } else { - final List attributesThatExistOnRI = eitherAttributesThatExistOnRI.left().value(); - final List attributesThatDoesNotExistOnRI = eitherAttributesThatDoesNotExistOnRI.left().value(); + final List attributesThatExistOnRI = eitherAttributesThatExistOnRI.left().value(); + final List attributesThatDoesNotExistOnRI = eitherAttributesThatDoesNotExistOnRI.left().value(); Set attributesIdThatExistOnRI = attributesThatExistOnRI.stream().map(e -> e.getUniqueId()).collect(Collectors.toSet()); // Attributes From The Resource Without attributes that also exist // on the instance - Stream filterAttributesThatDoesNotExistOnRI = attributesThatDoesNotExistOnRI.stream().filter(e -> !attributesIdThatExistOnRI.contains(e.getUniqueId())); + Stream filterAttributesThatDoesNotExistOnRI = attributesThatDoesNotExistOnRI.stream().filter(e -> !attributesIdThatExistOnRI.contains(e.getUniqueId())); // Add Fields From Resource Attributes fillAttributeInfoFromResource(attributesThatExistOnRI, attributesThatDoesNotExistOnRI); // Adding the Attributes on the instance for the full list - List mergedList = Stream.concat(filterAttributesThatDoesNotExistOnRI, attributesThatExistOnRI.stream()).collect(Collectors.toList()); + List mergedList = Stream.concat(filterAttributesThatDoesNotExistOnRI, attributesThatExistOnRI.stream()).collect(Collectors.toList()); result = Either.left(mergedList); } return result; } - private void fillAttributeInfoFromResource(List attributesThatExistOnRI, List attributesThatDoesNotExistOnRI) { + private void fillAttributeInfoFromResource(List attributesThatExistOnRI, List attributesThatDoesNotExistOnRI) { attributesThatExistOnRI.stream() .forEach(e -> addAttributeInfo(e, // Finds the same attribute in the resource @@ -217,7 +217,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } - private void addAttributeInfo(ComponentInstanceAttribute attributeFromRI, ComponentInstanceAttribute attributeFromResource) { + private void addAttributeInfo(ComponentInstanceProperty attributeFromRI, ComponentInstanceProperty attributeFromResource) { attributeFromRI.setName(attributeFromResource.getName()); attributeFromRI.setDescription(attributeFromResource.getDescription()); attributeFromRI.setDefaultValue(attributeFromResource.getDefaultValue()); @@ -228,18 +228,18 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } } - private Either, TitanOperationStatus> getAttributesFromResource(ComponentInstance compInstance) { - Either, TitanOperationStatus> result; - List attributes = new ArrayList<>(); + private Either, TitanOperationStatus> getAttributesFromResource(ComponentInstance compInstance) { + Either, TitanOperationStatus> result; + List attributes = new ArrayList<>(); // Attributes does not exist on Ri - fetch them from resource TitanOperationStatus findAllResourceAttribues = findAllResourceAttributesRecursively(compInstance.getComponentUid(), attributes); if (findAllResourceAttribues != TitanOperationStatus.OK) { result = Either.right(findAllResourceAttribues); } else { - List buildAttInstanceFromResource = attributes.stream().map(attDef -> new ComponentInstanceAttribute(attDef, false, null)).collect(Collectors.toList()); + List buildAttInstanceFromResource = attributes.stream().map(attDef -> new ComponentInstanceProperty(false, attDef, null)).collect(Collectors.toList()); // Set Value to be default value in case it is empty - Consumer valueSetter = att -> { + Consumer valueSetter = att -> { if (StringUtils.isEmpty(att.getValue())) { att.setValue(att.getDefaultValue()); } @@ -251,9 +251,9 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO return result; } - private Either, TitanOperationStatus> convertToComponentInstanceAttribute(List> list) { - Either, TitanOperationStatus> result = null; - List componentInstanceAttribute = new ArrayList<>(); + private Either, TitanOperationStatus> convertToComponentInstanceAttribute(List> list) { + Either, TitanOperationStatus> result = null; + List componentInstanceAttribute = new ArrayList<>(); for (ImmutablePair attributeValue : list) { AttributeValueData attributeValueData = attributeValue.getLeft(); String attributeValueUid = attributeValueData.getUniqueId(); @@ -272,7 +272,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO ImmutablePair attributeDefPair = attributeDefRes.left().value(); String attributeUniqueId = attributeDefPair.left.getUniqueId(); - ComponentInstanceAttribute resourceInstanceAttribute = new ComponentInstanceAttribute(); + ComponentInstanceProperty resourceInstanceAttribute = new ComponentInstanceProperty(); // set attribute original unique id resourceInstanceAttribute.setUniqueId(attributeUniqueId); // set hidden @@ -302,14 +302,14 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO * @return */ @Override - public TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List attributes) { - final NodeElementFetcher singleNodeFetcher = (resourceIdParam, attributesParam) -> findNodeNonInheretedAttribues(resourceIdParam, NodeTypeEnum.Resource, attributesParam); + public TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List attributes) { + final NodeElementFetcher singleNodeFetcher = (resourceIdParam, attributesParam) -> findNodeNonInheretedAttribues(resourceIdParam, NodeTypeEnum.Resource, attributesParam); return findAllResourceElementsDefinitionRecursively(resourceId, attributes, singleNodeFetcher); } @Override - public TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List attributes) { + public TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List attributes) { Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ATTRIBUTE, NodeTypeEnum.Attribute, AttributeData.class); @@ -330,7 +330,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO log.debug("Attribute {} is associated to node {}", attributeName, uniqueId); AttributeData attributeData = immutablePair.getKey(); - AttributeDefinition attributeDefinition = this.convertAttributeDataToAttributeDefinition(attributeData, attributeName, uniqueId); + PropertyDefinition attributeDefinition = this.convertAttributeDataToAttributeDefinition(attributeData, attributeName, uniqueId); attributes.add(attributeDefinition); @@ -343,16 +343,16 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public AttributeDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId) { + public PropertyDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId) { log.debug("The object returned after create attribute is {}", attributeData); - AttributeDefinition attributeDefResult = new AttributeDefinition(attributeData.getAttributeDataDefinition()); + PropertyDefinition attributeDefResult = new PropertyDefinition(attributeData.getAttributeDataDefinition()); attributeDefResult.setName(attributeName); attributeDefResult.setParentUniqueId(resourceId); return attributeDefResult; } @Override - public Either addAttribute(AttributeDefinition attributeDefinition, String resourceId) { + public Either addAttribute(PropertyDefinition attributeDefinition, String resourceId) { Either eitherResult; Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); @@ -373,7 +373,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public Either updateAttribute(String attributeId, AttributeDefinition newAttDef, Map dataTypes) { + public Either updateAttribute(String attributeId, PropertyDefinition newAttDef, Map dataTypes) { StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, dataTypes); if (validateAndUpdateAttribute != StorageOperationStatus.OK) { @@ -388,7 +388,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO return Either.left(either.left().value()); } - private Either updateAttributeFromGraph(String attributeId, AttributeDefinition attributeDefenition) { + private Either updateAttributeFromGraph(String attributeId, PropertyDefinition attributeDefenition) { log.debug("Before updating attribute on graph {}", attributeId); // get the original property data @@ -398,12 +398,12 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO return Either.right(eitherAttribute.right().value()); } AttributeData orgAttributeData = eitherAttribute.left().value(); - AttributeDataDefinition orgAttributeDataDefinition = orgAttributeData.getAttributeDataDefinition(); + PropertyDataDefinition orgAttributeDataDefinition = orgAttributeData.getAttributeDataDefinition(); // create new property data to update AttributeData newAttributeData = new AttributeData(); newAttributeData.setAttributeDataDefinition(attributeDefenition); - AttributeDataDefinition newAttributeDataDefinition = newAttributeData.getAttributeDataDefinition(); + PropertyDataDefinition newAttributeDataDefinition = newAttributeData.getAttributeDataDefinition(); // update the original property data with new values if (!Objects.equals(orgAttributeDataDefinition.getDefaultValue(), newAttributeDataDefinition.getDefaultValue())) { @@ -424,17 +424,15 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public ComponentInstanceAttribute buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceAttribute resourceInstanceAttribute) { + public ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) { Boolean hidden = attributeValueData.isHidden(); String uid = attributeValueData.getUniqueId(); - ComponentInstanceAttribute instanceAttribute = new ComponentInstanceAttribute(resourceInstanceAttribute, hidden, uid); - - return instanceAttribute; + return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid); } @Override - public Either addAttributeToGraph(AttributeDefinition attribute, String resourceId, Map dataTypes) { + public Either addAttributeToGraph(PropertyDefinition attribute, String resourceId, Map dataTypes) { Either eitherResult; StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes); if (validateAndUpdateAttribute != StorageOperationStatus.OK) { @@ -448,7 +446,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO } @Override - public TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, AttributeDefinition attribute, String resourceId, Map dataTypes) { + public TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, PropertyDefinition attribute, String resourceId, Map dataTypes) { StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes); TitanOperationStatus result; if (validateAndUpdateAttribute != StorageOperationStatus.OK) { 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 c487b0ce71..43e4d0683b 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 @@ -66,7 +66,6 @@ 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.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; @@ -3893,7 +3892,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private StorageOperationStatus cloneResourceInstanceAttributeValues(ComponentInstance createdInstance, ComponentInstance resourceInstance) { Wrapper storageStatusWrapper = new Wrapper<>(); - Wrapper> compInstanceAttList = new Wrapper<>(); + Wrapper> compInstanceAttList = new Wrapper<>(); findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper); @@ -3902,7 +3901,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } if (storageStatusWrapper.isEmpty()) { - List attributesOnInstance = compInstanceAttList.getInnerElement(); + List attributesOnInstance = compInstanceAttList.getInnerElement(); for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) { cloneSingleAttributeOnResourceInstance(createdInstance, attributesOnInstance.get(i), storageStatusWrapper); } @@ -3915,7 +3914,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private StorageOperationStatus cloneResourceInstanceAttributeValues(TitanVertex createdInstanceVertex, ComponentInstance resourceInstance, String instanceId) { Wrapper storageStatusWrapper = new Wrapper<>(); - Wrapper> compInstanceAttList = new Wrapper<>(); + Wrapper> compInstanceAttList = new Wrapper<>(); findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper); @@ -3924,7 +3923,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } if (storageStatusWrapper.isEmpty()) { - List attributesOnInstance = compInstanceAttList.getInnerElement(); + List attributesOnInstance = compInstanceAttList.getInnerElement(); for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) { StorageOperationStatus result = cloneSingleAttributeOnResourceInstance(createdInstanceVertex, attributesOnInstance.get(i), instanceId); if (result != StorageOperationStatus.OK) { @@ -3945,9 +3944,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } } - private void findAllAttributesOfResourceInstance(ComponentInstance resourceInstance, Wrapper> compInstanceAttList, Wrapper storageStatusWrapper) { + private void findAllAttributesOfResourceInstance(ComponentInstance resourceInstance, Wrapper> compInstanceAttList, Wrapper storageStatusWrapper) { - Either, TitanOperationStatus> allAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance); + Either, TitanOperationStatus> allAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance); if (allAttributes.isRight()) { TitanOperationStatus status = allAttributes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { @@ -3960,7 +3959,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } } - private void cloneSingleAttributeOnResourceInstance(ComponentInstance createdInstance, ComponentInstanceAttribute attribute, Wrapper storageStatusWrapper) { + private void cloneSingleAttributeOnResourceInstance(ComponentInstance createdInstance, ComponentInstanceProperty attribute, Wrapper storageStatusWrapper) { // Only if valueUniqueId is not empty, then its belongs to the // instance if (attribute.getValueUniqueUid() != null) { @@ -3981,7 +3980,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - private StorageOperationStatus cloneSingleAttributeOnResourceInstance(TitanVertex createdInstanceVertex, ComponentInstanceAttribute attribute, String instanceId) { + private StorageOperationStatus cloneSingleAttributeOnResourceInstance(TitanVertex createdInstanceVertex, ComponentInstanceProperty attribute, String instanceId) { // Only if valueUniqueId is not empty, then its belongs to the // instance if (attribute.getValueUniqueUid() != null) { @@ -4053,7 +4052,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } } - private void createAttributeValueDataNode(ComponentInstanceAttribute attributeInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, + private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, Wrapper attValueDataWrapper) { String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) { @@ -4093,7 +4092,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo * } else { BeEcompErrorManager.getInstance().logInternalFlowError( "CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); } } */ - private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceAttribute resourceInstanceAttribute, String uniqueId) { + private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute, String uniqueId) { AttributeValueData attributeValueData = new AttributeValueData(); attributeValueData.setUniqueId(uniqueId); attributeValueData.setHidden(resourceInstanceAttribute.isHidden()); @@ -4509,7 +4508,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } @Override - public Either createOrUpdateAttributeOfResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId) { + public Either createOrUpdateAttributeOfResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId) { Either result; // Create if (attributeInstanceProperty.getValueUniqueUid() == null) { @@ -4536,7 +4535,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo * @param resourceInstanceId * @return */ - private Either updateAttributeOfResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId) { + private Either updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { Either result = null; Wrapper errorWrapper = new Wrapper<>(); @@ -4562,7 +4561,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - private Either addAttributeToResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId, Integer index) { + private Either addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) { Wrapper errorWrapper = new Wrapper<>(); Wrapper compInsWrapper = new Wrapper<>(); Wrapper attDataWrapper = new Wrapper<>(); @@ -5263,8 +5262,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } @Override - public Either addAttributeValueToResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { - Either result = null; + public Either addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { + Either result = null; try { @@ -5277,7 +5276,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else { AttributeValueData attributeValueData = eitherStatus.left().value(); - ComponentInstanceAttribute attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); + ComponentInstanceProperty attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); result = Either.left(attributeValueResult); @@ -5291,9 +5290,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } @Override - public Either updateAttributeValueInResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { + public Either updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { - Either result = null; + Either result = null; try { Either eitherAttributeValue = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId); @@ -5305,7 +5304,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else { AttributeValueData attributeValueData = eitherAttributeValue.left().value(); - ComponentInstanceAttribute attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); + ComponentInstanceProperty attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); result = Either.left(attributeValueResult); @@ -5463,7 +5462,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.left(result); } - // TODO Tal G US831698 + //US831698 public Either, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(ComponentInstance resourceInstance) { Map> alreadyProcessedResources = new HashMap<>(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java index 215a1464a6..a5a1348f21 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java @@ -23,24 +23,29 @@ package org.openecomp.sdc.be.model.operations.impl; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.IConsumerOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ConsumerData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import fj.data.Either; +import java.util.Collections; +import java.util.List; + @Component("consumer-operation") public class ConsumerOperation implements IConsumerOperation { - @javax.annotation.Resource private TitanGenericDao titanGenericDao; private static Logger log = LoggerFactory.getLogger(ConsumerOperation.class.getName()); - public ConsumerOperation() { + public ConsumerOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; } @Override @@ -58,6 +63,13 @@ public class ConsumerOperation implements IConsumerOperation { return Either.left(consumerData); } + @Override + public Either, StorageOperationStatus> getAll() { + log.debug("retrieving all consumers"); + return titanGenericDao.getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class) + .right().map(DaoStatusConverter::convertTitanStatusToStorageStatus); + } + @Override public Either createCredentials(ConsumerData consumerData) { return createCredentials(consumerData, false); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java index 4dce650f18..2cc78eade2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java @@ -20,20 +20,11 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.function.Predicate; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -54,25 +45,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; -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.ComponentInstanceAttribute; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.ResourceMetadataDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -82,7 +55,7 @@ import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.migration.MigrationErrorInformer; +import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger; import org.openecomp.sdc.be.model.operations.utils.GraphDeleteUtil; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.PropertyData; @@ -100,13 +73,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.Function; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("resource-operation") @Deprecated @@ -651,7 +629,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return getPropertiesOfAllDerivedFromRes; } - private TitanOperationStatus associateAttributesToResource(TitanVertex metadataVertex, List attributes, String resourceId) { + private TitanOperationStatus associateAttributesToResource(TitanVertex metadataVertex, List attributes, String resourceId) { TitanOperationStatus operationStatus = TitanOperationStatus.OK; Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); @@ -662,7 +640,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } if (attributes != null) { - Map convertedAttributes = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); + Map convertedAttributes = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); operationStatus = attributeOperation.addAttributesToGraph(metadataVertex, convertedAttributes, resourceId, allDataTypes.left().value()); } return operationStatus; @@ -805,12 +783,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } private TitanOperationStatus setComponentInstancesAttributesFromGraph(String uniqueId, Resource component) { - Map> resourceInstancesAttributes = new HashMap<>(); + Map> resourceInstancesAttributes = new HashMap<>(); TitanOperationStatus status = TitanOperationStatus.OK; List componentInstances = component.getComponentInstances(); if (componentInstances != null) { for (ComponentInstance resourceInstance : componentInstances) { - Either, TitanOperationStatus> eitherRIAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance); + Either, TitanOperationStatus> eitherRIAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance); if (eitherRIAttributes.isRight()) { status = eitherRIAttributes.right().value(); break; @@ -875,8 +853,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } else { Map capabilities = result.left().value(); if (capabilities != null && !capabilities.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) { - log.error(String.format("VF %s has direct capabilities.!!!!!!!!!!!!!", resource.getName())); - MigrationErrorInformer.addMalformedVF(resource.getUniqueId()); + MigrationMalformedDataLogger.reportMalformedVF(resource.getUniqueId(), String.format("VF %s with id %s has direct capabilities.!!!!!!!!!!!!!", resource.getName(), resource.getUniqueId())); } if (capabilities == null || capabilities.isEmpty() || resource.getResourceType().equals(ResourceTypeEnum.VF)) { Either>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(resource, NodeTypeEnum.Resource, true); @@ -946,8 +923,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } else { Map requirements = result.left().value(); if (requirements != null && !requirements.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) { - log.error(String.format("VF %s has direct requirements.!!!!!!!!!!!!!", resource.getName())); - MigrationErrorInformer.addMalformedVF(resource.getUniqueId()); + MigrationMalformedDataLogger.reportMalformedVF(resource.getUniqueId(), String.format("VF %s with id %s has direct requirements.!!!!!!!!!!!!!", resource.getName(), resource.getUniqueId())); } if (requirements == null || requirements.isEmpty() || resource.getResourceType() == ResourceTypeEnum.VF) { Either>, TitanOperationStatus> eitherCapabilities = super.getRequirements(resource, NodeTypeEnum.Resource, true); @@ -982,7 +958,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp private TitanOperationStatus setResourceAttributesFromGraph(String uniqueId, Resource resource) { - List attributes = new ArrayList<>(); + List attributes = new ArrayList<>(); TitanOperationStatus status = attributeOperation.findAllResourceAttributesRecursively(uniqueId, attributes); if (status == TitanOperationStatus.OK) { resource.setAttributes(attributes); @@ -1372,7 +1348,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } private StorageOperationStatus removeAttributesFromResource(Resource resource) { - Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode = attributeOperation.deleteAllAttributeAssociatedToNode(NodeTypeEnum.Resource, resource.getUniqueId()); + Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode = attributeOperation.deleteAllAttributeAssociatedToNode(NodeTypeEnum.Resource, resource.getUniqueId()); return deleteAllAttributeAssociatedToNode.isRight() ? deleteAllAttributeAssociatedToNode.right().value() : StorageOperationStatus.OK; } @@ -1862,25 +1838,23 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return getResourceListByCriteria(rootToscaResource, false); } - @Override - public Either, StorageOperationStatus> getAll() { - Either, StorageOperationStatus> resourceListByCriteria = getResourceListByCriteria(new HashMap<>(), false); - if (resourceListByCriteria.isRight() && resourceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) { - return Either.left(Collections.emptyList()); - } - return resourceListByCriteria; - } - - private Either>, TitanOperationStatus> getDerivingChildren(Resource resource) { return titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); } private Either, StorageOperationStatus> convertToResources(List resourcesMetaData) { - List> resources = resourcesMetaData.stream() - .map(resourceMetaData -> this.getResource(resourceMetaData.getMetadataDataDefinition().getUniqueId())) - .collect(Collectors.toList()); - return Either.sequenceLeft(fj.data.List.iterableList(resources)).bimap(fj.data.List::toJavaList, Function.identity()); + List resources = new ArrayList<>(); + for (ResourceMetadataData resourceMetadataData : resourcesMetaData) { + String uniqueId = resourceMetadataData.getMetadataDataDefinition().getUniqueId(); + Either resource = this.getResource(uniqueId); + if (resource.isRight()) { + StorageOperationStatus status = resource.right().value(); + log.error("Failed to fetch resource {} . status is {}", uniqueId, status); + return Either.right(status); + } + resources.add(resource.left().value()); + } + return Either.left(resources); } protected TitanOperationStatus findResourcesPathRecursively(String resourceId, List resourcesPathList) { @@ -2163,19 +2137,23 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (byCriteria.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); } - List resources = new ArrayList(); + List resources = new ArrayList<>(); List resourcesDataList = byCriteria.left().value(); for (ResourceMetadataData data : resourcesDataList) { - Either resource = getResource(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (resource.isLeft()) { - resources.add(resource.left().value()); - } else { - log.debug("Failed to fetch resource for name = {} and id = {}", data.getUniqueId(), data.getMetadataDataDefinition().getName()); - } + buildResource(inTransaction, resources, data); } return Either.left(resources); } + private void buildResource(boolean inTransaction, List resources, ResourceMetadataData data) { + Either resource = getResource(data.getMetadataDataDefinition().getUniqueId(), inTransaction); + if (resource.isLeft()) { + resources.add(resource.left().value()); + } else { + log.debug("Failed to fetch resource for name = {} and id = {}", data.getUniqueId(), data.getMetadataDataDefinition().getName()); + } + } + public Either, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction) { return getLatestResourceByUuid(uuid, false, inTransaction); } @@ -2623,7 +2601,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } resource.setInterfaces(interfacesOfResourceOnly.left().value()); - List attributes = new ArrayList<>(); + List attributes = new ArrayList<>(); TitanOperationStatus status = attributeOperation.findNodeNonInheretedAttribues(prevId, NodeTypeEnum.Resource, attributes); if (status != TitanOperationStatus.OK) { return DaoStatusConverter.convertTitanStatusToStorageStatus(status); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java index 7c45f8f384..81ca98444c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java @@ -33,6 +33,7 @@ import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.User; @@ -282,7 +283,7 @@ public class UserAdminOperation implements IUserAdminOperation { } } - public Either, StorageOperationStatus> getUserPandingTasksList(User user, Map properties) { + public Either, StorageOperationStatus> getUserPendingTasksList(User user, Map properties) { UserData userData = convertToUserData(user); @@ -316,7 +317,16 @@ public class UserAdminOperation implements IUserAdminOperation { } } } - + + if(log.isDebugEnabled()) { + for (Edge edge : pandingTasks) { + Object resourceUuid = edge.inVertex().property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value(); + Object componentName = edge.inVertex().property(GraphPropertyEnum.NAME.getProperty()).value(); + Object componentState = edge.inVertex().property(GraphPropertyEnum.STATE.getProperty()).value(); + log.debug("The user userId = {} is working on the component name = {} uid = {} in state {}", user.getUserId(), componentName, resourceUuid, componentState); + } + } + return Either.left(pandingTasks); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java deleted file mode 100644 index 952c0672cc..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.openecomp.sdc.be.model.operations.migration; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * to be moved with all operations to the migration project - */ -@Deprecated -public class MigrationErrorInformer { - - private static Logger log = LoggerFactory.getLogger(MigrationErrorInformer.class); - private static Set malformedVFs = new HashSet<>(); - - public static void addMalformedVF(String vfId) { - malformedVFs.add(vfId); - } - - public static void logIfServiceUsingMalformedVfs(Component service) { - List componentInstances = service.getComponentInstances(); - if (componentInstances != null && !componentInstances.isEmpty() && !malformedVFs.isEmpty()) { - Set serviceInstances = componentInstances.stream().map(ComponentInstance::getComponentUid).collect(Collectors.toSet()); - serviceInstances.retainAll(malformedVFs); - if (!serviceInstances.isEmpty()) { - log.error(String.format("Service %s is using malformed VFs: %s", service.getUniqueId(), StringUtils.join(serviceInstances, ','))); - } - } - } - - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java new file mode 100644 index 0000000000..2d4ca635e7 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java @@ -0,0 +1,44 @@ +package org.openecomp.sdc.be.model.operations.migration; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * to be moved with all operations to the migration project + */ + +public class MigrationMalformedDataLogger { + + private static Logger log = LoggerFactory.getLogger(MigrationMalformedDataLogger.class); + private static Set malformedVFs = new HashSet<>(); + + public static void reportMalformedVF(String vfId, String errorMsg) { + log.error(errorMsg); + malformedVFs.add(vfId); + } + + public static void logMalformedDataMsg(String errorMsg) { + log.error(errorMsg); + } + + public static void logIfServiceUsingMalformedVfs(Component service) { + List componentInstances = service.getComponentInstances(); + if (componentInstances != null && !componentInstances.isEmpty() && !malformedVFs.isEmpty()) { + Set serviceInstances = componentInstances.stream().map(ComponentInstance::getComponentUid).collect(Collectors.toSet()); + serviceInstances.retainAll(malformedVFs); + if (!serviceInstances.isEmpty()) { + log.error(String.format("Service %s is using malformed VFs: %s", service.getUniqueId(), StringUtils.join(serviceInstances, ','))); + } + } + } + + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java index 079d64a60e..ad226f4e57 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java @@ -63,6 +63,8 @@ public enum ToscaPropertyType { FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()), INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()), + + SCALAR_UNIT("scalar-unit", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), 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 80b8779e1e..14f63650ac 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 @@ -168,7 +168,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T return handleComplexJsonValue(entryValue); } - // Tal G ticket 228696523 created / DE272734 / Bug 154492 Fix + // ticket 228696523 created / DE272734 / Bug 154492 Fix if(entryValue instanceof JsonArray) { ArrayList toscaObjectPresentationArray = new ArrayList<>(); JsonArray jsonArray = entryValue.getAsJsonArray(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java index 6eb7b841ab..36b6c574aa 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java @@ -7,10 +7,8 @@ import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.GroupDefinition; @@ -48,7 +46,7 @@ public class UiComponentDataTransfer { private Map> componentInstancesProperties; - private Map> componentInstancesAttributes; + private Map> componentInstancesAttributes; private Map> capabilities; @@ -60,7 +58,7 @@ public class UiComponentDataTransfer { protected List additionalInformation; - + public UiComponentDataTransfer(){} public Map getArtifacts() { return artifacts; @@ -192,13 +190,13 @@ public class UiComponentDataTransfer { } - public Map> getComponentInstancesAttributes() { + public Map> getComponentInstancesAttributes() { return componentInstancesAttributes; } public void setComponentInstancesAttributes( - Map> componentInstancesAttributes) { + Map> componentInstancesAttributes) { this.componentInstancesAttributes = componentInstancesAttributes; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java index f0679d31de..6dabfc1402 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java @@ -64,6 +64,7 @@ public abstract class UiComponentMetadata { private String lastUpdaterFullName; + public UiComponentMetadata(){} public UiComponentMetadata (List categories, ComponentMetadataDataDefinition metadata) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java index c56daa4fc9..2547457abc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java @@ -4,7 +4,6 @@ import java.util.List; import java.util.Map; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; @@ -18,7 +17,7 @@ public class UiResourceDataTransfer extends UiComponentDataTransfer{ private List properties; - private List attributes; + private List attributes; private Map interfaces; @@ -26,6 +25,8 @@ public class UiResourceDataTransfer extends UiComponentDataTransfer{ private List additionalInformation; + public UiResourceDataTransfer(){} + public List getAdditionalInformation() { return additionalInformation; } @@ -66,11 +67,11 @@ public class UiResourceDataTransfer extends UiComponentDataTransfer{ this.properties = properties; } - public List getAttributes() { + public List getAttributes() { return attributes; } - public void setAttributes(List attributes) { + public void setAttributes(List attributes) { this.attributes = attributes; } 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 19c7246462..3675bc619c 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 @@ -16,6 +16,7 @@ public class UiResourceMetadata extends UiComponentMetadata { private String toscaResourceName; private List derivedFrom; + public UiResourceMetadata(List categories, List derivedFrom, ResourceMetadataDataDefinition metadata) { super(categories, metadata); this.vendorName = metadata.getVendorName(); @@ -27,6 +28,8 @@ public class UiResourceMetadata extends UiComponentMetadata { this.derivedFrom = derivedFrom; } + public UiResourceMetadata(){} + public List getDerivedFrom() { return derivedFrom; } diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts index db03aa53fb..b404a83634 100644 --- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts +++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts @@ -168,7 +168,7 @@ export class CompositionGraph implements ng.IDirective { this.ComponentServiceNg2.getCapabilitiesAndRequirements(leftPaletteComponent.componentType, leftPaletteComponent.uniqueId).subscribe((response: ComponentGenericResponse) => { - let component = this.ComponentFactory.createEmptyComponent(leftPaletteComponent.componentType); + let component = this.ComponentFactory.createEmptyComponent(leftPaletteComponent.componentType); component.uniqueId = component.uniqueId; component.capabilities = response.capabilities; component.requirements = response.requirements; @@ -246,6 +246,7 @@ export class CompositionGraph implements ng.IDirective { this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_VERSION_CHANGED, (component:Component) => { scope.component = component; + this._cy.elements().remove(); this.loadGraphData(scope); }); 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 a0c9a6c460..fa71e47804 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 @@ -96,15 +96,17 @@ export class TypeMapDirective implements ng.IDirective { } else { scope.parentFormObj[fieldName].$setValidity('keyExist', true); if (!scope.parentFormObj[fieldName].$invalid) { + //To preserve the order of the keys, delete each one and recreate let newObj = {}; - angular.forEach(scope.valueObjRef,function(value:any,key:string){ + angular.copy(scope.valueObjRef , newObj); + angular.forEach(newObj,function(value:any,key:string){ + delete scope.valueObjRef[key]; if(key == oldKey){ - newObj[newKey] = value; + scope.valueObjRef[newKey] = value; }else{ - newObj[key] = value; + scope.valueObjRef[key] = value; } }); - scope.valueObjRef = newObj; } } }; diff --git a/catalog-ui/src/app/models.ts b/catalog-ui/src/app/models.ts index 5b286d0667..838137ba72 100644 --- a/catalog-ui/src/app/models.ts +++ b/catalog-ui/src/app/models.ts @@ -29,6 +29,7 @@ export * from './models/properties-inputs/property-fe-model'; export * from './models/properties-inputs/property-fe-map'; export * from './models/properties-inputs/derived-fe-property'; export * from './models/properties-inputs/input-fe-model'; +export * from './models/properties-inputs/simple-flat-property'; export * from './models/data-types-map'; export * from './models/data-types'; export * from './models/distribution'; @@ -82,3 +83,5 @@ export * from './models/component-metadata'; 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/components/component.ts b/catalog-ui/src/app/models/components/component.ts index 898285f032..c7cc81fae7 100644 --- a/catalog-ui/src/app/models/components/component.ts +++ b/catalog-ui/src/app/models/components/component.ts @@ -205,7 +205,19 @@ export abstract class Component implements IComponent { //------------------------------------------ API Calls ----------------------------------------------------------------// public changeLifecycleState = (state:string, commentObj:AsdcComment):ng.IPromise => { - return this.componentService.changeLifecycleState(this, state, JSON.stringify(commentObj)); + let deferred = this.$q.defer(); + let onSuccess = (componentMetadata:ComponentMetadata):void => { + this.setComponentMetadata(componentMetadata); + // this.version = componentMetadata.version; + this.lifecycleState = componentMetadata.lifecycleState; + + deferred.resolve(this); + }; + let onError = (error:any):void => { + deferred.reject(error); + }; + this.componentService.changeLifecycleState(this, state, JSON.stringify(commentObj)).then(onSuccess, onError); + return deferred.promise; }; public getComponent = ():ng.IPromise => { @@ -892,7 +904,7 @@ export abstract class Component implements IComponent { this.systemName = componentMetadata.systemName; this.projectCode = componentMetadata.projectCode; this.categories = componentMetadata.categories; - + } public toJSON = ():any => { diff --git a/catalog-ui/src/app/models/graph/graph-links/links-factory.ts b/catalog-ui/src/app/models/graph/graph-links/links-factory.ts index 7fdc0838ed..1744aa0ff3 100644 --- a/catalog-ui/src/app/models/graph/graph-links/links-factory.ts +++ b/catalog-ui/src/app/models/graph/graph-links/links-factory.ts @@ -33,19 +33,20 @@ export class LinksFactory { let newRelation:CompositionCiLinkBase; - let fromNode:CompositionCiNodeBase = cy.getElementById(relation.fromNode).data(); - let toNode:CompositionCiNodeBase = cy.getElementById(relation.toNode).data(); - - if ((relation.fromNode && fromNode.isUcpePart) || (relation.toNode && toNode.isUcpePart )) { //Link from or to node inside ucpe - - if (singleRelation && singleRelation.relationship.type && singleRelation.relationship.type == 'tosca.relationships.HostedOn') { - newRelation = new LinkUcpeHost(relation, singleRelation); - } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) { - newRelation = new CompositionCiVlUcpeLink(relation, fromNode.isUcpePart, singleRelation); - } else { - newRelation = new CompositionCiUcpeLink(relation, fromNode.isUcpePart, singleRelation); - } - } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) { + // let fromNode:CompositionCiNodeBase = cy.getElementById(relation.fromNode).data(); + // let toNode:CompositionCiNodeBase = cy.getElementById(relation.toNode).data(); + // + // if ((relation.fromNode && fromNode.isUcpePart) || (relation.toNode && toNode.isUcpePart )) { //Link from or to node inside ucpe + // + // if (singleRelation && singleRelation.relationship.type && singleRelation.relationship.type == 'tosca.relationships.HostedOn') { + // newRelation = new LinkUcpeHost(relation, singleRelation); + // } else if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) { + // newRelation = new CompositionCiVlUcpeLink(relation, fromNode.isUcpePart, singleRelation); + // } else { + // newRelation = new CompositionCiUcpeLink(relation, fromNode.isUcpePart, singleRelation); + // } + // } else + if (singleRelation.relationship.type && _.includes(singleRelation.relationship.type.toLowerCase(), 'link')) { newRelation = new CompositionCiVLink(relation, singleRelation); } else { newRelation = new CompositionCiSimpleLink(relation, singleRelation); diff --git a/catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts b/catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts index 1d79353453..f7117e456c 100644 --- a/catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts +++ b/catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts @@ -1,15 +1,11 @@ import { SchemaPropertyGroupModel, SchemaProperty } from '../aschema-property'; -import { PROPERTY_DATA, PROPERTY_TYPES} from 'app/utils'; -import { PropertyBEModel } from '../../models'; +import { DerivedPropertyType, PropertyBEModel } from '../../models'; +import { PROPERTY_TYPES } from 'app/utils'; +import { UUID } from "angular2-uuid"; -export enum DerivedPropertyType { - SIMPLE, - LIST, - MAP, - COMPLEX //other datatype, list of non-simple, or map of non-simple -} export class DerivedFEProperty extends PropertyBEModel { + valueObj: any; parentName: string; propertiesName: string; //"network_assignments#ipv4_subnet#use_ipv4 = parentPath + name derivedDataType: DerivedPropertyType; @@ -17,56 +13,39 @@ export class DerivedFEProperty extends PropertyBEModel { isSelected: boolean; isDisabled: boolean; isChildOfListOrMap: boolean; + canBeDeclared: boolean; + mapKey: string; - constructor(property: PropertyBEModel, parentName?: string) - constructor(name: string, parentName: string, type: string, value: string, isChildOfListOrMap?:boolean, schema?: SchemaPropertyGroupModel); - constructor(nameOrPropertyObj?: string | PropertyBEModel, parentName?: string, type?: string, value?: string, isChildOfListOrMap?: boolean, schema?: SchemaPropertyGroupModel) { - - super(typeof nameOrPropertyObj === 'string' ? null : nameOrPropertyObj); - - if (typeof nameOrPropertyObj !== 'string') { //constructor #1 + constructor(property: PropertyBEModel, parentName?: string, createChildOfListOrMap?: boolean, key?:string, value?:any) { + if (!createChildOfListOrMap) { //creating a standard derived prop + super(property); this.parentName = parentName ? parentName : null; - this.propertiesName = (parentName) ? parentName + '#' + nameOrPropertyObj.name : nameOrPropertyObj.name; - } else { //constructor #2 - this.name = nameOrPropertyObj; - this.type = type; + this.propertiesName = (parentName) ? parentName + '#' + property.name : property.name; + this.canBeDeclared = true; //defaults to true + } else { //creating a direct child of list or map (ie. Item that can be deleted, with UUID instead of name) + super(null); + this.isChildOfListOrMap = true; + this.canBeDeclared = false; + this.name = UUID.UUID(); this.parentName = parentName; - this.propertiesName = parentName + '#' + nameOrPropertyObj; - this.value = value; - if (schema) { - this.schema = new SchemaPropertyGroupModel(new SchemaProperty(schema.property)); + this.propertiesName = parentName + '#' + this.name; + + + if (property.type == PROPERTY_TYPES.LIST) { + this.mapKey = property.schema.property.type.split('.').pop(); + this.type = property.schema.property.type; + } else { //map + this.mapKey = key || ""; + this.type = property.type; } + this.valueObj = (this.type == PROPERTY_TYPES.JSON && typeof value == 'object') ? JSON.stringify(value) : value; + this.schema = new SchemaPropertyGroupModel(new SchemaProperty(property.schema.property)); } this.derivedDataType = this.getDerivedPropertyType(); - this.isChildOfListOrMap = (isChildOfListOrMap) ? isChildOfListOrMap : false; } - - public getDerivedPropertyType = () => { - if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1) { - return DerivedPropertyType.SIMPLE; - } else if (this.type == PROPERTY_TYPES.LIST) { - return DerivedPropertyType.LIST; - } else if (this.type == PROPERTY_TYPES.MAP) { - return DerivedPropertyType.MAP; - } else { - return DerivedPropertyType.COMPLEX; - } - } } export class DerivedFEPropertyMap { [parentPath: string]: Array; } - - -// isDataType: boolean; - - -// canAdd: boolean; -// canCollapse: boolean; -// canBeDeclared: boolean; - -// derivedValue: string; -// derivedValueType: string; -// propertiesName: string; \ No newline at end of file diff --git a/catalog-ui/src/app/models/properties-inputs/input-be-model.ts b/catalog-ui/src/app/models/properties-inputs/input-be-model.ts new file mode 100644 index 0000000000..6d7854a6bf --- /dev/null +++ b/catalog-ui/src/app/models/properties-inputs/input-be-model.ts @@ -0,0 +1,49 @@ +import {PropertyBEModel} from 'app/models'; +/** + * Created by rc2122 on 6/1/2017. + */ +export class InputBEModel extends PropertyBEModel { + properties:Array; + inputs:Array; + + constructor(input?: PropertyBEModel) { + super(input); + } + + + + public toJSON = (): any => { + }; + +} + +export class ComponentInstanceProperty extends PropertyBEModel { + componentInstanceId:string; + componentInstanceName:string; + + constructor(property?: PropertyBEModel) { + super(property); + } + + + + public toJSON = (): any => { + }; + +} + +export class ComponentInstanceInput extends InputBEModel { + componentInstanceId:string; + componentInstanceName:string; + + constructor(property?: PropertyBEModel) { + super(property); + } + + + + public toJSON = (): any => { + }; + +} + 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 1261df3d6d..03c923c228 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 @@ -1,25 +1,37 @@ import { SchemaPropertyGroupModel, SchemaProperty } from "../aschema-property"; import { PropertyBEModel } from "../../models"; import {PROPERTY_DATA} from "../../utils/constants"; +import {InputBEModel} from "./input-be-model"; -export class InputFEModel extends PropertyBEModel { +export class InputFEModel extends InputBEModel { isSimpleType: boolean; isDataType: boolean; instanceName: string; + instanceId: string; propertyName: string; - constructor(input?: PropertyBEModel) { + constructor(input?: InputBEModel) { super(input); if (input) { this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1; this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1; + let propNameIndex:number = this.name.indexOf('_'); this.instanceName = this.name.substring(0, propNameIndex); - if (input.inputPath) { - this.propertyName = input.inputPath.substring(0, input.inputPath.indexOf('#')) - } else { - this.propertyName = this.name.substring(propNameIndex + 1); + + if(input.properties && input.properties.length){ + this.instanceId = input.properties[0].componentInstanceId; + this.propertyName = input.properties[0].name; + }else if(input.inputs && input.inputs.length){ + this.instanceId = input.inputs[0].componentInstanceId; + this.propertyName = input.inputs[0].name; + }else{ + if (input.inputPath) { + this.propertyName = input.inputPath.substring(0, input.inputPath.indexOf('#')) + } else { + this.propertyName = this.name.substring(propNameIndex + 1); + } } } } diff --git a/catalog-ui/src/app/models/properties-inputs/property-be-model.ts b/catalog-ui/src/app/models/properties-inputs/property-be-model.ts index a5279d0668..f5cd4094f5 100644 --- a/catalog-ui/src/app/models/properties-inputs/property-be-model.ts +++ b/catalog-ui/src/app/models/properties-inputs/property-be-model.ts @@ -1,4 +1,11 @@ import { SchemaPropertyGroupModel, SchemaProperty } from "../aschema-property"; +import { PROPERTY_DATA, PROPERTY_TYPES } from 'app/utils'; +export enum DerivedPropertyType { + SIMPLE, + LIST, + MAP, + COMPLEX +} export class PropertyBEModel { @@ -16,6 +23,7 @@ export class PropertyBEModel { definition: boolean; inputPath: string; propertiesName: string; + ownerId: string; input: PropertyBEModel; constructor(property?: PropertyBEModel, childProperty?:PropertyBEModel) { @@ -32,6 +40,7 @@ export class PropertyBEModel { this.uniqueId = property.uniqueId; this.value = property.value ? property.value : property.defaultValue; this.definition = property.definition; + this.ownerId = property.ownerId; if (property.inputPath) { this.inputPath = property.inputPath; } @@ -39,6 +48,8 @@ export class PropertyBEModel { if (childProperty) { this.input = childProperty; this.propertiesName = childProperty.propertiesName; + } else { + this.propertiesName = this.name; } if (!this.schema || !this.schema.property) { @@ -48,7 +59,7 @@ export class PropertyBEModel { } } - + public toJSON = (): any => { let temp = angular.copy(this); @@ -57,6 +68,18 @@ export class PropertyBEModel { return temp; }; + public getDerivedPropertyType = () => { + if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1) { + return DerivedPropertyType.SIMPLE; + } else if (this.type == PROPERTY_TYPES.LIST) { + return DerivedPropertyType.LIST; + } else if (this.type == PROPERTY_TYPES.MAP) { + return DerivedPropertyType.MAP; + } else { + return DerivedPropertyType.COMPLEX; + } + } + } 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 29f2c79225..564611c344 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 @@ -1,86 +1,40 @@ import {SchemaPropertyGroupModel, SchemaProperty} from '../aschema-property'; -import { PROPERTY_DATA } from 'app/utils'; -import { PropertyBEModel, DerivedFEPropertyMap, DerivedFEProperty } from '../../models'; +import { PROPERTY_DATA, PROPERTY_TYPES } from 'app/utils'; +import { FilterPropertiesAssignmentData, PropertyBEModel, DerivedPropertyType, DerivedFEPropertyMap, DerivedFEProperty } from 'app/models'; export class PropertyFEModel extends PropertyBEModel { - //START - TO REMOVE: - treeNodeId: string; - parent: PropertyFEModel; - - childrenProperties: Array; - isAllChildrenLevelsCalculated: boolean; - uniqueId: string; - valueObjectRef: any; - //END - TO REMOVE: - expandedChildPropertyId: string; flattenedChildren: Array; //[parentPath] : Array - isDataType: boolean; //aka- isComplexType. (Type is NOT: simple, list, or map) isDeclared: boolean; isDisabled: boolean; isSelected: boolean; - isSimpleType: boolean; - - private _derivedFromSimpleTypeName:string; - get derivedFromSimpleTypeName():string { - return this._derivedFromSimpleTypeName; - } - set derivedFromSimpleTypeName(derivedFromSimpleTypeName:string) { - this._derivedFromSimpleTypeName = derivedFromSimpleTypeName; - } - - constructor(property?: PropertyBEModel); - constructor(name: string, type: string, treeNodeId: string, parent: PropertyFEModel, valueObjectRef: any, schema?: SchemaPropertyGroupModel); - constructor(nameOrPropertyObj?: string | PropertyBEModel, type?: string, treeNodeId?: string, parent?: PropertyFEModel, valueObjectRef?: any, schema?: SchemaPropertyGroupModel) { - - super(typeof nameOrPropertyObj === 'string' ? null : nameOrPropertyObj); - - if (typeof nameOrPropertyObj === 'string') { - this.name = nameOrPropertyObj; - this.type = type; - this.treeNodeId = treeNodeId; - this.parent = parent; - this.valueObjectRef = valueObjectRef; - this.value = this.value || this.defaultValue; - if(schema){ - this.schema = new SchemaPropertyGroupModel(new SchemaProperty(schema.property)); - } - } + isSimpleType: boolean; //for convenience only - we can really just check if derivedDataType == derivedPropertyTypes.SIMPLE to know if the prop is simple + uniqueId: string; + valueObj: any; //this is the only value we relate to in the html templates + derivedDataType: DerivedPropertyType; + constructor(property: PropertyBEModel){ + super(property); this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1; - this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1; this.setNonDeclared(); + this.derivedDataType = this.getDerivedPropertyType(); + this.flattenedChildren = []; } - public convertChildToInput = (childName: string): void => { - //childName: "mac_count_required" - let childJson = this.flattenedChildren[childName].map((child) => { - }); - }; - - public getChildJsonRecursive = (child: string, value?: string): void => { - //TODO: use array.map for the below - /* value += "{" + this.flattenedChildren[child].name + ":"; - if (this.flattenedChildren[child].valueType == 'simple') { - value += this.flattenedChildren[child].value + '}'; - return value; - } else { - this.flattenedChildren[child].forEach(grandChild => { - if (this.flattenedChildren[grandChild].valueType == 'simple') { - return "{" + this.flattenedChildren[grandChild].name + ':' + this.flattenedChildren[child].value.toString() + "}"; - } else { - return this.getChildJsonRecursive(grandChild + '#' + this.flattenedChildren[child].name); - } - }); + public getJSONValue = (): string => { + //If type is JSON, need to try parsing it before we stringify it so that it appears property in TOSCA - change per Bracha due to AMDOCS + //TODO: handle this.derivedDataType == DerivedPropertyType.MAP + if (this.derivedDataType == DerivedPropertyType.LIST && this.schema.property.type == PROPERTY_TYPES.JSON) { + try { + return JSON.stringify(this.valueObj.map(item => JSON.parse(item))); + } catch (e){} } - return "{" + this.flattenedChildren[child].name + this.flattenedChildren[child].value.toString() + "}"; -*/ - - }; + return (this.derivedDataType == DerivedPropertyType.SIMPLE) ? this.valueObj : JSON.stringify(this.valueObj); + } public setNonDeclared = (childPath?: string): void => { if (!childPath) { //declaring a child prop @@ -102,31 +56,26 @@ export class PropertyFEModel extends PropertyBEModel { } } - - - //For expand-collapse functionality + //For expand-collapse functionality - used within HTML template public updateExpandedChildPropertyId = (childPropertyId: string): void => { if (childPropertyId.lastIndexOf('#') > -1) { this.expandedChildPropertyId = (this.expandedChildPropertyId == childPropertyId) ? (childPropertyId.substring(0, childPropertyId.lastIndexOf('#'))) : childPropertyId; } else { this.expandedChildPropertyId = this.name; } - //console.log("expandedChild is now " + this.expandedChildPropertyId); } - public convertToServerObject: Function = (): any => { //TODO: Idan, Rachel, Nechama: Decide what we need to do here - // let serverObject = {}; - // let mapData = { - // 'type': this.type, - // 'required': this.required || false, - // 'defaultValue': this.defaultValue != '' && this.defaultValue != '[]' && this.defaultValue != '{}' ? this.defaultValue : null, - // 'description': this.description, - // 'isPassword': this.password || false, - // 'schema': this.schema, - // 'name': this.name - // }; - // serverObject[this.name] = mapData; + public getIndexOfChild = (childPropName: string): number => { + return this.flattenedChildren.findIndex(prop => prop.propertiesName.indexOf(childPropName) === 0); + } + + public getCountOfChildren = (childPropName: string):number => { + let matchingChildren:Array = this.flattenedChildren.filter(prop => prop.propertiesName.indexOf(childPropName) === 0) || []; + return matchingChildren.length; + } + + // public getListIndexOfChild = (childPropName: string): number => { //gets list of siblings and then the index within that list + // this.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName) + // } - //return JSON.stringify(serverObject); - }; } diff --git a/catalog-ui/src/app/models/properties-inputs/simple-flat-property.ts b/catalog-ui/src/app/models/properties-inputs/simple-flat-property.ts new file mode 100644 index 0000000000..d67a7d4d14 --- /dev/null +++ b/catalog-ui/src/app/models/properties-inputs/simple-flat-property.ts @@ -0,0 +1,15 @@ +export class SimpleFlatProperty { + uniqueId: string; + path: string; + name: string; + parentName: string; + instanceName: string; + + constructor(uniqueId?: string, path?: string, name?: string, parentName?: string, instanceName?: string) { + this.uniqueId = uniqueId; + this.path = path; + this.name = name; + this.parentName = parentName; + this.instanceName = instanceName; + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/models/property-fe-model.ts b/catalog-ui/src/app/models/property-fe-model.ts deleted file mode 100644 index f83d6d6b51..0000000000 --- a/catalog-ui/src/app/models/property-fe-model.ts +++ /dev/null @@ -1,78 +0,0 @@ -import {SchemaPropertyGroupModel, SchemaProperty} from './aschema-property'; -import { PROPERTY_DATA } from 'app/utils'; -import { FilterPropertiesAssignmentData, PropertyBEModel } from 'app/models'; - -export class PropertyFEModel extends PropertyBEModel { - public static filterData:FilterPropertiesAssignmentData; - childrenProperties: Array; - expandedChildPropertyId: string; - isAllChildrenLevelsCalculated: boolean; - isDataType: boolean; - isDisabled: boolean; - isSelected: boolean; - isSimpleType: boolean; - parent: PropertyFEModel; - treeNodeId: string; - valueObjectRef: any; - private _derivedFromSimpleTypeName:string; - get derivedFromSimpleTypeName():string { - return this._derivedFromSimpleTypeName; - } - set derivedFromSimpleTypeName(derivedFromSimpleTypeName:string) { - this._derivedFromSimpleTypeName = derivedFromSimpleTypeName; - } - - constructor(property?: PropertyBEModel); - constructor(name: string, type: string, treeNodeId: string, parent: PropertyFEModel, valueObjectRef: any, schema?: SchemaPropertyGroupModel); - constructor(nameOrPropertyObj?: string | PropertyBEModel, type?: string, treeNodeId?: string, parent?: PropertyFEModel, valueObjectRef?: any, schema?: SchemaPropertyGroupModel) { - - super(typeof nameOrPropertyObj === 'string' ? null : nameOrPropertyObj); - - if (typeof nameOrPropertyObj === 'string') { - this.name = nameOrPropertyObj; - this.type = type; - this.treeNodeId = treeNodeId; - this.parent = parent; - this.valueObjectRef = valueObjectRef; - this.value = this.value || this.defaultValue; - if(schema){ - this.schema = new SchemaPropertyGroupModel(new SchemaProperty(schema.property)); - } - } - this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1; - this.isDataType = PROPERTY_DATA.TYPES.indexOf(this.type) == -1; - this.setNonDeclared(); - } - - - public setNonDeclared = (): void => { - this.isSelected = false; - this.isDisabled = false; - } - - public setAsDeclared = (): void => { - this.isSelected = true; - this.isDisabled = true; - } - - //For expand-collapse functionality - public updateExpandedChildPropertyId = (childPropertyId: string): void => { - this.expandedChildPropertyId = (this.expandedChildPropertyId == childPropertyId) ? '' : childPropertyId; - } - - public convertToServerObject: Function = (): any => { //TODO: Idan, Rachel, Nechama: Decide what we need to do here - // let serverObject = {}; - // let mapData = { - // 'type': this.type, - // 'required': this.required || false, - // 'defaultValue': this.defaultValue != '' && this.defaultValue != '[]' && this.defaultValue != '{}' ? this.defaultValue : null, - // 'description': this.description, - // 'isPassword': this.password || false, - // 'schema': this.schema, - // 'name': this.name - // }; - // serverObject[this.name] = mapData; - - //return JSON.stringify(serverObject); - }; -} diff --git a/catalog-ui/src/app/modules/view-model-module.ts b/catalog-ui/src/app/modules/view-model-module.ts index 4060fe794e..7bfc014c36 100644 --- a/catalog-ui/src/app/modules/view-model-module.ts +++ b/catalog-ui/src/app/modules/view-model-module.ts @@ -53,7 +53,7 @@ import {ReqAndCapabilitiesViewModel} from "../view-models/workspace/tabs/req-and import {InputFormViewModel} from "../view-models/forms/input-form/input-form-view-modal"; import {HierarchyViewModel} from "../view-models/tabs/hierarchy/hierarchy-view-model"; import {downgradeComponent} from "@angular/upgrade/static"; -import {ConformanceLevelModalViewModel} from "../view-models/workspace/conformance-level-modal/conformance-level-modal-view-model"; +import {ConformanceLevelModalViewModel} from "../view-models/modals/conformance-level-modal/conformance-level-modal-view-model"; // import {NG2ExampleComponent} from "../ng2/view-ng2/ng2.example.component/ng2.example.component"; // import {upgradeAdapter} from "../ng2/app.module"; // import { UpgradeAdapter } from '@angular/upgrade'; diff --git a/catalog-ui/src/app/ng2/app.module.ts b/catalog-ui/src/app/ng2/app.module.ts index 9e122cd288..ea73d382e2 100644 --- a/catalog-ui/src/app/ng2/app.module.ts +++ b/catalog-ui/src/app/ng2/app.module.ts @@ -8,7 +8,7 @@ import {UpgradeModule} from '@angular/upgrade/static'; import {PropertiesAssignmentModule} from './pages/properties-assignment/properties-assignment.module'; import { DataTypesServiceProvider, SharingServiceProvider, CookieServiceProvider, - StateParamsServiceFactory + StateParamsServiceFactory, CacheServiceProvider, EventListenerServiceProvider } from "./utils/ng1-upgraded-provider"; import {ConfigService} from "./services/config.service"; import {HttpService} from "./services/http.service"; @@ -48,6 +48,8 @@ export function configServiceFactory(config:ConfigService) { SharingServiceProvider, CookieServiceProvider, StateParamsServiceFactory, + CacheServiceProvider, + EventListenerServiceProvider, AuthenticationService, Cookie2Service, ConfigService, diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts index de5965e488..84ac46c4cf 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts +++ b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.component.ts @@ -4,6 +4,7 @@ import { UiElementDropDownComponent, DropdownValue } from './elements-ui/dropdow import { UiElementInputComponent } from './elements-ui/input/ui-element-input.component'; import {UiElementPopoverInputComponent} from "./elements-ui/popover-input/ui-element-popover-input.component"; import {ValidationConfiguration} from "app/models"; +import {UiElementIntegerInputComponent} from "./elements-ui/integer-input/ui-element-integer-input.component"; @Component({ selector: 'dynamic-element', @@ -13,7 +14,8 @@ import {ValidationConfiguration} from "app/models"; UiElementInputComponent, UiElementDropDownComponent, UiElementCheckBoxComponent, - UiElementPopoverInputComponent + UiElementPopoverInputComponent, + UiElementIntegerInputComponent ] }) export class DynamicElementComponent { @@ -21,6 +23,7 @@ export class DynamicElementComponent { @ViewChild('target', { read: ViewContainerRef }) target: any; @Input() type: any; @Input() name: string; + @Input() readonly:boolean; value:any; // Two way binding for value (need to write the "Change" word like this) @@ -50,17 +53,16 @@ export class DynamicElementComponent { // Factory to create component based on type or peroperty name. switch(this.type) { case 'list': - case 'integer': - this.createComponent(UiElementInputComponent); + case 'integer': + this.createComponent(UiElementIntegerInputComponent); this.cmpRef.instance.pattern = this.validation.validationPatterns.integer; break; case 'string': - switch(this.name.toUpperCase()) { - case 'SUBNETPOOLID': - this.createComponent(UiElementPopoverInputComponent); - break; - default: - this.createComponent(UiElementInputComponent); + if (this.name.toUpperCase().indexOf("SUBNETPOOLID") !== -1) { + this.createComponent(UiElementPopoverInputComponent); + } + else { + this.createComponent(UiElementInputComponent); } break; case 'boolean': @@ -84,6 +86,7 @@ export class DynamicElementComponent { this.cmpRef.instance.name = this.name; this.cmpRef.instance.type = this.type; this.cmpRef.instance.value = this.value; + this.cmpRef.instance.readonly = this.readonly; } // Subscribe to change event of of ui-element-basic and fire event to change the value diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts index 18b044bc9d..f53b8616ac 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts +++ b/catalog-ui/src/app/ng2/components/dynamic-element/dynamic-element.module.ts @@ -8,6 +8,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms' import { UiElementPopoverInputComponent } from "./elements-ui/popover-input/ui-element-popover-input.component"; import {PopoverModule} from "../popover/popover.module"; import {TooltipModule} from "../tooltip/tooltip.module"; +import {UiElementIntegerInputComponent} from "./elements-ui/integer-input/ui-element-integer-input.component"; @NgModule({ declarations: [ @@ -15,7 +16,8 @@ import {TooltipModule} from "../tooltip/tooltip.module"; UiElementInputComponent, UiElementCheckBoxComponent, UiElementDropDownComponent, - UiElementPopoverInputComponent + UiElementPopoverInputComponent, + UiElementIntegerInputComponent ], imports: [ BrowserModule, diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html index 2ad3d8e94a..a3e28c5f0b 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/checkbox/ui-element-checkbox.component.html @@ -1 +1 @@ - + diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html index 589d00e42d..bfb927af71 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.html @@ -1,3 +1,3 @@ - diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts index 208bf54983..b1fb37a186 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/dropdown/ui-element-dropdown.component.ts @@ -18,7 +18,6 @@ export class DropdownValue { styleUrls: ['./ui-element-dropdown.component.less'], }) export class UiElementDropDownComponent extends UiElementBase implements UiElementBaseInterface { - @Input() values: DropdownValue[]; @@ -27,7 +26,7 @@ export class UiElementDropDownComponent extends UiElementBase implements UiEleme } onSave() { - this.baseEmitter.emit(this.value); + this.baseEmitter.emit(JSON.parse(this.value)); } } diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html index 00fea65b72..814ebfd28b 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.html @@ -10,4 +10,6 @@ [pattern]="pattern" [formControl]="control" tooltip="{{value}}" + [readonly]="readonly" + [ngClass]="{'disabled':readonly}" /> diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts index 5a14d8f206..2d64d9b713 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/input/ui-element-input.component.ts @@ -1,4 +1,4 @@ -import { Component, ViewChild, ElementRef, ContentChildren } from '@angular/core'; +import {Component, ViewChild, ElementRef, ContentChildren, Input} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser' import { UiElementBase, UiElementBaseInterface } from './../ui-element-base.component'; @@ -8,7 +8,6 @@ import { UiElementBase, UiElementBaseInterface } from './../ui-element-base.comp styleUrls: ['./ui-element-input.component.less'], }) export class UiElementInputComponent extends UiElementBase implements UiElementBaseInterface { - constructor() { super(); this.pattern = this.validation.validationPatterns.comment; diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.html new file mode 100644 index 0000000000..e5518d453f --- /dev/null +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.html @@ -0,0 +1,15 @@ + diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.less b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.less new file mode 100644 index 0000000000..8073c3858e --- /dev/null +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.less @@ -0,0 +1,17 @@ +@import '../../../../../../assets/styles/variables'; + +/deep/ ui-element-integer-input { + + input { + text-indent: 6px; + border: solid 1px @main_color_o; + } + + .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/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts new file mode 100644 index 0000000000..d42c80a89e --- /dev/null +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts @@ -0,0 +1,21 @@ +import {Component, ViewChild, ElementRef, ContentChildren, Input} from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser' +import { UiElementBase, UiElementBaseInterface } from './../ui-element-base.component'; + +@Component({ + selector: 'ui-element-integer-input', + templateUrl: './ui-element-integer-input.component.html', + styleUrls: ['./ui-element-integer-input.component.less'], +}) +export class UiElementIntegerInputComponent extends UiElementBase implements UiElementBaseInterface { + constructor() { + super(); + this.pattern = this.validation.validationPatterns.comment; + } + + onSave() { + if (!this.control.invalid){ + this.baseEmitter.emit(JSON.parse(this.value)); + } + } +} diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html index 5adceb49a0..3bd51b4e36 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.html @@ -4,10 +4,10 @@ type="text" [ngClass]="{'error': control.invalid}" [name]="name" - [value]="value" + [value]="value!=undefined?value:''" disabled /> - + diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts index 7300417686..84dd884d1f 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/popover-input/ui-element-popover-input.component.ts @@ -1,4 +1,4 @@ -import {Component, ViewChild, ElementRef} from '@angular/core'; +import {Component, ViewChild, ElementRef, Input} from '@angular/core'; import {UiElementBase, UiElementBaseInterface} from "../ui-element-base.component"; import {ButtonsModelMap, ButtonModel} from "app/models"; import { PopoverContentComponent } from "app/ng2/components/popover/popover-content.component" @@ -10,7 +10,6 @@ import { PopoverComponent } from "app/ng2/components/popover/popover.component" styleUrls: ['./ui-element-popover-input.component.less'] }) export class UiElementPopoverInputComponent extends UiElementBase implements UiElementBaseInterface { - @ViewChild('textArea') textArea: ElementRef; @ViewChild('popoverForm') popoverContentComponent: PopoverContentComponent; diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts index b60271f6f0..fa2be1048c 100644 --- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts +++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/ui-element-base.component.ts @@ -25,6 +25,7 @@ export class UiElementBase { protected type: string; protected value: any; protected pattern: any; + protected readonly:boolean; constructor() { //this.control = new FormControl('', [Validators.required]); diff --git a/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less index c1341b8dcf..afed54672c 100644 --- a/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less +++ b/catalog-ui/src/app/ng2/components/filter-properties-assignment/filter-properties-assignment.component.less @@ -6,6 +6,13 @@ form{ &:not(:last-child){ border-bottom: solid 1px @main_color_o; } + input{ + &::-webkit-input-placeholder { font-style: italic; } /* Safari, Chrome and Opera */ + &:-moz-placeholder { font-style: italic; } /* Firefox 18- */ + &::-moz-placeholder { font-style: italic; } /* Firefox 19+ */ + &:-ms-input-placeholder { font-style: italic; } /* IE 10+ */ + &:-ms-input-placeholder { font-style: italic; } /* Edge */ + } } /deep/ [ng-reflect-checked="true"]{ /deep/ .checkbox-label-content{ @@ -16,7 +23,7 @@ form{ .open-filter-button{ cursor: pointer; - width: 25px; + width: 32px; height: 34px; display: inline-block; &.open{ @@ -29,6 +36,7 @@ form{ } .filter-icon{ top: 8px; + right: 2px; position: relative; } } 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 new file mode 100644 index 0000000000..7fdd95b304 --- /dev/null +++ b/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.html @@ -0,0 +1,3 @@ + + Are you sure you want to delete this input? + 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 new file mode 100644 index 0000000000..24c37b5636 --- /dev/null +++ b/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.ts @@ -0,0 +1,38 @@ +/** + * 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 = new EventEmitter(); + @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 e7801b82cf..fb6b04013f 100644 --- a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html +++ b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html @@ -1,4 +1,5 @@
+
Property Name
Type
@@ -7,31 +8,39 @@
No data to display
-
-
- {{input.name}} - -
-
{{input.type | contentAfterLastDot}}
-
{{input.schema && input.schema.property && input.schema.property.type ? (input.schema.property.type | contentAfterLastDot) : ''}}
-
- - -
- +
+
+
+
{{input.name}}
+ +
+
+
+ {{input.type | contentAfterLastDot}} +
+
+
{{input.schema && input.schema.property && input.schema.property.type ? (input.schema.property.type | contentAfterLastDot) : ''}}
+
+ + +
+ +
-
+
+ diff --git a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.less b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.less new file mode 100644 index 0000000000..93f96470bc --- /dev/null +++ b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.less @@ -0,0 +1,178 @@ + +@import './../../../../assets/styles/variables.less'; + +:host /deep/ input { width:100%;} + +.properties-table { + display:flex; + flex-direction:column; + flex: 1; + height:100%; + text-align:left; + + dynamic-property { + width:100%; + } + + /deep/ .dynamic-property-row { + border-top:solid #d2d2d2 1px; + } + + /deep/ dynamic-property dynamic-property:first-of-type .dynamic-property-row:not(.with-top-border) { + border-top: none; + } + + .table-header { + font-weight:bold; + border-top: #d2d2d2 solid 1px; + background-color: #eaeaea; + + .valueCol { + justify-content: flex-start; + padding: 5px; + } + } + .table-header, .table-row { + display: flex; + flex-direction:row; + flex: 0 0 auto; + } + + .table-body { + display:flex; + flex-direction: column; + overflow-y:auto; + flex: 1; + + .no-data { + border: #d2d2d2 solid 1px; + border-top:none; + text-align: center; + height: 100%; + padding: 20px; + } + /deep/.selected{ + background-color: #e6f6fb; + color: #009fdb; + } + } + + .table-rows-header { + font-size:16px; + flex:1; + border: #d2d2d2 solid 1px; + border-top:none; + padding: 5px; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + background-color: @tlv_color_v; + } + + .table-row { + &:hover { + background-color:#f8f8f8; cursor:pointer; + } + + &:last-child { + flex: 1 0 auto; + } + .selected-row { + background-color:#e6f6fb; + } + } + .cut-inner-long-text{ + text-overflow: ellipsis; + overflow: hidden; + } + .table-cell { + font-size:13px; + flex:1; + border: #d2d2d2 solid 1px; + border-right:none; + border-top:none; + padding: 5px; + text-overflow: ellipsis; + white-space: nowrap; + + + &:last-child { + border-right:#d2d2d2 solid 1px; + } + &.col1 { + flex: 0 0 300px; + max-width:300px; + display: flex; + justify-content: space-between; + + .property-name { + flex: 1; + } + + .property-description-icon { + float: right; + margin-top: 4px; + margin-left: 5px; + flex: 0 0 auto; + } + } + &.col2 { + flex: 0 0 150px; + max-width:150px; + } + + &.col3 { + flex:0 0 120px; + max-width:120px; + } + + &.valueCol { + flex: 1 0 auto; + min-width: 350px; + display: flex; + justify-content: flex-end; + padding: 0px; + + .value-input { + flex: 1; + max-height: 24px; + border: none; + background-color: inherit; + + &:focus, &:active { + border:none; + outline:none; + } + } + + .delete-btn { + flex: 0 0 auto; + } + + .delete-button-container { + max-height: 24px; + } + + &.inner-table-container { + padding: 0px; + + .delete-button-container { + padding: 3px 5px 0 0 ; + } + } + } + + &.input-value-col { + padding: 5px; + } + + + } + + .filtered { + /deep/ .checkbox-label-content{ + background-color: yellow; + } + } + +} 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 ea01edf043..83c0bda991 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 @@ -1,20 +1,25 @@ /** * Created by rc2122 on 5/4/2017. */ -import {Component, Input, Output, EventEmitter} from "@angular/core"; +import {Component, Input, Output, EventEmitter, ViewChild} from "@angular/core"; import {InputFEModel} from "app/models"; +import {ConfirmationDeleteInputComponent} from "./confirmation-delete-input/confirmation-delete-input.component"; @Component({ selector: 'inputs-table', templateUrl: './inputs-table.component.html', - styleUrls: ['../properties-table/properties-table.component.less'] + styleUrls: ['../inputs-table/inputs-table.component.less'] }) export class InputsTableComponent { @Input() inputs: Array; - + @Input() readonly:boolean; + @Input() isLoading:boolean; @Output() inputValueChanged: EventEmitter = new EventEmitter(); @Output() deleteInput: EventEmitter = new EventEmitter(); + @ViewChild ('deleteInputConfirmation') deleteInputConfirmation:ConfirmationDeleteInputComponent; + + selectedInputToDelete:InputFEModel; constructor (){ } @@ -23,11 +28,14 @@ export class InputsTableComponent { this.inputValueChanged.emit(input); }; - onDeleteInput = (input) => { - this.deleteInput.emit(input); - } - + onDeleteInput = () => { + this.deleteInput.emit(this.selectedInputToDelete); + }; + openDeleteModal = (input:InputFEModel) => { + this.selectedInputToDelete = input; + this.deleteInputConfirmation.openModal(); + } } diff --git a/catalog-ui/src/app/ng2/components/loader/loader.component.html b/catalog-ui/src/app/ng2/components/loader/loader.component.html new file mode 100644 index 0000000000..0e13cee674 --- /dev/null +++ b/catalog-ui/src/app/ng2/components/loader/loader.component.html @@ -0,0 +1,5 @@ +
+
+
+
+ diff --git a/catalog-ui/src/app/ng2/components/loader/loader.component.less b/catalog-ui/src/app/ng2/components/loader/loader.component.less new file mode 100644 index 0000000000..054b6021a1 --- /dev/null +++ b/catalog-ui/src/app/ng2/components/loader/loader.component.less @@ -0,0 +1,75 @@ +@import '../../../../assets/styles/variables'; +.tlv-loader-back { + background-color: @main_color_p; + position: fixed; + top: 50px; + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + opacity: 0.5; +} + +.tlv-loader-relative { position: absolute; top: 0;} + +.tlv-loader { + z-index: 10002; +} + +@keyframes fadein { + from { opacity: 0; } + to { opacity: 0.8; } +} + +/* Firefox < 16 */ +@-moz-keyframes fadein { + from { opacity: 0; } + to { opacity: 0.8; } +} + +/* Safari, Chrome and Opera > 12.1 */ +@-webkit-keyframes fadein { + from { opacity: 0; } + to { opacity: 0.8; } +} + +/* Internet Explorer */ +@-ms-keyframes fadein { + from { opacity: 0; } + to { opacity: 0.8; } +} + +/* Opera < 12.1 */ +@-o-keyframes fadein { + from { opacity: 0; } + to { opacity: 0.8; } +} + +@keyframes fadeout { + from { opacity: 0.8; } + to { opacity: 0; } +} + +/* Firefox < 16 */ +@-moz-keyframes fadeout { + from { opacity: 0.8; } + to { opacity: 0; } +} + +/* Safari, Chrome and Opera > 12.1 */ +@-webkit-keyframes fadeout { + from { opacity: 0.8; } + to { opacity: 0; } +} + +/* Internet Explorer */ +@-ms-keyframes fadeout { + from { opacity: 0.8; } + to { opacity: 0; } +} + +/* Opera < 12.1 */ +@-o-keyframes fadeout { + from { opacity: 0.8; } + to { opacity: 0; } +} diff --git a/catalog-ui/src/app/ng2/components/loader/loader.component.ts b/catalog-ui/src/app/ng2/components/loader/loader.component.ts new file mode 100644 index 0000000000..4d90b2853d --- /dev/null +++ b/catalog-ui/src/app/ng2/components/loader/loader.component.ts @@ -0,0 +1,92 @@ +/** + * Created by rc2122 on 6/6/2017. + */ +import {Component, Input, ElementRef, Renderer, SimpleChanges} from "@angular/core"; +@Component({ + selector: 'loader', + templateUrl: './loader.component.html', + styleUrls: ['./loader.component.less'] +}) +export class LoaderComponent { + + @Input() display:boolean; + @Input() size:string;// small || medium || large + @Input() elementSelector:string; // required if is relative true + @Input() relative:boolean; + + interval; + + constructor (private el: ElementRef, private renderer: Renderer){ + } + + ngOnInit() { + + if (this.elementSelector) { + let elemParent = angular.element(this.elementSelector); + let positionStyle:string = elemParent.css('position'); + this.setStyle(positionStyle); + } + + if (this.relative === true) { + let positionStyle:string = this.el.nativeElement.parentElement.style.position; + this.setStyle(positionStyle); + } + if (!this.size) { + this.size = 'large'; + } + } + + ngOnDestroy(){ + clearInterval(this.interval); + } + + calculateSizesForFixPosition = (positionStyle:string):void => { + // This is problematic, I do not want to change the parent position. + // set the loader on all the screen + let parentLeft = this.el.nativeElement.parentElement.offsetLeft; + let parentTop = this.el.nativeElement.parentElement.offsetTop; + let parentWidth = this.el.nativeElement.parentElement.offsetWidth; + let parentHeight = this.el.nativeElement.parentElement.offsetHeight; + this.renderer.setElementStyle(this.el.nativeElement, 'position', positionStyle); + this.renderer.setElementStyle(this.el.nativeElement, 'top', parentTop); + this.renderer.setElementStyle(this.el.nativeElement, 'left', parentLeft); + this.renderer.setElementStyle(this.el.nativeElement, 'width', parentWidth); + this.renderer.setElementStyle(this.el.nativeElement, 'height', parentHeight); + }; + + setStyle = (positionStyle:string):void => { + + switch (positionStyle) { + case 'absolute': + case 'fixed': + // The parent size is not set yet, still loading, so need to use interval to update the size. + this.interval = window.setInterval(()=> { + this.calculateSizesForFixPosition(positionStyle); + }, 2000); + break; + default: + // Can change the parent position to relative without causing style issues. + this.renderer.setElementStyle(this.el.nativeElement.parentElement,'position', 'relative'); + break; + } + }; + + ngOnChanges(changes: SimpleChanges) { + if(changes.display){ + this.changeLoaderDisplay(false); + if ( this.display ) { + window.setTimeout(():void => { + this.changeLoaderDisplay(true); + }, 500); + } else { + window.setTimeout(():void => { + this.changeLoaderDisplay(false); + }, 0); + } + } + } + + changeLoaderDisplay = (display:boolean):void => { + this.renderer.setElementStyle(this.el.nativeElement, 'display', display ? 'block' : 'none'); + } +} diff --git a/catalog-ui/src/app/ng2/components/modal/modal.component.html b/catalog-ui/src/app/ng2/components/modal/modal.component.html new file mode 100644 index 0000000000..4882449596 --- /dev/null +++ b/catalog-ui/src/app/ng2/components/modal/modal.component.html @@ -0,0 +1,18 @@ +
+
+
+ {{ title }} + +
+
+ +
+ +
+
+ diff --git a/catalog-ui/src/app/ng2/components/modal/modal.component.less b/catalog-ui/src/app/ng2/components/modal/modal.component.less new file mode 100644 index 0000000000..a35f829e6a --- /dev/null +++ b/catalog-ui/src/app/ng2/components/modal/modal.component.less @@ -0,0 +1,115 @@ +@import '../../../../assets/styles/variables'; +@import '../../../../assets/styles/mixins'; +@import '../../../../assets/styles/sprite-old'; +/deep/ modal { + display: none; + + .custom-modal { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1000; + overflow: auto; + margin: auto; + display: flex; + align-items: center; + + .ng2-modal-content { + background: #fff; + width: 100%; + box-shadow: 0 5px 15px rgba(0,0,0,.5); + border-radius: 4px; + .ng2-modal-body{ + padding: 20px; + } + + .ng2-modal-header{ + .m_18_m; + font-weight: bold; + -webkit-box-flex: 1; + -ms-flex-positive: 1; + flex-grow: 1; + height: 50px; + line-height: 50px; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + text-align: left; + border-bottom: solid 1px @main_color_o; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + margin: 0px 20px; + .title{ + -webkit-box-flex: 999; + -ms-flex-positive: 999; + flex-grow: 999; + } + .close-button{ + .sprite; + .sprite.x-btn-black; + cursor: pointer; + } + } + + .ng2-modal-footer{ + background-color: @tlv_color_t; + padding: 17px 30px; + clear: both; + -webkit-box-flex: 1; + -ms-flex-positive: 1; + flex-grow: 1; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + -webkit-box-pack: end; + -ms-flex-pack: end; + justify-content: flex-end; + border-radius: 4px; + button{ + margin: 0 12px 0 6px; + } + } + } + } + + .modal-background { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + background-color: #000; + opacity: 0.5; + z-index: 900; + } +} + +.xl { + width: 1200px; +} + +.l { + width: 875px; +} + +.md { + width: 650px; +} + +.sm { + width: 552px; +} + +.xsm { + width: 432px; +} + +body.modal-open { + overflow: hidden; +} diff --git a/catalog-ui/src/app/ng2/components/modal/modal.component.ts b/catalog-ui/src/app/ng2/components/modal/modal.component.ts new file mode 100644 index 0000000000..4a00871b21 --- /dev/null +++ b/catalog-ui/src/app/ng2/components/modal/modal.component.ts @@ -0,0 +1,46 @@ +/** + * Created by rc2122 on 6/1/2017. + */ +import { Component, ElementRef, Input, OnInit, OnDestroy } from '@angular/core'; +import * as $ from 'jquery'; +import {ButtonsModelMap} from "app/models/button"; + +@Component({ + selector: 'modal', + templateUrl: './modal.component.html', + styleUrls:['modal.component.less'] +}) + +export class ModalComponent implements OnInit, OnDestroy { + @Input() size: string; 'xl|l|md|sm|xsm' + @Input() title: string; + @Input() public buttons:ButtonsModelMap; + private modalElement: JQuery; + private buttonsNames:Array; + + 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 { + this.modalElement.remove(); + } + + open(): void { + this.modalElement.show(); + $('body').addClass('modal-open'); + } + + close(): void { + this.modalElement.hide(); + $('body').removeClass('modal-open'); + } +} diff --git a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html deleted file mode 100644 index 6e7d4e882b..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.html +++ /dev/null @@ -1,24 +0,0 @@ - -
-
- -
- -
-
-
-
-
- {{propertyObj.type | contentAfterLastDot }} - V -
-
-
-
- {{propertyObj.name}} -
-
-
-
-
- diff --git a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less deleted file mode 100644 index 3102c5ceb8..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.less +++ /dev/null @@ -1,35 +0,0 @@ -.derived-property-row { - display:flex; - flex-direction:row; - position:relative; - border-top: #d2d2d2 solid 1px; - - &:first-child { - border-top:none; - } - .table-cell { - flex: 0 0 50%; - padding:5px; - position:relative; - text-overflow: ellipsis; - white-space: nowrap; - - &:first-child { - border-right:#d2d2d2 solid 1px; - overflow:hidden; - } - span.expand-icon { - position: absolute; - right: 10px; - transition: 200ms transform ease-in-out; - } - span.expand-icon.expanded { - transform: rotate(-180deg); - } - } -} -.filtered { - /deep/ .checkbox-label-content{ - background-color: yellow; - } -} diff --git a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts deleted file mode 100644 index 16f069a685..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/derived-property/derived-property.component.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Created by rc2122 on 4/20/2017. - */ -import {Component, Input, Output, EventEmitter} from "@angular/core"; -import { DerivedFEProperty, DerivedPropertyType} from "app/models"; -import {PropertiesService} from "../../../services/properties.service"; - -@Component({ - selector: 'derived-property', - templateUrl: './derived-property.component.html', - styleUrls: ['./derived-property.component.less'] -}) -export class DerivedPropertyComponent { - - derivedPropertyTypes = DerivedPropertyType; //http://stackoverflow.com/questions/35835984/how-to-use-a-typescript-enum-value-in-an-angular2-ngswitch-statement - - @Input() propertyObj: DerivedFEProperty; - @Input() propertyNameSearchText: string; - @Input() expanded: boolean; - @Output() valueChanged: EventEmitter = new EventEmitter(); - @Output() expandChild: EventEmitter = new EventEmitter(); - @Output() selectProperty: EventEmitter = new EventEmitter(); - - - constructor ( private propertiesService:PropertiesService){ - } - - - propValueChanged = () => { - this.valueChanged.emit(this.propertyObj); - }; - - expandChildById = (id: string) => { - this.expandChild.emit(id); - } - - checkedChange = (isChecked:boolean) => { - this.selectProperty.emit(isChecked); - } - - addRows = (flatProperty: DerivedFEProperty): void => { - console.log("ADDING A ROW OF TYPE " + flatProperty.type); - console.log(flatProperty); - } - -} 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 17e4002ae5..d6ee568c0c 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 @@ -1,66 +1,65 @@
- + -
- +
{{property.name}}
+
+ +
- - -
+ + +
- - - -
- {{property.type | contentAfterLastDot }} -
-
- -
-
-
-
- {{property.schema.property.type | contentAfterLastDot }} -
-
- - -
- - V + +
{{property.type | contentAfterLastDot }}
+
{{property.schema.property.type | contentAfterLastDot }}
+
+ +
+
+ + + + + V
- - - + +
+ - +
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 53cde3035a..cb7cd39640 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,40 +1,40 @@ +.flat-children-container { + dynamic-property:first-child .dynamic-property-row:not(.with-top-border) { + border-top:none; + } + .dynamic-property-row { + border-top: solid 1px #CCC; + } +} .dynamic-property-row { display:flex; flex-direction:row; - position:relative; - + align-items: center; + .table-cell { - flex: 1 0 50%; + flex: 1; padding:5px; - position:relative; text-overflow: ellipsis; white-space: nowrap; - + overflow:hidden; + min-height:32px; - &.full-width { - border-right:none; - flex: 0 0 100%; - } - - &:first-child:not(:only-child) { + &:first-child { + flex: 0 0 50%; border-right:#d2d2d2 solid 1px; - overflow:hidden; + + + &:only-of-type { + flex: 1 1 100%; + border-right:none; + } } - - } - span.delete-item-icon{ - position: absolute; - right: 25px; - top: 10px; } - span.add-item-icon { - float:right; + .property-icon { + flex: 0 0 auto; } span.expand-icon { - position: absolute; - top:6px; - right: 10px; transition: 200ms transform ease-in-out; } span.expand-icon.expanded { 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 0ca93a773f..1c7fbfac7a 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 @@ -3,7 +3,6 @@ import { PropertyBEModel, PropertyFEModel, DerivedFEProperty, DerivedPropertyTyp import { PROPERTY_DATA, PROPERTY_TYPES } from 'app/utils'; import { PropertiesUtils } from "app/ng2/pages/properties-assignment/properties.utils"; import { DataTypeService } from "../../../services/data-type.service"; -import { UUID } from "angular2-uuid"; @Component({ @@ -17,64 +16,33 @@ export class DynamicPropertyComponent { propType: DerivedPropertyType; propPath: string; isPropertyFEModel: boolean; - mapOfIDsAndKeys: Map = new Map(); //used for map and list + childrenCount: number; - childrenCanBeDeclared: boolean; @Input() canBeDeclared: boolean; @Input() property: PropertyFEModel | DerivedFEProperty; - @Input() propChildren: Array; @Input() expandedChildId: string; @Input() selectedPropertyId: string; + @Input() propertyNameSearchText: string; + @Input() readonly: boolean; @Output() valueChanged: EventEmitter = new EventEmitter(); @Output() expandChild: EventEmitter = new EventEmitter(); @Output() checkProperty: EventEmitter = new EventEmitter(); @Output() deleteItem: EventEmitter = new EventEmitter(); @Output() clickOnPropertyRow: EventEmitter = new EventEmitter(); + @Output() mapKeyChanged: EventEmitter = new EventEmitter(); + @Output() addChildPropsToParent: EventEmitter> = new EventEmitter>(); + constructor(private propertiesUtils: PropertiesUtils, private dataTypeService: DataTypeService) { } ngOnInit() { this.isPropertyFEModel = this.property instanceof PropertyFEModel; - if (this.property instanceof PropertyFEModel) { - this.propType = this.getDerivedPropertyType(this.property.type); - this.propPath = this.property.name; - } else { - this.propType = this.property.derivedDataType; - this.propPath = this.property.propertiesName; - } - - this.childrenCanBeDeclared = this.canBeDeclared && this.propType != this.derivedPropertyTypes.MAP && this.propType != this.derivedPropertyTypes.LIST; - - if (this.propType == this.derivedPropertyTypes.LIST || this.propType == this.derivedPropertyTypes.MAP) { - this.initializeValues(); - } - + this.propType = this.property.derivedDataType; + this.propPath = (this.property instanceof PropertyFEModel) ? this.property.name : this.property.propertiesName; } - initializeValues = () => { - let tempValue: any; - if (this.property.value) { - tempValue = JSON.parse(this.property.value); - if (!_.isEmpty(tempValue)) { - tempValue.forEach((element, key) => { - let newChildID: string = this.createNewChildProperty(JSON.stringify(element)); - this.mapOfIDsAndKeys[newChildID] = key; - console.log(this.mapOfIDsAndKeys); - }); - } - } - //this.pseudoChildren = []; - //this.valueObjRef = []; - //TODO: generate necessary elements for existing values here - // if (this.propType == this.derivedPropertyTypes.LIST) { - // this.valueObjRef = (this.property.value) ? JSON.parse(this.property.value) : []; - // } else if (this.propType == this.derivedPropertyTypes.MAP) { - // this.valueObjRef = (this.property.value)? JSON.parse(this.property.value) : {}; - // } - console.log(this.property.value); - } onClickPropertyRow = (property, event) => { // Because DynamicPropertyComponent is recrusive second time the event is fire event.stopPropagation = undefined @@ -82,68 +50,106 @@ export class DynamicPropertyComponent { this.clickOnPropertyRow.emit(property); } - deleteListOrMapItem = (itemName: string) => { - this.propChildren = this.propChildren.filter(prop => prop.propertiesName.indexOf(itemName) != 0); //remove item and children; - } - - propValueChanged = (property) => { - console.log("property value change!! Prop type: " + property.type + " New value: " + property.value); - this.valueChanged.emit(property); - }; expandChildById = (id: string) => { this.expandedChildId = id; - this.expandChild.emit(id); + this.expandChild.emit(id); } checkedChange = (propName: string) => { this.checkProperty.emit(propName); } + hasChildren = (): number => { + return (this.property.valueObj && typeof this.property.valueObj == 'object') ? Object.keys(this.property.valueObj).length : 0; + } + createNewChildProperty = (): void => { + + let newProps: Array = this.propertiesUtils.createListOrMapChildren(this.property, "", null); + if (this.property instanceof PropertyFEModel) { + this.addChildProps(newProps, this.property.name); + } else { + this.addChildPropsToParent.emit(newProps); + } + } - addRows = (): void => { //from within the template, when creating empty item - let childPropId = this.createNewChildProperty(); - this.expandChildById(this.propPath + "#" + childPropId); + addChildProps = (newProps: Array, 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 + this.expandChildById(newProps[0].propertiesName); + } } - createNewChildProperty = (value?:string):string => { - let propUUID:string = UUID.UUID(); - let newProp: DerivedFEProperty; - if (this.propType == this.derivedPropertyTypes.LIST) { //for list - create new prop of schema type - newProp = new DerivedFEProperty(propUUID, this.propPath, this.property.schema.property.type, value, true); - } else { //for map - create new prop of type map, with schema, but with flag that its a child - newProp = new DerivedFEProperty(propUUID, this.propPath, this.property.type, value, true, this.property.schema); + childValueChanged = (property: DerivedFEProperty) => { //value of child property changed + + if (this.property instanceof PropertyFEModel) { // will always be the case + let parentNames = this.getParentNamesArray(property.propertiesName, []); + if (parentNames.length) { + _.set(this.property.valueObj, parentNames.join('.'), property.valueObj); + } + console.log(parentNames); + this.valueChanged.emit(this.property.name); } + } + deleteListOrMapItem = (item: DerivedFEProperty) => { + if (this.property instanceof PropertyFEModel) { + this.removeValueFromParent(item); + this.property.flattenedChildren.splice(this.property.getIndexOfChild(item.propertiesName), this.property.getCountOfChildren(item.propertiesName)); + this.expandChildById(item.propertiesName); + } + } - this.propChildren = this.propChildren || []; - this.propChildren.push(newProp); + removeValueFromParent = (item: DerivedFEProperty, replaceKey?: string) => { + 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; + } + delete itemParent.valueObj[oldKey]; + } else { + let itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName); + itemParent.valueObj.splice(itemIndex, 1); + } - //if it's a complex type, add children properties - if (!this.property.schema.property.isSimpleType) { - let schemaDataType: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(this.property.schema.property.type); - this.dataTypeService.getDerivedDataTypeProperties(schemaDataType, this.propChildren, newProp.propertiesName); - this.propertiesUtils.assignValuesRecursively(JSON.parse(value), this.propChildren, newProp.propertiesName); - console.log(JSON.stringify(this.propChildren)); + if (itemParent instanceof PropertyFEModel) { //direct child + this.valueChanged.emit(this.property.name); + } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc) + this.childValueChanged(itemParent); + } } + } - return propUUID; - } + getParentNamesArray = (parentPropName: string, parentNames?: Array): Array => { + if (this.property instanceof PropertyFEModel) { + if (parentPropName.indexOf("#") == -1) { return parentNames; } //finished recursing parents. return - //TODO: remove this and move to somewhere central!! (or make all properties be the same type...) - getDerivedPropertyType = (type) => { - if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) > -1) { - return DerivedPropertyType.SIMPLE; - } else if (type == PROPERTY_TYPES.LIST) { - return DerivedPropertyType.LIST; - } else if (type == PROPERTY_TYPES.MAP) { - return DerivedPropertyType.MAP; - } else { - return DerivedPropertyType.COMPLEX; + let parentProp: DerivedFEProperty = this.property.flattenedChildren.find(prop => prop.propertiesName === parentPropName); + let nameToInsert: string = parentProp.name; + + if (parentProp.isChildOfListOrMap) { + if (parentProp.derivedDataType == DerivedPropertyType.MAP) { + nameToInsert = parentProp.mapKey; + } else { //LIST + let siblingProps = this.property.flattenedChildren.filter(prop => prop.parentName == parentProp.parentName).map(prop => prop.propertiesName); + nameToInsert = siblingProps.indexOf(parentProp.propertiesName).toString(); + } + } + + parentNames.splice(0, 0, nameToInsert); //add prop name to array + return this.getParentNamesArray(parentProp.parentName, parentNames); //continue recursing + } } + } diff --git a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html deleted file mode 100644 index a251d33649..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.html +++ /dev/null @@ -1,33 +0,0 @@ -
-
-
-
- -
- - -
-
-
- - -
diff --git a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less deleted file mode 100644 index 7c4d90a38d..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.less +++ /dev/null @@ -1,3 +0,0 @@ -.simple-list-item{ - position: relative; -} diff --git a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts deleted file mode 100644 index 96f8c680a2..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/list-property/list-property.component.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Created by rc2122 on 4/23/2017. - */ -import {Component, Input, Output, EventEmitter} from "@angular/core"; -import { PropertyFEModel} from "app/models"; -import {PropertiesService} from "app/ng2/services/properties.service"; -import { ContentAfterLastDotPipe } from "app/ng2/pipes/contentAfterLastDot.pipe"; -import {UUID} from "angular2-uuid"; -import {ComponentType} from "app/utils"; - -@Component({ - selector: 'list-property', - templateUrl: './list-property.component.html', - styleUrls: ['../properties-value-inner-table/properties-value-inner-table.component.less', './list-property.component.less'] -}) -export class ListPropertyComponent { - - @Input() property: PropertyFEModel; - @Input() selectedPropertyId: string; - @Input() propertyNameSearchText:string; - - @Output() valueChanged: EventEmitter = new EventEmitter(); - @Output() selectChildProperty: EventEmitter = new EventEmitter(); - - constructor ( private propertiesService:PropertiesService, private contentAfterLastDotPipe:ContentAfterLastDotPipe ){ - } - - propValueChanged = () => { - this.valueChanged.emit(this.property); - }; - - onChildPropertySelected = (property) => { - this.selectChildProperty.emit(property); - }; - - getNumber = (valueObjectRef: any): Array => { - let num: number = (valueObjectRef) ? valueObjectRef.length : 0; - return new Array(num); - } - - createNewChildProperty = ():void => { - let newProperty: PropertyFEModel = new PropertyFEModel(this.contentAfterLastDotPipe.transform(this.property.schema.property.type), - this.property.schema.property.type, - UUID.UUID(), - this.property, - this.property.valueObjectRef[this.property.childrenProperties.length] - ); - this.propertiesService.createPropertiesTreeForProp(newProperty); - this.property.childrenProperties.push(newProperty); - } - - addListItem = ():void => { - this.property.valueObjectRef = this.property.valueObjectRef || []; - this.property.childrenProperties = this.property.childrenProperties || []; - if (this.property.schema.property.isSimpleType){ - if( this.property.valueObjectRef.indexOf("") == -1 ) {//prevent insert multiple empty simple type items to list - this.property.valueObjectRef.push(""); - } - }else{ - this.property.valueObjectRef[this.property.childrenProperties.length] = {}; - this.property.childrenProperties = this.property.childrenProperties || []; - this.createNewChildProperty(); - this.valueChanged.emit(this.property); - } - } - - deleteListItem = (indexInList:number):void => { - this.property.valueObjectRef.splice(indexInList, 1); - if(this.property.childrenProperties){ - this.property.childrenProperties.splice(indexInList, 1); - } - if (!this.property.valueObjectRef.length) {//only when user removes all items from list - put the default - if ( this.property.defaultValue ) { - angular.copy(JSON.parse(this.property.defaultValue), this.property.valueObjectRef); - if (this.property.schema.property.isDataType){ - _.forEach(this.property.valueObjectRef, () => { - this.createNewChildProperty(); - }); - } - } - } - this.valueChanged.emit(this.property); - } - -} diff --git a/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html deleted file mode 100644 index e1975175a8..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.html +++ /dev/null @@ -1,38 +0,0 @@ -
-
-
- - - - diff --git a/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts deleted file mode 100644 index d62d0b94e3..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/map-property/map-property.component.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Created by rc2122 on 4/24/2017. - */ -/** - * Created by rc2122 on 4/23/2017. - */ -import {Component, Input, Output, EventEmitter} from "@angular/core"; -import { PropertyFEModel} from "app/models"; -import { PropertiesService } from "../../../services/properties.service"; -import {ComponentType} from "app/utils"; -import {UUID} from "angular2-uuid"; - -@Component({ - selector: 'map-property', - templateUrl: './map-property.component.html', - styleUrls: ['../properties-value-inner-table/properties-value-inner-table.component.less'] -}) -export class MapPropertyComponent { - - @Input() property: PropertyFEModel; - @Input() selectedPropertyId: string; - @Input() propertyNameSearchText:string; - - @Output() valueChanged: EventEmitter = new EventEmitter(); - @Output() selectChildProperty: EventEmitter = new EventEmitter(); - - constructor ( private propertiesService:PropertiesService){ - } - - mapKeys:Array; - - ngOnInit() { - this.mapKeys = Object.keys(this.property.valueObjectRef); - } - - propValueChanged = () => { - this.valueChanged.emit(this.property); - }; - - onChildPropertySelected = (property) => { - this.selectChildProperty.emit(property); - }; - - getNumber = (num:number):Array => { - return new Array(num); - } - - createNewChildProperty = (mapKey:string):void => { - - let newProperty: PropertyFEModel = new PropertyFEModel(mapKey, - this.property.schema.property.type, - UUID.UUID(), this.property, - this.property.valueObjectRef[mapKey]); - this.propertiesService.createPropertiesTreeForProp(newProperty); - this.property.childrenProperties = this.property.childrenProperties || []; - this.property.childrenProperties.push(newProperty); - } - - //get: new key and the index of this item in the map - //This method checks if the new key isn't exist already in the map and update the object and the children array with the new key - changeKeyOfMap = (newKey:string, index:number):void => { - //let fieldName:string = "mapKey" + this.property.treeNodeId + index; - let oldKey:string = Object.keys(this.property.valueObjectRef)[index]; - let existsKeyIndex:number = Object.keys(this.property.valueObjectRef).indexOf(newKey); - if (existsKeyIndex > -1 && existsKeyIndex != index) { - //error for exists key validation - } else { - //remove error for exists key validation and if the form is valid - update the map object - let newObj = {}; - angular.forEach(this.property.valueObjectRef,function(value:any,key:string){ - if(key == oldKey){ - newObj[newKey] = value; - }else{ - newObj[key] = value; - } - }); - this.property.valueObjectRef = newObj; - this.property.parent.valueObjectRef[this.property.name] = this.property.valueObjectRef;//in order to prevent break ref - if(this.property.childrenProperties){ - this.property.childrenProperties[index].name = newKey;//update this property childrenProperties with the new key - } - } - } - - //get: index of the item in the map - //This method removes item from map. - deleteMapItem = (index:number):void=> { - delete this.property.valueObjectRef[this.mapKeys[index]]; - this.mapKeys.splice(index, 1); - if(this.property.childrenProperties){ - this.property.childrenProperties.splice(index, 1); - } - if (!this.mapKeys.length) {//only when user removes all pairs of key-value fields - put the default - if (this.property.defaultValue) { - angular.copy(JSON.parse(this.property.defaultValue), this.property.valueObjectRef); - this.mapKeys = Object.keys(this.property.valueObjectRef); - if (this.property.schema.property.isDataType){ - angular.forEach(this.property.valueObjectRef, (value, key) => { - this.createNewChildProperty(key); - }, this); - } - } - } - this.valueChanged.emit(this.property); - } - - //This method inserts new empty item to map - addMapItemFields = ():void => { - this.property.valueObjectRef = this.property.valueObjectRef || {}; - if (this.property.schema.property.isSimpleType){ - this.property.valueObjectRef[''] = null; - }else{ - if(!this.property.valueObjectRef['']){ - this.property.valueObjectRef[''] = {}; - this.createNewChildProperty(''); - } - } - this.mapKeys = Object.keys(this.property.valueObjectRef); - } -} - diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html index 3ab47074e7..426ae3ab23 100644 --- a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html +++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html @@ -1,6 +1,5 @@ - -
+
Property Name
Type
@@ -13,16 +12,27 @@
{{instanceName | contentAfterLastDot}}
-
-
- - +
+ +
+
+ +
+ {{property.name}} +
+
+ +
+
+
+ {{property.type | contentAfterLastDot}} +
-
{{property.type | contentAfterLastDot}}
{{property.schema && property.schema.property && property.schema.property.type ? (property.schema.property.type | contentAfterLastDot) : ''}}
@@ -32,7 +42,8 @@ [canBeDeclared]="true" [property]="property" [expandedChildId]="property.expandedChildPropertyId" - [propChildren]="property.flattenedChildren | filterChildProperties : property.expandedChildPropertyId" + [propertyNameSearchText]="propertyNameSearchText" + [readonly]="readonly" (valueChanged)="propValueChanged(property);" (expandChild)="property.updateExpandedChildPropertyId($event)" (clickOnPropertyRow)="onClickPropertyInnerRow($event, instanceName)" @@ -42,94 +53,8 @@
- - -
- - - - diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less index de080dfdc9..bb019a768b 100644 --- a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less +++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.less @@ -10,38 +10,17 @@ height:100%; text-align:left; - - .child-property-container { - display:flex; - flex-direction:column; - - &.table-cell { - padding:0; - } - - .child-property-row { - border-bottom: #d2d2d2 solid 1px; - &:last-child { - border-bottom:none; - } - } - } - - - derived-property, dynamic-property { - width:100%; - } - - /deep/ dynamic-property dynamic-property .dynamic-property-row { - border-top:solid #d2d2d2 1px; - } - - /deep/ dynamic-property dynamic-property:first-of-type .dynamic-property-row:not(.with-top-border) { - border-top: none; + .inner-cell-div{ + max-width: 100%; + text-overflow: ellipsis; + overflow: hidden; + height: 20px; } - - properties-value-inner-table { - width: 100%; + + .table-header, .table-row { + display: flex; + flex-direction:row; + flex: 0 0 auto; } .table-header { @@ -54,10 +33,17 @@ padding: 5px; } } - .table-header, .table-row { - display: flex; - flex-direction:row; - flex: 0 0 auto; + + .table-rows-header { + font-size:16px; + flex:1; + border: #d2d2d2 solid 1px; + border-top:none; + padding: 5px; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + background-color: @tlv_color_v; } .table-body { @@ -79,17 +65,6 @@ } } - .table-rows-header { - font-size:16px; - flex:1; - border: #d2d2d2 solid 1px; - border-top:none; - padding: 5px; - text-overflow: ellipsis; - white-space: nowrap; - overflow: hidden; - background-color: @tlv_color_v; - } .table-row { &:hover { @@ -102,6 +77,10 @@ .selected-row { background-color:#e6f6fb; } + } + .cut-inner-long-text{ + text-overflow: ellipsis; + overflow: hidden; } .table-cell { font-size:13px; @@ -112,7 +91,7 @@ padding: 5px; text-overflow: ellipsis; white-space: nowrap; - overflow: hidden; + display: flex; &:last-child { border-right:#d2d2d2 solid 1px; @@ -120,10 +99,24 @@ &.col1 { flex: 0 0 300px; max-width:300px; + display: flex; + justify-content: space-between; + + .property-name { + flex: 1; + display: flex; + max-width: 270px; + } .property-description-icon { float: right; margin-top: 4px; + margin-left: 5px; + flex: 0 0 auto; + } + + /deep/ .checkbox-container { + margin-right: 5px; } } &.col2 { @@ -137,46 +130,12 @@ } &.valueCol { - flex: 1 0 auto; + flex: 1; min-width: 350px; display: flex; justify-content: flex-end; padding: 0px; - - .value-input { - flex: 1; - max-height: 24px; - border: none; - background-color: inherit; - - &:focus, &:active { - border:none; - outline:none; - } - } - - .delete-btn { - flex: 0 0 auto; - } - - .delete-button-container { - max-height: 24px; - } - - &.inner-table-container { - padding: 0px; - - .delete-button-container { - padding: 3px 5px 0 0 ; - } - } } - - &.input-value-col { - padding: 5px; - } - - } .filtered { @@ -184,5 +143,9 @@ background-color: yellow; } } + + dynamic-property { + width:100%; + } } diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts index d5a9b40425..58214ca16b 100644 --- a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts +++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.ts @@ -2,8 +2,6 @@ import { Component, Input, Output, EventEmitter, SimpleChanges, ViewChild, Eleme import { trigger, state, style, transition, animate} from '@angular/core'; import {PropertyFEModel, DerivedFEProperty, DerivedPropertyType, InstanceFePropertiesMap} from "app/models"; import {PropertiesService} from "../../services/properties.service"; -// import { GroupByPipe } from 'app/ng2/pipes/groupBy.pipe'; -//import {PropertiesValueInnerTableComponent} from "./properties-table/properties-value-inner-table/properties-value-inner-table"; import { DynamicElementComponent } from 'app/ng2/components/dynamic-element/dynamic-element.component'; import { KeysPipe } from 'app/ng2/pipes/keys.pipe'; @@ -19,7 +17,10 @@ export class PropertiesTableComponent { @Input() selectedPropertyId: string; @Input() displayDeleteButton: boolean; @Input() propertyNameSearchText:string; - + @Input() searchTerm:string; + @Input() readonly:boolean; + @Input() isLoading:boolean; + @Output() valueChanged: EventEmitter = new EventEmitter(); @Output() selectPropertyRow: EventEmitter = new EventEmitter(); @Output() updateCheckedPropertyCount: EventEmitter = new EventEmitter(); @@ -50,6 +51,7 @@ export class PropertiesTableComponent { // Click on main row (row of propertyFEModel) onClickPropertyRow = (property:PropertyFEModel, instanceName:string, event?) => { //event && event.stopPropagation(); + this.selectedPropertyId = property.name; let propertyRowSelectedEvent:PropertyRowSelectedEvent = new PropertyRowSelectedEvent(property, instanceName); this.selectPropertyRow.emit(propertyRowSelectedEvent); }; @@ -72,14 +74,6 @@ export class PropertiesTableComponent { this.updateCheckedPropertyCount.emit(isChecked); } - putDefaultValueInEmptyProperty = (property:PropertyFEModel):void => { - property.value = property.value || property.defaultValue; - } - - // clickOnInstanceRow = (instanceName:string) =>{ - // this.selectInstanceRow.emit(instanceName); - // }; - } export class PropertyRowSelectedEvent { diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html deleted file mode 100644 index 61555cac50..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less deleted file mode 100644 index 1b7f6d4cd1..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.less +++ /dev/null @@ -1,71 +0,0 @@ -table { width:100%;} -tr {border-bottom: #d2d2d2 solid 1px;} -tr:last-child { border-bottom:none;} -td { border:none; padding:5px;} -td:first-child { border-right:#d2d2d2 solid 1px;} - -.prop-value{ - span { - position: absolute; - top: 5px; - right: 2px; - - &.delete-span { - right:20px; - } - - &.datatype-text { - position:static; - } - - } -} - -.add-data-row { - padding:5px; - text-align:right; - border-bottom: #d2d2d2 solid 1px; - - &:last-child { - border-bottom:none; - } -} -.table-inner-row { - display:flex; - flex-direction:row; - border-bottom: #d2d2d2 solid 1px; - flex: 0 0 100%; - position:relative; - - &:last-child { - border-bottom:none; - } - - .table-cell { - flex: 0 0 50%; - padding:5px; - position:relative; - text-overflow: ellipsis; - white-space: nowrap; - - &:first-child { - border-right:#d2d2d2 solid 1px; - overflow:hidden; - } - - - } - - .table-inner-container, .inner-table-container { - flex: 0 0 100%; - } -} -/deep/ map-property, /deep/ properties-value-inner-table, /deep/ list-property{ - width:100%; -} - -.filtered { - /deep/ .checkbox-label-content{ - background-color: yellow; - } -} diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts b/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts deleted file mode 100644 index 7d0b219ffe..0000000000 --- a/catalog-ui/src/app/ng2/components/properties-table/properties-value-inner-table/properties-value-inner-table.component.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Created by rc2122 on 4/20/2017. - */ -import {Component, Input, Output, EventEmitter} from "@angular/core"; -import {PropertyFEModel} from "app/models"; -import {PropertiesService} from "../../../services/properties.service"; - -@Component({ - selector: 'properties-value-inner-table', - templateUrl: './properties-value-inner-table.component.html', - styleUrls: ['./properties-value-inner-table.component.less'] -}) -export class PropertiesValueInnerTableComponent { - - @Input() property: PropertyFEModel; - @Input() selectedPropertyId: string; - @Input() propertyNameSearchText:string; - - @Output() selectChildProperty: EventEmitter = new EventEmitter(); - @Output() valueChanged: EventEmitter = new EventEmitter(); - - constructor ( private propertiesService:PropertiesService){ - } - - - onChildPropertySelected = (property) => { - this.selectChildProperty.emit(property); - }; - - propValueChanged = () => { - this.valueChanged.emit(this.property); - }; - - putDefaultValueInEmptyChildProperty = (childProp:PropertyFEModel):void => { - this.property.valueObjectRef[childProp.name] = this.property.valueObjectRef[childProp.name] || childProp.defaultValue; - } -} 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 6ef3e57678..b59ef9dbda 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 @@ -13,21 +13,20 @@ import { SearchFilterPipe } from "../../pipes/searchFilter.pipe"; import { FilterChildPropertiesPipe } from "../../pipes/filterChildProperties.pipe"; import { DataTypeService } from './../../services/data-type.service'; import { PropertiesService } from './../../services/properties.service'; +import { HierarchyNavService } from './../../services/hierarchy-nav.service'; import { PropertiesUtils } from './properties.utils'; import { PostsService } from "../../services/posts.service"; -import { PropertiesValueInnerTableComponent } from "./../../components/properties-table/properties-value-inner-table/properties-value-inner-table.component"; -import { ListPropertyComponent } from "./../../components/properties-table/list-property/list-property.component"; -import { MapPropertyComponent } from "./../../components/properties-table/map-property/map-property.component"; import { DynamicElementModule } from 'app/ng2/components/dynamic-element/dynamic-element.module'; import { DynamicPropertyComponent } from './../../components/properties-table/dynamic-property/dynamic-property.component'; -import { DerivedPropertyComponent } from './../../components/properties-table/derived-property/derived-property.component'; -// import {PopoverContentComponent} from "../../components/popover/popover-content.component" -// import {PopoverComponent} from "../../components/popover/popover.component" +import {ConfirmationDeleteInputComponent} from "app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component" import { PopoverModule } from "../../components/popover/popover.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" @NgModule({ declarations: [ @@ -40,14 +39,13 @@ import {TooltipModule} from "../../components/tooltip/tooltip.module"; SearchFilterPipe, FilterChildPropertiesPipe, HierarchyNavigationComponent, - PropertiesValueInnerTableComponent, - ListPropertyComponent, - MapPropertyComponent, - DerivedPropertyComponent, DynamicPropertyComponent, // PopoverContentComponent, // PopoverComponent, - FilterPropertiesAssignmentComponent + FilterPropertiesAssignmentComponent, + ModalComponent, + ConfirmationDeleteInputComponent, + LoaderComponent ], imports: [ BrowserModule, @@ -65,7 +63,7 @@ import {TooltipModule} from "../../components/tooltip/tooltip.module"; // PopoverContentComponent, // PopoverComponent ], - providers: [PropertiesService, PropertiesUtils, DataTypeService, PostsService, ContentAfterLastDotPipe, GroupByPipe, KeysPipe] + providers: [PropertiesService, HierarchyNavService, PropertiesUtils, DataTypeService, PostsService, ContentAfterLastDotPipe, GroupByPipe, KeysPipe, ComponentModeService] }) export class PropertiesAssignmentModule { diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html index d1b671cff2..317a1fc827 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html @@ -4,9 +4,12 @@ - +
- - Clear All + + Clear All
- +
-
{{component.name}}
-
No data to display
- + +
+ {{component.name}} +
+
No data to display
+
-
{{propertyStructureHeader || selectedFlatProperty.name || "No Property Selected"}}
-
No data to display
- +
+ {{!isInpusTabSelected ? (propertyStructureHeader || selectedFlatProperty.name || "No Property Selected") : "No Property Selected"}} +
+
No data to display
+
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 f7a62bbcb5..e56374a2c2 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 @@ -145,6 +145,12 @@ text-align: left; background-color: @ng2-light-gray; font-size: 13px; + span{ + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + max-width: 290px; + } } .hierarchy-nav { 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 299615b122..98fdc7391a 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 @@ -1,18 +1,23 @@ import {Component, ViewChild, ElementRef, Renderer, Inject} from "@angular/core"; import {PostsService} from "../../services/posts.service"; -import {PropertiesService, SimpleFlatProperty} from "../../services/properties.service"; +import { PropertiesService } from "../../services/properties.service"; +import { HierarchyNavService } from "../../services/hierarchy-nav.service"; import { PropertiesUtils } from './properties.utils'; import { PropertyFEModel, InstanceFePropertiesMap, InstanceBePropertiesMap, InstancePropertiesAPIMap, Component as ComponentData, FilterPropertiesAssignmentData } from "app/models"; import { PROPERTY_TYPES, ResourceType } from "app/utils"; import property = require("lodash/property"); import {ComponentServiceNg2} from "../../services/component-services/component.service"; import {ComponentInstanceServiceNg2} from "../../services/component-instance-services/component-instance.service" -import {InputFEModel, ComponentInstance, PropertyBEModel, DerivedFEProperty, ResourceInstance} from "app/models"; +import { InputFEModel, ComponentInstance, PropertyBEModel, DerivedPropertyType, DerivedFEProperty, ResourceInstance, SimpleFlatProperty } from "app/models"; import {HierarchyDisplayOptions} from "../../components/hierarchy-navigtion/hierarchy-display-options" import {PropertyRowSelectedEvent} from "./../../components/properties-table/properties-table.component"; import { KeysPipe } from 'app/ng2/pipes/keys.pipe'; import {FilterPropertiesAssignmentComponent} from "../../components/filter-properties-assignment/filter-properties-assignment.component"; - +import { ComponentModeService } from "app/ng2/services/component-mode.service" +import {WorkspaceMode, EVENTS} from "../../../utils/constants"; +import {ComponentInstanceProperty, InputBEModel} from "app/models" +import {ComponentInstanceInput} from "../../../models/properties-inputs/input-be-model"; +import {EventListenerService} from "app/services/event-listener-service" @Component({ templateUrl: './properties-assignment.page.component.html', styleUrls: ['./properties-assignment.page.component.less'] @@ -29,39 +34,60 @@ export class PropertiesAssignmentComponent { inputs: Array = []; instances: Array = []; searchQuery: string; - propertyStructureHeader: string + propertyStructureHeader: string; selectedFlatProperty: SimpleFlatProperty = new SimpleFlatProperty(); selectedInstanceType: string; selectedInstanceData: ComponentInstance = new ComponentInstance(); checkedPropertiesCount: number = 0; - hierarchyPropertiesDisplayOptions:HierarchyDisplayOptions = new HierarchyDisplayOptions('uniqueId', 'name', 'childrens'); + hierarchyPropertiesDisplayOptions:HierarchyDisplayOptions = new HierarchyDisplayOptions('path', 'name', 'childrens'); hierarchyInstancesDisplayOptions:HierarchyDisplayOptions = new HierarchyDisplayOptions('uniqueId', 'name'); displayClearSearch = false; searchPropertyName:string; - hideAdvanceSearch:boolean; + isInpusTabSelected:boolean; + isReadonly:boolean; + loadingInstances:boolean = false; + loadingInputs:boolean = false; + loadingProperties:boolean = false; @ViewChild('hierarchyNavTabs') hierarchyNavTabs: ElementRef; @ViewChild('propertyInputTabs') propertyInputTabs: ElementRef; @ViewChild('advanceSearch') advanceSearch: FilterPropertiesAssignmentComponent; - constructor(private propertiesService:PropertiesService, + constructor(private propertiesService: PropertiesService, + private hierarchyNavService: HierarchyNavService, private propertiesUtils:PropertiesUtils, private componentServiceNg2:ComponentServiceNg2, private componentInstanceServiceNg2:ComponentInstanceServiceNg2, @Inject("$stateParams") _stateParams, - private renderer: Renderer) { + private renderer: Renderer, + private componentModeService:ComponentModeService, + private EventListenerService:EventListenerService) { this.instanceFePropertiesMap = new InstanceFePropertiesMap(); /* This is the way you can access the component data, please do not use any data except metadata, all other data should be received from the new api calls on the first time than if the data is already exist, no need to call the api again - Ask orit if you have any questions*/ this.component = _stateParams.component; + this.EventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.onCheckout); + this.updateViewMode(); } ngOnInit() { console.log("==>" + this.constructor.name + ": ngOnInit"); + this.loadingInputs = true; + this.loadingInstances = true; + this.loadingProperties = true; + this.componentServiceNg2 + .getComponentInputs(this.component) + .subscribe(response => { + _.forEach(response.inputs, (input: InputBEModel) => { + this.inputs.push(new InputFEModel(input)); + }); + this.loadingInputs = false; + + }); this.componentServiceNg2 .getComponentResourceInstances(this.component) .subscribe(response => { @@ -70,95 +96,33 @@ export class PropertiesAssignmentComponent { _.forEach(this.instances, (instance) => { this.instancesNavigationData.push(instance); }); - + this.loadingInstances = false; + if (this.instancesNavigationData[0] == undefined) { + this.loadingProperties = false; + } this.selectFirstInstanceByDefault(); }); + }; - this.componentServiceNg2 - .getComponentInputs(this.component) - .subscribe(response => { - _.forEach(response.inputs, (input: PropertyBEModel) => { - this.inputs.push(new InputFEModel(input)); - }); - }) + ngOnDestroy() { + this.EventListenerService.unRegisterObserver(EVENTS.ON_CHECKOUT); } selectFirstInstanceByDefault = () => { if (this.instancesNavigationData[0] !== undefined) { this.onInstanceSelectedUpdate(this.instancesNavigationData[0]); } - } - - propertyValueChanged = (event) => { - console.log("==>" + this.constructor.name + ": propertyValueChanged " + event); - - if(this.selectedInstanceData.originType === ResourceType.VF) { - console.log("I want to update input value on the resource instance"); - let inputToUpdate = new PropertyBEModel(event); - this.componentInstanceServiceNg2 - .updateInstanceInput(this.component, this.selectedInstanceData.uniqueId, inputToUpdate) - .subscribe(response => { - console.log("update resource instance input and got this response: ",response); - }) - } - else { - // Copying the actual value from the object ref into the value if it's from a complex type - if(event.isDataType) { - event.value = JSON.stringify(event.valueObjectRef); - } - let propertyBe = new PropertyBEModel(event); - this.componentInstanceServiceNg2 - .updateInstanceProperty(this.component, this.selectedInstanceData.uniqueId, propertyBe) - .subscribe(response => { - console.log("updated resource instance property and got this response: ",response); - }); - console.log(event); - } - - }; - - inputValueChanged = (event) => { - console.log("==>" + this.constructor.name + ": inputValueChanged"); - let inputToUpdate = new PropertyBEModel(event); - - this.componentServiceNg2 - .updateComponentInput(this.component, inputToUpdate) - .subscribe(response => { - console.log("updated the component input and got this response: ", response); - }) }; - declareProperties = ():void => { - console.log("==>" + this.constructor.name + ": declareProperties"); - - let selectedProperties: InstanceBePropertiesMap = new InstanceBePropertiesMap(); - - let instancesNames = new KeysPipe().transform(this.instanceFePropertiesMap,[]); - angular.forEach(instancesNames, (instanceName:string):void=>{ - selectedProperties[instanceName] = this.propertiesService.getCheckedProperties(this.instanceFePropertiesMap[instanceName]); - //selectedProperties[this.selectedInstanceData.uniqueId] = this.propertiesService.getCheckedProperties(this.properties); - }); + updateViewMode = () => { + this.isReadonly = this.componentModeService.getComponentMode(this.component) === WorkspaceMode.VIEW; + } - let inputsToCreate: InstancePropertiesAPIMap; - if (this.selectedInstanceType !== ResourceType.VF) { - inputsToCreate = new InstancePropertiesAPIMap(null, selectedProperties); - } else { - inputsToCreate = new InstancePropertiesAPIMap(selectedProperties, null); - } - this.componentServiceNg2 - .createInput(this.component, inputsToCreate) - .subscribe(response => { - this.setInputTabIndication(response.length); - this.checkedPropertiesCount = 0; - _.forEach(response, (input: PropertyBEModel) => { this.inputs.push(new InputFEModel(input)); }); - this.findAndDisableDeclaredProperties(); - }); + onCheckout = (component:ComponentData) => { + this.component = component; + this.updateViewMode(); } - //TODO: Can remove? no one use it - // getSelectedFEProps = (): Array => { - // return this.properties.filter(prop => prop.isSelected && !prop.isDeclared); - // } onInstanceSelectedUpdate = (resourceInstance: ResourceInstance) => { console.log("==>" + this.constructor.name + ": onInstanceSelectedUpdate"); @@ -166,12 +130,15 @@ export class PropertiesAssignmentComponent { this.selectedInstanceData = resourceInstance; this.selectedInstanceType = resourceInstance.originType; + this.loadingProperties = true; if(resourceInstance.originType === ResourceType.VF) { this.componentInstanceServiceNg2 .getComponentInstanceInputs(this.component, resourceInstance) .subscribe(response => { instanceBePropertiesMap[resourceInstance.uniqueId] = response; this.processInstancePropertiesResponse(instanceBePropertiesMap); + this.loadingProperties = false; + }); } else { this.componentInstanceServiceNg2 @@ -179,23 +146,68 @@ export class PropertiesAssignmentComponent { .subscribe(response => { instanceBePropertiesMap[resourceInstance.uniqueId] = response; this.processInstancePropertiesResponse(instanceBePropertiesMap); + this.loadingProperties = false; }); } if( this.searchPropertyName ){ this.clearSearch(); } + //clear selected property from the navigation + this.selectedFlatProperty = new SimpleFlatProperty(); + this.propertiesNavigationData = []; }; /** * Entry point handling response from server */ processInstancePropertiesResponse = (instanceBePropertiesMap:InstanceBePropertiesMap) => { - this.instanceFePropertiesMap = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren(instanceBePropertiesMap); //create flattened children - this.findAndDisableDeclaredProperties(); //disable properties or flattened children that are declared + this.instanceFePropertiesMap = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren(instanceBePropertiesMap, this.inputs); //create flattened children, disable declared props, and init values this.checkedPropertiesCount = 0; }; + + /*** VALUE CHANGE EVENTS ***/ + propertyValueChanged = (event: PropertyFEModel) => { + console.log("==>" + this.constructor.name + ": propertyValueChanged " + event); + // Copying the actual value from the object ref into the value if it's from a complex type + event.value = event.getJSONValue(); + + if (this.selectedInstanceData.originType === ResourceType.VF) { + console.log("I want to update input value on the resource instance"); + let inputToUpdate = new PropertyBEModel(event); + this.componentInstanceServiceNg2 + .updateInstanceInput(this.component, this.selectedInstanceData.uniqueId, inputToUpdate) + .subscribe(response => { + console.log("update resource instance input and got this response: ", response); + }) + } + else { + let propertyBe = new PropertyBEModel(event); + this.componentInstanceServiceNg2 + .updateInstanceProperty(this.component, this.selectedInstanceData.uniqueId, propertyBe) + .subscribe(response => { + console.log("updated resource instance property and got this response: ", response); + }); + console.log(event); + } + + }; + + inputValueChanged = (event) => { + console.log("==>" + this.constructor.name + ": inputValueChanged"); + let inputToUpdate = new PropertyBEModel(event); + + this.componentServiceNg2 + .updateComponentInput(this.component, inputToUpdate) + .subscribe(response => { + console.log("updated the component input and got this response: ", response); + }) + }; + + + /*** HEIRARCHY/NAV RELATED FUNCTIONS ***/ + /** * Handle select node in navigation area, and select the row in table */ @@ -219,13 +231,13 @@ export class PropertiesAssignmentComponent { if(this.selectedInstanceData.originType !== ResourceType.VF) { let simpleFlatProperty:Array; if (property instanceof PropertyFEModel) { - simpleFlatProperty = this.propertiesService.getSimplePropertiesTree(property, instanceName); + simpleFlatProperty = this.hierarchyNavService.getSimplePropertiesTree(property, instanceName); } else if (property instanceof DerivedFEProperty) { // Need to find parent PropertyFEModel let parentPropertyFEModel:PropertyFEModel = _.find(this.instanceFePropertiesMap[instanceName], (tmpFeProperty):boolean => { return property.propertiesName.indexOf(tmpFeProperty.name)===0; }); - simpleFlatProperty = this.propertiesService.getSimplePropertiesTree(parentPropertyFEModel, instanceName); + simpleFlatProperty = this.hierarchyNavService.getSimplePropertiesTree(parentPropertyFEModel, instanceName); } this.propertiesNavigationData = simpleFlatProperty; } @@ -236,20 +248,10 @@ export class PropertiesAssignmentComponent { } // Set selected property in table - this.selectedFlatProperty = new SimpleFlatProperty(property.uniqueId, null, property.name, null); + this.selectedFlatProperty = this.hierarchyNavService.createSimpleFlatProperty(property, instanceName); this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Property Structure']); }; - //TODO: Can remove? no one use it - // findParentProperty = (childProp: DerivedFEProperty): PropertyFEModel => { - // return this.properties.find(prop => prop.name == childProp.propertiesName.substring(0, childProp.propertiesName.indexOf("#"))); - // } - - //used for declare button, to keep count of newly checked properties (and ignore declared properties) - updateCheckedPropertyCount = (increment: boolean):void => { - this.checkedPropertiesCount += (increment) ? 1 : -1; - console.log("CheckedProperties count is now.... " + this.checkedPropertiesCount); - } selectInstanceRow = ($event) => {//get instance name this.selectedInstanceData = _.find(this.instancesNavigationData, (instance:ComponentInstance) => { @@ -257,15 +259,90 @@ export class PropertiesAssignmentComponent { }); this.renderer.invokeElementMethod( this.hierarchyNavTabs, 'triggerTabChange', ['Composition']); - } + }; tabChanged = (event) => { console.log("==>" + this.constructor.name + ": tabChanged " + event); - this.hideAdvanceSearch = event.title !== "Properties"; + this.isInpusTabSelected = event.title === "Inputs"; + this.propertyStructureHeader = null; this.searchQuery = ''; }; - deleteInput = (input:InputFEModel) => { + + + /*** DECLARE PROPERTIES/INPUTS ***/ + declareProperties = (): void => { + console.log("==>" + this.constructor.name + ": declareProperties"); + + let selectedProperties: InstanceBePropertiesMap = new InstanceBePropertiesMap(); + + let instancesNames = new KeysPipe().transform(this.instanceFePropertiesMap, []); + angular.forEach(instancesNames, (instanceName: string): void => { + selectedProperties[instanceName] = this.propertiesService.getCheckedProperties(this.instanceFePropertiesMap[instanceName]); + //selectedProperties[this.selectedInstanceData.uniqueId] = this.propertiesService.getCheckedProperties(this.properties); + }); + + let inputsToCreate: InstancePropertiesAPIMap; + if (this.selectedInstanceType !== ResourceType.VF) { + inputsToCreate = new InstancePropertiesAPIMap(null, selectedProperties); + } else { + inputsToCreate = new InstancePropertiesAPIMap(selectedProperties, null); + } + this.componentServiceNg2 + .createInput(this.component, inputsToCreate) + .subscribe(response => { + this.setInputTabIndication(response.length); + this.checkedPropertiesCount = 0; + _.forEach(response, (input: InputBEModel) => { + this.inputs.push(new InputFEModel(input)); + this.updatePropertyValueAfterDeclare(input); + }); + }); + }; + + updatePropertyValueAfterDeclare = (input: InputBEModel) => { + _.forEach(input.properties, (property: ComponentInstanceProperty) => { + this.updatePropertyOrInputValueAfterDeclare(property, input); + }); + + _.forEach(input.inputs, (inputInstance: ComponentInstanceInput) => { + this.updatePropertyOrInputValueAfterDeclare(inputInstance, input); + }); + } + + updatePropertyOrInputValueAfterDeclare = (inputSource: ComponentInstanceProperty | ComponentInstanceInput, input: InputBEModel) => { + if (this.instanceFePropertiesMap[inputSource.componentInstanceId]) { + let propertyForUpdatindVal = _.find(this.instanceFePropertiesMap[inputSource.componentInstanceId], (feProperty: PropertyFEModel) => { + return feProperty.name == inputSource.name; + }); + + if (input.inputPath == propertyForUpdatindVal.name) input.inputPath = null; //Fix - if inputPath is sent for parent props, remove it + + propertyForUpdatindVal.setAsDeclared(input.inputPath); //set prop as declared before assigning value + this.propertiesService.disableRelatedProperties(propertyForUpdatindVal, input.inputPath); + this.propertiesUtils.resetPropertyValue(propertyForUpdatindVal, inputSource.value, input.inputPath); + // if (input.inputPath) { + // let childProp = _.find(propertyForUpdatindVal.flattenedChildren, (child: DerivedFEProperty) => { + // return child.propertiesName == input.inputPath; + // }); + // this.propertiesUtils.assignFlattenedChildrenValues(JSON.parse(inputSource.value), [childProp], inputSource.name); + // } else { + // propertyForUpdatindVal.valueObj = inputSource.value; + // } + } + } + + //used for declare button, to keep count of newly checked properties (and ignore declared properties) + updateCheckedPropertyCount = (increment: boolean): void => { + this.checkedPropertiesCount += (increment) ? 1 : -1; + console.log("CheckedProperties count is now.... " + this.checkedPropertiesCount); + }; + + setInputTabIndication = (numInputs: number): void => { + this.renderer.invokeElementMethod(this.propertyInputTabs, 'setTabIndication', ['Inputs', numInputs]); + }; + + deleteInput = (input: InputFEModel) => { console.log("==>" + this.constructor.name + ": deleteInput"); let inputToDelete = new PropertyBEModel(input); @@ -273,51 +350,45 @@ export class PropertiesAssignmentComponent { .deleteInput(this.component, inputToDelete) .subscribe(response => { this.inputs = this.inputs.filter(input => input.uniqueId !== response.uniqueId); - let propToEnable: PropertyFEModel = this.instanceFePropertiesMap[input.instanceName].find(prop => prop.name == input.propertyName); - propToEnable.setNonDeclared(response.inputPath); - this.propertiesService.undoDisableRelatedProperties(propToEnable, response.inputPath); - //this.propertiesService.initValueObjectRef(propToEnable); //TODO:speak to BE about value returned by server - }); - } - setInputTabIndication = (numInputs: number): void => { - this.renderer.invokeElementMethod( this.propertyInputTabs, 'setTabIndication', ['Inputs', numInputs]); - } + //Reload the whole instance for now - TODO: CHANGE THIS after the BE starts returning properties within the response, use commented code below instead! + this.onInstanceSelectedUpdate(this.selectedInstanceData); + // let instanceFeProperties = this.instanceFePropertiesMap[this.getInstanceUniqueId(input.instanceName)]; + + // if (instanceFeProperties) { + // let propToEnable: PropertyFEModel = instanceFeProperties.find((prop) => { + // return prop.name == input.propertyName; + // }); + + // if (propToEnable) { + // if (propToEnable.name == response.inputPath) response.inputPath = null; + // propToEnable.setNonDeclared(response.inputPath); + // //this.propertiesUtils.resetPropertyValue(propToEnable, newValue, response.inputPath); + // this.propertiesService.undoDisableRelatedProperties(propToEnable, response.inputPath); + // } + // } + }); + }; - findAndDisableDeclaredProperties = () => { - this.inputs.filter(input => input.instanceName === this.selectedInstanceData.normalizedName).forEach(input => { - let prop: PropertyFEModel = this.instanceFePropertiesMap[this.selectedInstanceData.uniqueId].find(prop => prop.name === input.propertyName); - if (prop) { - prop.setAsDeclared(input.inputPath); //if a path was sent, its a child prop. this param is optional - this.propertiesService.disableRelatedProperties(prop, input.inputPath) - //this.propertiesService.initValueObjectRef(prop); - } + getInstanceUniqueId = (instanceName: string): string => { + let wantedInstance: ComponentInstance = this.instances.find((instance) => { + return instance.normalizedName === instanceName; }); + + return wantedInstance.uniqueId; }; + + + /*** SEARCH RELATED FUNCTIONS ***/ searchPropertiesInstances = (filterData:FilterPropertiesAssignmentData) => { - //let filteredProperties = this.componentServiceNg2.filterComponentInstanceProperties(this.component, filterData); let instanceBePropertiesMap:InstanceBePropertiesMap; this.componentServiceNg2 .filterComponentInstanceProperties(this.component, filterData) .subscribe(response => { - //instanceBePropertiesMap=response; - //console.log("================filter results============="); - //console.table(instanceBePropertiesMap); - this.processInstancePropertiesResponse(response); - - - //this.properties = []; - // _.forEach(instanceBePropertiesMap, (InstanceProperties:Array, instanceName:string) => { - // this.properties = this.properties.concat(this.propertiesService.convertPropertiesToFEAndCreateChildren(InstanceProperties, instanceName)); - // }); - - - // this.instancesNavigationData = _.filter(this.instancesNavigationData, (instance:ComponentInstance) => { - // return instanceBePropertiesMap[instance.name]; - // }); - // this.hierarchyPropertiesDisplayOptions.searchText = filterData.propertyName;//mark results in tree + this.processInstancePropertiesResponse(response); + this.hierarchyPropertiesDisplayOptions.searchText = filterData.propertyName;//mark results in tree this.searchPropertyName = filterData.propertyName;//mark in table this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Composition']); this.propertiesNavigationData = []; @@ -332,13 +403,13 @@ export class PropertiesAssignmentComponent { this.hierarchyPropertiesDisplayOptions.searchText = ""; this.displayClearSearch = false; this.advanceSearch.clearAll(); - } + }; clickOnClearSearch = () => { this.clearSearch(); this.selectFirstInstanceByDefault(); this.renderer.invokeElementMethod( this.hierarchyNavTabs, 'triggerTabChange', ['Composition']); - } + }; } 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 79769e21b5..dfde2a40b2 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 @@ -1,78 +1,154 @@ import { Injectable } from '@angular/core'; import { DataTypeModel, PropertyFEModel, PropertyBEModel, InstanceBePropertiesMap, InstanceFePropertiesMap, SchemaProperty, DerivedFEProperty, DerivedFEPropertyMap, DerivedPropertyType, InputFEModel} from "app/models"; import { DataTypeService } from "app/ng2/services/data-type.service"; +import { PropertiesService } from "app/ng2/services/properties.service"; import { PROPERTY_TYPES } from "app/utils"; import { UUID } from "angular2-uuid"; @Injectable() export class PropertiesUtils { - constructor(private dataTypeService:DataTypeService) {} + constructor(private dataTypeService:DataTypeService, private propertiesService: PropertiesService) {} /** * Entry point when getting properties from server - * Returning InstanceFePropertiesMap + * For each instance, loop through each property, and: + * 1. Create flattened children + * 2. Check against inputs to see if any props are declared and disable them + * 3. Initialize valueObj (which also creates any new list/map flattened children as needed) + * Returns InstanceFePropertiesMap */ - public convertPropertiesMapToFEAndCreateChildren = (instancePropertiesMap:InstanceBePropertiesMap): InstanceFePropertiesMap => { + public convertPropertiesMapToFEAndCreateChildren = (instancePropertiesMap:InstanceBePropertiesMap, inputs:Array): InstanceFePropertiesMap => { let instanceFePropertiesMap:InstanceFePropertiesMap = new InstanceFePropertiesMap(); angular.forEach(instancePropertiesMap, (properties:Array, instanceName:string) => { - instanceFePropertiesMap[instanceName] = this.convertPropertiesToFEAndCreateChildren(properties); + let instanceInputs: Array = inputs.filter(input => input.instanceName == instanceName.split('.').pop()); + let propertyFeArray: Array = []; + _.forEach(properties, (property: PropertyBEModel) => { + + if (!this.dataTypeService.getDataTypeByTypeName(property.type)) { // if type not exist in data types remove property from list + console.log("ERROR: missing type " + property.type + " in dataTypes , of property ", property); + } else { + + let newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE + + if (newFEProp.derivedDataType == DerivedPropertyType.COMPLEX) { //Create children if prop is not simple, list, or map. + newFEProp.flattenedChildren = this.createFlattenedChildren(newFEProp.type, newFEProp.name); + } + if (instanceInputs.length) { //if this prop (or any children) are declared, set isDeclared and disable checkbox on parents/children + instanceInputs.filter(input => input.propertyName == newFEProp.name).forEach((input) => { + newFEProp.setAsDeclared(input.inputPath); //if a path was sent, its a child prop. this param is optional + this.propertiesService.disableRelatedProperties(newFEProp, input.inputPath); + }); + } + this.initValueObjectRef(newFEProp); //initialize valueObj. + propertyFeArray.push(newFEProp); + newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children + } + }); + instanceFePropertiesMap[instanceName] = propertyFeArray; + }); return instanceFePropertiesMap; } + private createListOrMapChildrenFromValueObj = (property: PropertyFEModel) => { + if ((property.derivedDataType == DerivedPropertyType.LIST || property.derivedDataType == DerivedPropertyType.MAP) + && Object.keys(property.valueObj).length) { - /** - * Convert the properties Array to Array - */ - private convertPropertiesToFEAndCreateChildren = (properties: Array): Array => { - let propertyFeArray: Array = []; - _.forEach(properties, (property: PropertyBEModel, index: number) => { - //console.log("=======" + property.name + "========"); - if(!this.dataTypeService.getDataTypeByTypeName(property.type)){ // if type not exist in data types remove property from list - console.log("ERROR: missing type " + property.type + " in dataTypes , of property ",property); - return; - } - let propertyFe:PropertyFEModel = new PropertyFEModel(property); - if (propertyFe.isDataType) { //prop is not simple, list, or map. Need to create children. - let tempProps: Array = []; - let dataTypeObj: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(propertyFe.type); - this.dataTypeService.getDerivedDataTypeProperties(dataTypeObj, tempProps, propertyFe.name); - propertyFe.flattenedChildren = tempProps; - propertyFe.expandedChildPropertyId = propertyFe.name; - this.initValueObjectRef(propertyFe); - } - propertyFeArray.push(propertyFe); - + Object.keys(property.valueObj).forEach((key) => { + let newProps: Array = this.createListOrMapChildren(property, key, property.valueObj[key]); + property.flattenedChildren.push(...newProps); + }); + + } + } - }); - return propertyFeArray; + public createListOrMapChildren = (property:PropertyBEModel, key: string, valueObj: any): Array => { + let newProps: Array = []; + let parentProp = new DerivedFEProperty(property, property.propertiesName, true, key, valueObj); + newProps.push(parentProp); - //TODO: need to look at schema to create the nested properties for the following cases: - // 1 - when value is populated for a complex type (list or map) - // 2 - when adding new entries to a complex type (eg. adding a new entry to a list of AddressRequirements) + if (!property.schema.property.isSimpleType) { + let additionalChildren:Array = this.createFlattenedChildren(property.schema.property.type, parentProp.propertiesName); + this.assignFlattenedChildrenValues(parentProp.valueObj, additionalChildren, parentProp.propertiesName); + additionalChildren.forEach(prop => prop.canBeDeclared = false); + newProps.push(...additionalChildren); + } + return newProps; } + /** + * Creates derivedFEProperties of a specified type and returns them. + */ + private createFlattenedChildren = (type: string, parentName: string):Array => { + let tempProps: Array = []; + let dataTypeObj: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(type); + this.dataTypeService.getDerivedDataTypeProperties(dataTypeObj, tempProps, parentName); + return tempProps; + } + + /* Sets the valueObj of parent property and its children. + * Note: This logic is different than assignflattenedchildrenvalues - here we merge values, there we pick either the parents value, props value, or default value - without merging. + */ public initValueObjectRef = (property: PropertyFEModel): void => { - //console.log("Property " + property.name + " has value: " + property.value); - if (!property.isDataType || property.isDeclared) { //if property is declared, it gets a simple input instead. List and map values and pseudo-children will be handled in property component - property.value = property.value || property.defaultValue; - } else if (property.value){ //we have a complex property with a value. Lets parse property.value and populate our flattened children with those values - this.assignValuesRecursively(JSON.parse(property.value), property.flattenedChildren, property.name); + if (property.derivedDataType == DerivedPropertyType.SIMPLE || property.isDeclared) { //if property is declared, it gets a simple input instead. List and map values and pseudo-children will be handled in property component + property.valueObj = property.value || property.defaultValue; + + if (property.isDeclared && typeof property.valueObj == 'object') property.valueObj = JSON.stringify(property.valueObj); + } else { + if (property.derivedDataType == DerivedPropertyType.LIST) { + property.valueObj = _.merge([], JSON.parse(property.defaultValue || '[]'), JSON.parse(property.value || '[]')); //value object should be merged value and default value. Value takes higher precendence. Set valueObj to empty obj if undefined. + } else { + property.valueObj = _.merge({}, JSON.parse(property.defaultValue || '{}'), JSON.parse(property.value || '{}')); //value object should be merged value and default value. Value takes higher precendence. Set valueObj to empty obj if undefined. + } + if (property.derivedDataType == DerivedPropertyType.COMPLEX) { + this.assignFlattenedChildrenValues(property.valueObj, property.flattenedChildren, property.name); + } else { + this.createListOrMapChildrenFromValueObj(property); + } } } - public assignValuesRecursively = (valueJSON: any, derivedPropArray: Array, propName: string) => { - if (valueJSON && Object.keys(valueJSON)) { - Object.keys(valueJSON).forEach(valueKey => { - let childProp: DerivedFEProperty = derivedPropArray.find(prop => prop.propertiesName == propName + "#" + valueKey); - if (!childProp) return; - if (childProp.isDeclared || (childProp.derivedDataType != DerivedPropertyType.COMPLEX && !_.isEmpty(valueJSON[valueKey]))) { - childProp.value = (typeof valueJSON[valueKey] === 'object')? JSON.stringify(valueJSON[valueKey]) : valueJSON[valueKey]; - } else { - this.assignValuesRecursively(valueJSON[valueKey], derivedPropArray, childProp.propertiesName) + /* + * Loops through flattened properties array and to assign values + * Then, convert any neccessary strings to objects, and vis-versa + * For list or map property, creates new children props if valueObj has values + */ + public assignFlattenedChildrenValues = (parentValueJSON: any, derivedPropArray: Array, parentName: string) => { + if (!derivedPropArray || !parentName) return; + derivedPropArray.forEach((prop, index) => { + + 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 + prop.valueObj = JSON.stringify(prop.valueObj); + } else { //parse strings that should be objects + if ((prop.derivedDataType == DerivedPropertyType.COMPLEX || prop.derivedDataType == DerivedPropertyType.MAP) && typeof prop.valueObj != 'object') { + prop.valueObj = JSON.parse(prop.valueObj || '{}'); + } else if (prop.derivedDataType == DerivedPropertyType.LIST && typeof prop.valueObj != 'object') { + prop.valueObj = JSON.parse(prop.valueObj || '[]'); } - }); + if ((prop.derivedDataType == DerivedPropertyType.LIST || prop.derivedDataType == DerivedPropertyType.MAP) && Object.keys(prop.valueObj).length) { + let newProps: Array = []; + Object.keys(prop.valueObj).forEach((key) => { + newProps.push(...this.createListOrMapChildren(prop, key, prop.valueObj[key]));//create new children, assign their values, and then add to array + }); + derivedPropArray.splice(index + 1, 0, ...newProps); + } + } + }); + } + + public resetPropertyValue = (property: PropertyFEModel, newValue: string, inputPath?: string): void => { + property.value = newValue; + if (inputPath) { + let newProp = property.flattenedChildren.find(prop => prop.propertiesName == inputPath); + newProp && this.assignFlattenedChildrenValues(JSON.parse(newValue), [newProp], property.name); + } else { + this.initValueObjectRef(property); } } + + } diff --git a/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts b/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts index 7e017e8590..3a0c85dda2 100644 --- a/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts +++ b/catalog-ui/src/app/ng2/pipes/searchFilter.pipe.ts @@ -8,11 +8,10 @@ export class SearchFilterPipe implements PipeTransform { if (!term || !term.length) return value; return value.filter((item) => { if (item.hasOwnProperty(key)) { - let regExp = new RegExp(term, 'gi'); - return regExp.test(item[key]); + return item[key].indexOf(term) > -1; } else { return false; } }); } -} \ No newline at end of file +} diff --git a/catalog-ui/src/app/ng2/services/component-mode.service.ts b/catalog-ui/src/app/ng2/services/component-mode.service.ts new file mode 100644 index 0000000000..12a581e5f9 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/component-mode.service.ts @@ -0,0 +1,29 @@ +/** + * Created by rc2122 on 5/23/2017. + */ +import { Injectable } from '@angular/core'; +import {WorkspaceMode, ComponentState, Role} from "../../utils/constants"; +import { Component as ComponentData } from "app/models"; +import { CacheService } from "app/services/cache-service" + +@Injectable() + +export class ComponentModeService { + + constructor(private cacheService:CacheService) { + } + + public getComponentMode = (component:ComponentData):WorkspaceMode => {//return if is edit or view for resource or service + let mode = WorkspaceMode.VIEW; + + let user = this.cacheService.get("user"); + if (component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT && + component.lastUpdaterUserId === user.userId) { + if ((component.isService() || component.isResource()) && user.role == Role.DESIGNER) { + mode = WorkspaceMode.EDIT; + } + } + return mode; + } +} + diff --git a/catalog-ui/src/app/ng2/services/component-services/service.service.ts b/catalog-ui/src/app/ng2/services/component-services/service.service.ts index b47b64c5c2..d2f7078599 100644 --- a/catalog-ui/src/app/ng2/services/component-services/service.service.ts +++ b/catalog-ui/src/app/ng2/services/component-services/service.service.ts @@ -20,7 +20,7 @@ export class ServiceServiceNg2 { validateConformanceLevel(service: Service): Observable { - return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/conformanceLevelValidation') + return this.http.get(this.baseUrl + service.getTypeUrl() + service.uuid + '/conformanceLevelValidation') .map((res: Response) => { return res.json(); }); diff --git a/catalog-ui/src/app/ng2/services/data-type.service.ts b/catalog-ui/src/app/ng2/services/data-type.service.ts index e7ea1a8430..be2388144f 100644 --- a/catalog-ui/src/app/ng2/services/data-type.service.ts +++ b/catalog-ui/src/app/ng2/services/data-type.service.ts @@ -49,12 +49,14 @@ export class DataTypeService { return propertiesArray; } */ - + public getDerivedDataTypeProperties(dataTypeObj: DataTypeModel, propertiesArray: Array, parentName: string) { //push all child properties to array if (dataTypeObj.properties) { dataTypeObj.properties.forEach((derivedProperty) => { - propertiesArray.push(new DerivedFEProperty(derivedProperty, parentName)); + if(dataTypeObj.name !== PROPERTY_DATA.OPENECOMP_ROOT || derivedProperty.name !== PROPERTY_DATA.SUPPLEMENTAL_DATA){//The requirement is to not display the property supplemental_data + propertiesArray.push(new DerivedFEProperty(derivedProperty, parentName)); + } let derivedDataTypeObj: DataTypeModel = this.getDataTypeByTypeName(derivedProperty.type); this.getDerivedDataTypeProperties(derivedDataTypeObj, propertiesArray, parentName + "#" + derivedProperty.name); }); @@ -62,8 +64,8 @@ export class DataTypeService { //recurse parent (derivedFrom), in case one of parents contains properties if (PROPERTY_DATA.ROOT_DATA_TYPE !== dataTypeObj.derivedFrom.name) { this.getDerivedDataTypeProperties(dataTypeObj.derivedFrom, propertiesArray, parentName); - } - } - + } + } + } diff --git a/catalog-ui/src/app/ng2/services/hierarchy-nav.service.ts b/catalog-ui/src/app/ng2/services/hierarchy-nav.service.ts new file mode 100644 index 0000000000..512505d7c6 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/hierarchy-nav.service.ts @@ -0,0 +1,63 @@ +import { Injectable } from '@angular/core'; +import { SimpleFlatProperty, PropertyFEModel, DerivedFEProperty } from 'app/models'; + + +@Injectable() +export class HierarchyNavService { + /** + * Build hirarchy structure for the tree when user selects on table row. + * First create Array and insert also the parent (PropertyFEModel) to this array. + * The Array is flat and contains SimpleFlatProperty that has parentName and uniqueId. + * Now we build hirarchy from this Array (that includes childrens) and return it for the tree + * + * @argument property: PropertyFEModel - property contains flattenedChildren array of DerivedFEProperty + * @returns Array - containing childrens Array, augmantin childrens to SimpleFlatProperty. + */ + public getSimplePropertiesTree(property: PropertyFEModel, instanceName: string): Array { + // Build Array of SimpleFlatProperty before unflatten function + let flattenProperties: Array = []; + flattenProperties.push(this.createSimpleFlatProperty(property, instanceName)); // Push the root property + _.each(property.flattenedChildren, (child: DerivedFEProperty): void => { + if (child.isChildOfListOrMap && child.schema.property.isSimpleType) return; //do not display non-complex children of list or map + flattenProperties.push(this.createSimpleFlatProperty(child, instanceName)); + }); + + let tree = this.unflatten(flattenProperties, '', []); + return tree[0].childrens; // Return the childrens without the root. + } + + public createSimpleFlatProperty = (property: PropertyFEModel | DerivedFEProperty, instanceName:string): SimpleFlatProperty => { + if (property instanceof PropertyFEModel) { + return new SimpleFlatProperty(property.uniqueId, property.name, property.name, '', instanceName); + } else { + let propName: string = (property.isChildOfListOrMap) ? property.mapKey : property.name; + return new SimpleFlatProperty(property.uniqueId, property.propertiesName, propName, property.parentName, instanceName); + } + + } + + /** + * Unflatten Array and build hirarchy. + * The result will be Array that augmantin with childrens for each SimpleFlatProperty. + */ + private unflatten(array: Array, parent: any, tree?: any): any { + tree = typeof tree !== 'undefined' ? tree : []; + parent = typeof parent !== 'undefined' && parent !== '' ? parent : { path: '' }; + + var childrens = _.filter(array, (child: SimpleFlatProperty): boolean => { + return child.parentName == parent.path; + }); + + if (!_.isEmpty(childrens)) { + if (parent.path == '') { + tree = childrens; + } else { + parent['childrens'] = childrens; + } + _.each(childrens, (child): void => { + this.unflatten(array, child); + }); + } + return tree; + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/properties.service.ts b/catalog-ui/src/app/ng2/services/properties.service.ts index 638e537cd1..a22e2aed20 100644 --- a/catalog-ui/src/app/ng2/services/properties.service.ts +++ b/catalog-ui/src/app/ng2/services/properties.service.ts @@ -8,11 +8,11 @@ import { UUID } from "angular2-uuid"; @Injectable() export class PropertiesService { - constructor(private dataTypeService:DataTypeService, private contentAfterLastDotPipe:ContentAfterLastDotPipe) { + constructor(private dataTypeService: DataTypeService, private contentAfterLastDotPipe: ContentAfterLastDotPipe) { } - public getParentPropertyFEModelFromPath = (properties:Array, path:string) => { - let parent:PropertyFEModel = _.find(properties, (property:PropertyFEModel):boolean=>{ + public getParentPropertyFEModelFromPath = (properties: Array, path: string) => { + let parent: PropertyFEModel = _.find(properties, (property: PropertyFEModel): boolean => { return property.name === path.substring(0, path.indexOf('#')); }); return parent; @@ -33,7 +33,7 @@ export class PropertiesService { } //disable parents and children of prop - public disableRelatedProperties = (property:PropertyFEModel, childPath?: string): void => { + public disableRelatedProperties = (property: PropertyFEModel, childPath?: string): void => { if (!childPath) { //selecting the parent property property.isSelected = true; property.flattenedChildren && property.flattenedChildren.map(child => { child.isSelected = false; child.isDisabled = true; }); @@ -41,18 +41,18 @@ export class PropertiesService { property.isSelected = false; property.isDisabled = true; property.flattenedChildren.filter((childProp: DerivedFEProperty) => { - return (childProp.propertiesName.indexOf(childPath + "#") > -1 //is child of prop to disable - || childPath.indexOf(childProp.propertiesName + "#") > -1); //is parent of prop to disable + return (childProp.propertiesName.indexOf(childPath + "#") === 0 //is child of prop to disable + || childPath.indexOf(childProp.propertiesName + "#") === 0); //is parent of prop to disable }).map((child: DerivedFEProperty) => { child.isSelected = false; child.isDisabled = true; }); } } - public getCheckedProperties = (properties:Array): Array => { + public getCheckedProperties = (properties: Array): Array => { let selectedProps: Array = []; properties.forEach(prop => { if (prop.isSelected && !prop.isDeclared && !prop.isDisabled) { selectedProps.push(new PropertyBEModel(prop)); - } else if(prop.flattenedChildren) { + } else if (prop.flattenedChildren) { prop.flattenedChildren.forEach((child) => { if (child.isSelected && !child.isDeclared && !child.isDisabled) { let childProp = new PropertyBEModel(prop, child); //create it from the parent @@ -64,186 +64,5 @@ export class PropertiesService { return selectedProps; } - /** - * Build hirarchy structure for the tree when user selects on table row. - * First create Array and insert also the parent (PropertyFEModel) to this array. - * The Array is flat and contains SimpleFlatProperty that has parentName and uniqueId. - * Now we build hirarchy from this Array (that includes childrens) and return it for the tree - * - * @argument property: PropertyFEModel - property contains flattenedChildren array of DerivedFEProperty - * @returns Array - containing childrens Array, augmantin childrens to SimpleFlatProperty. - */ - public getSimplePropertiesTree(property: PropertyFEModel, instanceName:string):Array { - // Build Array of SimpleFlatProperty before unflatten function - let flattenProperties:Array = []; - flattenProperties.push(new SimpleFlatProperty(property.uniqueId, property.name, property.name, '', instanceName)); // Push the root property - _.each(property.flattenedChildren, (child:DerivedFEProperty):void => { - flattenProperties.push(new SimpleFlatProperty(child.uniqueId, child.propertiesName, child.name, child.parentName, instanceName)); - }); - - let tree = this.unflatten(flattenProperties, '', []); - return tree[0].childrens; // Return the childrens without the root. - } - - /** - * Unflatten Array and build hirarchy. - * The result will be Array that augmantin with childrens for each SimpleFlatProperty. - */ - private unflatten( array:Array, parent:any, tree?:any ):any { - tree = typeof tree!=='undefined' ? tree : []; - parent = typeof parent!=='undefined' && parent!=='' ? parent : { path: '' }; - - var childrens = _.filter( array, (child:SimpleFlatProperty):boolean => { - return child.parentName == parent.path; - }); - - if( !_.isEmpty( childrens ) ){ - if( parent.path == '' ){ - tree = childrens; - } else { - parent['childrens'] = childrens; - } - _.each( childrens, ( child ):void => { - this.unflatten( array, child ); - }); - } - return tree; - } - - // TODO: To remove - // public convertPropertiesToFEAndInitialize(properties: Array): Array { - // let props:Array = []; - // _.forEach(properties, (property: PropertyFEModel, index: number) => { - // props[index] = new PropertyFEModel(property); - // this.initValueObjectRef(props[index]); - // if (props[index].isDataType || - // ((props[index].type === PROPERTY_TYPES.MAP || props[index].type === PROPERTY_TYPES.LIST) && props[index].schema.property.isDataType)) { - // props[index].valueObjectRef = props[index].valueObjectRef || {}; - // let defaultValueObject:any = props[index].defaultValue ? JSON.parse(props[index].defaultValue): null; - // this.createPropertiesTreeForProp(props[index], true, defaultValueObject); - // } - // }); - // return props; - // } - - /** - * Converts a property's map values to properties and adds them to property.childrenProperties - * @param property - property to add children to - * @param onlyFirstLevel - recursively retrieve properties for each dataType? - */ - //TODO: To remove - // public createPropertyNodesForMapOfDataTypes(property: PropertyFEModel, onlyFirstLevel:boolean):void { - // property.childrenProperties = []; - // angular.forEach(property.valueObjectRef,function(itemInMap:any, keyInMap:string){ - // let newProperty: PropertyFEModel = new PropertyFEModel(keyInMap, - // property.schema.property.type, - // UUID.UUID(), - // property, - // property.valueObjectRef[keyInMap]); - // !onlyFirstLevel && this.createPropertiesTreeForProp(newProperty); - // property.childrenProperties.push(newProperty); - // },this); - // } - - - /** - * Converts a property's list values to properties and adds them to property.childrenProperties - * @param property - property to add children to - * @param onlyFirstLevel - recursively retrieve properties for each dataType? - */ - //TODO: To remove - // public createPropertyNodesForListOfDataTypes(property: PropertyFEModel, onlyFirstLevel:boolean):void { - // property.childrenProperties = []; - // property.valueObjectRef.forEach((itemInList:any, index:number):void =>{ - // let newProperty: PropertyFEModel = new PropertyFEModel(this.contentAfterLastDotPipe.transform(property.schema.property.type), - // property.schema.property.type, - // UUID.UUID(), - // property, - // property.valueObjectRef[index]); - // !onlyFirstLevel && this.createPropertiesTreeForProp(newProperty); - // property.childrenProperties.push(newProperty); - // }); - // } - - // private checkIfPropertyDerivedFromSimpleAndUpdateProp(property:PropertyFEModel | SchemaProperty): boolean{ - // property.derivedFromSimpleTypeName = this.dataTypeService.getTypeForDataTypeDerivedFromSimple(property.type); - // if(property.derivedFromSimpleTypeName){ - // property.isSimpleType = true; - // property.isDataType = false; - // } - // return property.isSimpleType; - // } - - // TODO: Remove - public createPropertiesTreeForProp(property: PropertyFEModel, onlyFirstLevel?: boolean, defaultValueObj?: any): void { - } - - public getPropertyFEModelFromDerivedPropertyUniqueId(properties: Array, uniqueId: string): PropertyFEModel { - // _.each(properties, (property):void => { - // property.flattenedChildren - - // }); - - // let rootProperty = _.find(properties, (property):boolean => { return property.uniqueId === uniqueId; }); - // if - return null; - } - - /** - * Utilizes the dataTypeService to retrieve children properties from dataTypes recursively. - * @param property - * @param onlyFirstLevel - */ - // TODO: To remove - // public createPropertiesTreeForProp(property: PropertyFEModel, onlyFirstLevel?:boolean, defaultValueObj?:any ):void{ - // if (property.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(property)){ - // let dataType: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(property.type); - // property.childrenProperties = []; - // let childrenProperties = this.dataTypeService.getDataTypePropertiesRecursively(dataType); - // childrenProperties.forEach((childProperty: PropertyBEModel):void => { - // let childDataTypePropertyObj: PropertyFEModel = new PropertyFEModel(childProperty.name, childProperty.type,UUID.UUID(),property, {}, childProperty.schema); - // //init empty object in valueObjectRef[childProperty.name] because this property's children should has ref to this obj. - // if(!property.valueObjectRef[childDataTypePropertyObj.name]){ - // if ((childDataTypePropertyObj.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(childDataTypePropertyObj)) - // || childDataTypePropertyObj.type === PROPERTY_TYPES.MAP){ - // property.valueObjectRef[childDataTypePropertyObj.name] = {}; - // }else if(childDataTypePropertyObj.type === PROPERTY_TYPES.LIST){ - // property.valueObjectRef[childDataTypePropertyObj.name] = []; - // } - // } - // childDataTypePropertyObj.valueObjectRef = property.valueObjectRef[childDataTypePropertyObj.name]; - // property.valueObjectRef[childDataTypePropertyObj.name] = property.valueObjectRef[childProperty.name] || childDataTypePropertyObj.defaultValue; - // if( !childDataTypePropertyObj.isDataType && defaultValueObj ){//init property default value - // childDataTypePropertyObj.defaultValue = JSON.stringify(defaultValueObj[childDataTypePropertyObj.name]); - // } - // property.childrenProperties.push(childDataTypePropertyObj); - // !onlyFirstLevel && this.createPropertiesTreeForProp(childDataTypePropertyObj, false, (defaultValueObj ? defaultValueObj[childDataTypePropertyObj.name] : null)); - // }); - // } else if (property.type == PROPERTY_TYPES.MAP && property.schema.property.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(property.schema.property)){ - // if( property.valueObjectRef && !_.isEmpty(property.valueObjectRef)){ - // this.createPropertyNodesForMapOfDataTypes(property, onlyFirstLevel); - // } - // } else if (property.type == PROPERTY_TYPES.LIST && property.schema.property.isDataType && !this.checkIfPropertyDerivedFromSimpleAndUpdateProp(property.schema.property)){ - // if( property.valueObjectRef && property.valueObjectRef.length){ - // this.createPropertyNodesForListOfDataTypes(property, onlyFirstLevel); - // } - // } - // } -} - -export class SimpleFlatProperty { - uniqueId:string; - path:string; - name:string; - parentName:string; - instanceName:string; - - constructor(uniqueId?:string, path?:string, name?: string, parentName?:string, instanceName?:string) { - this.uniqueId = uniqueId; - this.path = path; - this.name = name; - this.parentName = parentName; - this.instanceName = instanceName; - } -} +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less index aa59428a64..fa05249ea4 100644 --- a/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less +++ b/catalog-ui/src/app/ng2/shared/tabs/tabs.component.less @@ -15,7 +15,6 @@ .tab-content-container { flex: 1; height: 100%; - overflow: hidden; width:100%; } @@ -59,7 +58,7 @@ width: 25px; height: 25px; text-align: center; - + } } diff --git a/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts b/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts index c8c1d9b721..ed1ecd87bd 100644 --- a/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts +++ b/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts @@ -5,6 +5,8 @@ import {DataTypesService} from "../../services/data-types-service"; import ICacheObject = angular.ICacheObject; import {SharingService} from "../../services/sharing-service"; import {CookieService} from "../../services/cookie-service"; +import {CacheService} from "../../services/cache-service"; +import {EventListenerService} from "app/services/event-listener-service"; /** Services we need to upgrade from angular1 to angular2 - in the future we need to rewrite them all to angular2 **/ @@ -24,6 +26,14 @@ export function stateParamsServiceFactory(cacheObj: ICacheObject) { return cacheObj.get('$stateParams'); } +export function cacheServiceFactory(cacheObj: ICacheObject) { + return cacheObj.get('Sdc.Services.CacheService'); +} + +export function eventListenerServiceServiceFactory(cacheObj: ICacheObject) { + return cacheObj.get('EventListenerService'); +} + export const DataTypesServiceProvider = { provide: DataTypesService, useFactory: dataTypesServiceFactory, @@ -49,3 +59,15 @@ export const StateParamsServiceFactory = { useFactory: stateParamsServiceFactory, deps: ['$injector'] }; + +export const CacheServiceProvider = { + provide: CacheService, + useFactory: cacheServiceFactory, + deps: ['$injector'] +}; + +export const EventListenerServiceProvider = { + provide: EventListenerService, + useFactory: eventListenerServiceServiceFactory, + deps: ['$injector'] +}; diff --git a/catalog-ui/src/app/services/components/component-service.ts b/catalog-ui/src/app/services/components/component-service.ts index 1a6b9a8a14..7e031baa08 100644 --- a/catalog-ui/src/app/services/components/component-service.ts +++ b/catalog-ui/src/app/services/components/component-service.ts @@ -22,12 +22,13 @@ import {ArtifactModel, IFileDownload, InstancesInputsPropertiesMap, InputModel, AttributeModel, IAppConfigurtaion, Resource, Module, DisplayModule, ArtifactGroupModel, InputsAndProperties} from "app/models"; import {ComponentInstanceFactory, CommonUtils} from "app/utils"; import {SharingService} from "../sharing-service"; +import {ComponentMetadata} from "../../models/component-metadata"; export interface IComponentService { getComponent(id:string); updateComponent(component:Component):ng.IPromise; - changeLifecycleState(component:Component, state:string, userRemarks:any):ng.IPromise ; + changeLifecycleState(component:Component, state:string, userRemarks:any):ng.IPromise ; validateName(newName:string, subtype?:string):ng.IPromise; createComponent(component:Component):ng.IPromise; addOrUpdateArtifact(componentId:string, artifact:ArtifactModel):ng.IPromise; @@ -213,11 +214,11 @@ export class ComponentService implements IComponentService { return deferred.promise; }; - public changeLifecycleState = (component:Component, state:string, userRemarks:any):ng.IPromise => { + public changeLifecycleState = (component:Component, state:string, userRemarks:any):ng.IPromise => { let deferred = this.$q.defer(); - this.restangular.one(component.uniqueId).one(state).customPOST(userRemarks).then((response:Component) => { + this.restangular.one(component.uniqueId).one(state).customPOST(userRemarks).then((response:ComponentMetadata) => { this.sharingService.addUuidValue(response.uniqueId, response.uuid); - let component:Component = this.createComponentObject(response); + let component:ComponentMetadata = new ComponentMetadata().deserialize(response); deferred.resolve(component); }, (err)=> { deferred.reject(err); diff --git a/catalog-ui/src/app/utils/component-factory.ts b/catalog-ui/src/app/utils/component-factory.ts index 18edbfb02c..13f1d761f2 100644 --- a/catalog-ui/src/app/utils/component-factory.ts +++ b/catalog-ui/src/app/utils/component-factory.ts @@ -106,6 +106,7 @@ export class ComponentFactory { newResource.csarVersion = csar.version; newResource.packageId = csar.packageId; newResource.description = csar.description; + newResource.filterTerm = newResource.name + ' ' + newResource.description + ' ' + newResource.vendorName + ' ' + newResource.csarVersion return newResource; }; diff --git a/catalog-ui/src/app/utils/constants.ts b/catalog-ui/src/app/utils/constants.ts index d55079d662..7426c7c92b 100644 --- a/catalog-ui/src/app/utils/constants.ts +++ b/catalog-ui/src/app/utils/constants.ts @@ -91,11 +91,13 @@ export class PROPERTY_DATA { public static TYPES = [PROPERTY_TYPES.STRING, PROPERTY_TYPES.INTEGER, PROPERTY_TYPES.FLOAT, PROPERTY_TYPES.BOOLEAN, PROPERTY_TYPES.JSON, PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP]; public static SIMPLE_TYPES = [PROPERTY_TYPES.STRING, PROPERTY_TYPES.INTEGER, PROPERTY_TYPES.FLOAT, PROPERTY_TYPES.BOOLEAN, PROPERTY_TYPES.JSON]; public static ROOT_DATA_TYPE = "tosca.datatypes.Root"; + public static OPENECOMP_ROOT = "org.openecomp.datatypes.Root"; + public static SUPPLEMENTAL_DATA = "supplemental_data"; public static SOURCES = [SOURCES.A_AND_AI, SOURCES.ORDER, SOURCES.RUNTIME]; } export class PROPERTY_VALUE_CONSTRAINTS { - public static MAX_LENGTH = 100; + public static MAX_LENGTH = 2500; public static JSON_MAX_LENGTH = 4096; } @@ -216,6 +218,7 @@ export class EVENTS { static ON_WORKSPACE_SAVE_BUTTON_CLICK = "onWorkspaceSaveButtonClick"; static ON_WORKSPACE_SAVE_BUTTON_SUCCESS = "onWorkspaceSaveButtonSuccess"; static ON_WORKSPACE_SAVE_BUTTON_ERROR = "onWorkspaceSaveButtonError"; + static ON_CHECKOUT = "onCheckout"; //Loader events static SHOW_LOADER_EVENT = "showLoaderEvent"; diff --git a/catalog-ui/src/app/utils/modals-handler.ts b/catalog-ui/src/app/utils/modals-handler.ts index fe864cb658..c6d1d36fc7 100644 --- a/catalog-ui/src/app/utils/modals-handler.ts +++ b/catalog-ui/src/app/utils/modals-handler.ts @@ -372,7 +372,7 @@ export class ModalsHandler implements IModalsHandler { public openConformanceLevelModal = ():ng.IPromise => { let deferred = this.$q.defer(); let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/workspace/conformance-level-modal/conformance-level-modal-view.html', + templateUrl: '../view-models/modals/conformance-level-modal/conformance-level-modal-view.html', controller: 'Sdc.ViewModels.ConformanceLevelModalViewModel', size: 'sdc-sm', backdrop: 'static', diff --git a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html index 90b8f67df4..daa7a90bf8 100644 --- a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html +++ b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html @@ -103,9 +103,9 @@ ; + modalInstance:ng.ui.bootstrap.IModalServiceInstance; +} + +export class ConformanceLevelModalViewModel { + + static '$inject' = ['$scope', '$uibModalInstance']; + + constructor(private $scope:IConformanceLevelModalModelScope, + private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance) { + + this.initScope(); + } + + private initScope = ():void => { + + this.$scope.modalInstance = this.$uibModalInstance; + + this.$scope.footerButtons = [ + {'name': 'Continue', 'css': 'grey', 'callback': this.$uibModalInstance.close}, + {'name': 'Reject', 'css': 'blue', 'callback': this.$uibModalInstance.dismiss} + ]; + + }; + +} diff --git a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html new file mode 100644 index 0000000000..3577e4d77b --- /dev/null +++ b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html @@ -0,0 +1,22 @@ + + + +
+

+ You are about to distribute a service with models and artifacts created with an older version of the platform. + For such service, new properties, metadata and requirements needed by ECOMP components will not be available. +

+ It is highly recommended that you upgrade the service models and artifacts. +

+ Click "Continue" if you need to distribute the current service version.
+ Click "Reject" if you need to stop the distribution and manually upgrade the service. +

+
+
+ +
diff --git a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less new file mode 100644 index 0000000000..7f195ade83 --- /dev/null +++ b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less @@ -0,0 +1,3 @@ +.conformance-level-modal{ + +} diff --git a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html index 3657fad017..b078a4b1ef 100644 --- a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html +++ b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html @@ -9,9 +9,9 @@ + ng-model-options="{ debounce: 300 }" />
@@ -38,16 +38,16 @@
-
- + {{component.name}}
@@ -71,7 +71,7 @@
-
+
VSP Description:
diff --git a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts deleted file mode 100644 index 61a83c88f7..0000000000 --- a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view-model.ts +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -export interface IConformanceLevelModalModelScope { - footerButtons:Array; - modalInstance:ng.ui.bootstrap.IModalServiceInstance; -} - -export class ConformanceLevelModalViewModel { - - static '$inject' = ['$scope', '$uibModalInstance']; - - constructor(private $scope:IConformanceLevelModalModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance) { - - this.initScope(); - } - - private initScope = ():void => { - - this.$scope.modalInstance = this.$uibModalInstance; - - this.$scope.footerButtons = [ - {'name': 'Continue', 'css': 'grey', 'callback': this.$uibModalInstance.close}, - {'name': 'Reject', 'css': 'blue', 'callback': this.$uibModalInstance.dismiss} - ]; - - }; - -} diff --git a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html deleted file mode 100644 index 3577e4d77b..0000000000 --- a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal-view.html +++ /dev/null @@ -1,22 +0,0 @@ - - - -
-

- You are about to distribute a service with models and artifacts created with an older version of the platform. - For such service, new properties, metadata and requirements needed by ECOMP components will not be available. -

- It is highly recommended that you upgrade the service models and artifacts. -

- Click "Continue" if you need to distribute the current service version.
- Click "Reject" if you need to stop the distribution and manually upgrade the service. -

-
-
- -
diff --git a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less b/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less deleted file mode 100644 index 7f195ade83..0000000000 --- a/catalog-ui/src/app/view-models/workspace/conformance-level-modal/conformance-level-modal.less +++ /dev/null @@ -1,3 +0,0 @@ -.conformance-level-modal{ - -} 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 e2d95280c8..670655ea4b 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 @@ -215,6 +215,10 @@ export class CompositionViewModel { if (this.$state.current.name === 'workspace.composition.api') { this.$state.go('workspace.composition.details'); } + + if(this.$scope.selectedComponent.isService() && this.$state.current.name === 'workspace.composition.relations'){ + this.$state.go('workspace.composition.api'); + } }; this.$scope.openUpdateModal = ():void => { diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts index 0ac5fd0799..5d03563042 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts @@ -179,7 +179,7 @@ export class ResourceArtifactsViewModel { this.$scope.currentComponent.selectedInstance.artifacts = artifacts; break; } - this.loadComponentArtifactIfNeeded(); + this.initArtifactArr(this.$scope.artifactType); }; let onError = ()=> { 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 b0d81b3437..bd4864771e 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 @@ -49,7 +49,7 @@ data-tests-id="edit-parameters-of-{{artifact.artifactDisplayName}}"> + artifact="artifact" component="currentComponent" data-tests-id="download_{{artifact.artifactDisplayName}}" instance="isComponentInstanceSelected()"> { //latest checked in + let latestVersionComponent:LeftPaletteComponent = _.maxBy(_.filter(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent.componentType), (component:LeftPaletteComponent) => { //latest checked in return (component.systemName === this.$scope.selectedComponent.systemName || component.uuid === this.$scope.selectedComponent.uuid); - }); + }),(component)=>{return component.version}); + let latestVersion:string = latestVersionComponent ? latestVersionComponent.version : highestVersion; if (highestVersion != latestVersion) { //highest is checked out - remove from options diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts index 84769d7a62..90cb556c75 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts @@ -118,7 +118,9 @@ export class ResourcePropertiesViewModel { (this.$scope.isPropertyOwner() ? this.$scope.properties[property.parentUniqueId] : this.$scope.properties[property.resourceInstanceUniqueId]) || [], - this.isPropertyValueOwner()).then(() => { + this.isPropertyValueOwner()).then((updatedProperty:PropertyModel) => { + let oldProp = _.find(this.$scope.properties[updatedProperty.resourceInstanceUniqueId], (prop:PropertyModel) => {return prop.uniqueId == updatedProperty.uniqueId;}); + oldProp.value = updatedProperty.value; }); }; diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html index cc914b07a8..a36eb1b74d 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html +++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html @@ -28,7 +28,7 @@
- {{artifact.artifactDisplayName}} + {{artifact.artifactDisplayName}} this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG); @@ -424,12 +424,17 @@ export class WorkspaceViewModel { //when checking out a major(certified) version this.components.unshift(component); } + this.EventListenerService.notifyObservers(EVENTS.ON_CHECKOUT, component); + // this.$state.go(this.$state.current.name, { + // id: component.uniqueId, + // type: component.componentType.toLowerCase(), + // components: this.components + // }); + this.$scope.mode = this.initViewMode(); + this.initChangeLifecycleStateButtons(); + this.initVersionObject(); + this.$scope.isLoading = false; - this.$state.go(this.$state.current.name, { - id: component.uniqueId, - type: component.componentType.toLowerCase(), - components: this.components - }); this.Notification.success({ message: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TEXT"), title: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TITLE") 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 47fd5a28f7..7d37de7965 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 @@ -71,6 +71,7 @@ public class Configuration extends BasicConfiguration { private String titanCfgFile; private String titanMigrationKeySpaceCfgFile; private Boolean titanInMemoryGraph; + private int startMigrationFrom; private Long titanLockTimeout; private Long titanReconnectIntervalInSeconds; private Long titanHealthCheckReadTimeout; @@ -293,6 +294,14 @@ public class Configuration extends BasicConfiguration { this.titanInMemoryGraph = titanInMemoryGraph; } + public int getStartMigrationFrom() { + return startMigrationFrom; + } + + public void setStartMigrationFrom(int startMigrationFrom) { + this.startMigrationFrom = startMigrationFrom; + } + public Long getTitanLockTimeout() { return titanLockTimeout; } 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 102c7dde6e..24d801262c 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 @@ -348,6 +348,14 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio this.conformanceLevel = conformanceLevel; } + public String getLifecycleState() { + return state; + } + + public void setLifecycleState(String state) { + this.state = state; + } + @Override public String toString() { return "ComponentMetadataDataDefinition [uniqueId=" + uniqueId + ", name=" + name + ", version=" + version diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java deleted file mode 100644 index a753270bbd..0000000000 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java +++ /dev/null @@ -1,209 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.datatypes.elements; - -import java.io.Serializable; -import java.util.Objects; - -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; - -/** - * Represents AttributeDataDefinition - * - * @author mshitrit - * - */ -public class AttributeDataDefinition extends ToscaDataDefinition implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -3046831950009259569L; - - private String uniqueId; - private String name; - private String type; - private String description; - - private String defaultValue; - private String value; - - private String status; - private SchemaDefinition schema; - - public AttributeDataDefinition() { - // Used From Attribute Defenition - } - - /** - * Clone Constructor - * - * @param attribute - */ - public AttributeDataDefinition(AttributeDataDefinition attribute) { - this.uniqueId = attribute.uniqueId; - this.name = attribute.name; - this.type = attribute.type; - this.description = attribute.description; - this.defaultValue = attribute.defaultValue; - this.value = attribute.value; - this.status = attribute.status; - this.schema = attribute.schema; - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public SchemaDefinition getSchema() { - return schema; - } - - public void setSchema(SchemaDefinition entrySchema) { - this.schema = entrySchema; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - result = prime * result + ((schema == null) ? 0 : schema.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - boolean equals = true; - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - - AttributeDataDefinition other = (AttributeDataDefinition) obj; - if (!Objects.equals(defaultValue, other.defaultValue)) { - equals = false; - } else if (!Objects.equals(value, other.value)) { - equals = false; - } else if (!Objects.equals(description, other.description)) { - equals = false; - } else if (!Objects.equals(name, other.name)) { - equals = false; - } else if (!Objects.equals(type, other.type)) { - equals = false; - } else if (!Objects.equals(uniqueId, other.uniqueId)) { - equals = false; - } else if (!Objects.equals(status, other.status)) { - equals = false; - } else if (!Objects.equals(schema, other.schema)) { - equals = false; - } - return equals; - } - - @Override - public String toString() { - return "AttributeDataDefinition [uniqueId=" + uniqueId + ", name=" + name + ", type=" + type + ", description=" - + description + ", defaultValue=" + defaultValue + ", value=" + value + ", status=" + status - + ", entrySchema=" + schema + "]"; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public Object getToscaPresentationValue(JsonPresentationFields field) { - switch (field) { - case NAME: - return name; - case UNIQUE_ID: - return uniqueId; - case TYPE: - return type; - case DESCRIPTION: - return description; - case VALUE: - return value; - case DEFAULT_VALUE: - return defaultValue; - default: - return super.getToscaPresentationValue(field); - } - } -} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java index 3057c72c67..c986c0fe7e 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java @@ -33,10 +33,4 @@ public class ListCapabilityDataDefinition extends ListDataDefinition mapByName = listToMapByName(); - Map mapOtherByName = other.listToMapByName(); - mapByName.putAll(mapOtherByName); - return new ListCapabilityDataDefinition(mapByName.values().stream().collect(Collectors.toList())); - } } 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 2eb8dcad2e..c9bf851e17 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 @@ -55,15 +55,17 @@ public class ListDataDefinition extends ToscaData listToscaDataDefinition.forEach(e -> e.setOwnerIdIfEmpty(ownerId)); } } - - - public Map listToMapByName() { - Map mapByName = new HashMap<>(); - listToscaDataDefinition.forEach(e -> mapByName.put((String)e.getToscaPresentationValue(JsonPresentationFields.NAME), e)); - return mapByName; - } - + @Override + public S mergeFunction(S other, boolean allowDefaultValueOverride){ + Map mapByName = listToMapByName(listToscaDataDefinition); + List otherList = ((ListDataDefinition)other).getListToscaDataDefinition(); + for(T item : otherList){ + mapByName.merge(item.getName(), item, (thisItem, otherItem) -> thisItem.mergeFunction(otherItem, allowDefaultValueOverride)); + } + ((ListDataDefinition)other).listToscaDataDefinition = mapByName.values().stream().collect(Collectors.toList()); + return other; + } } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java index 4c69958e62..fb1248d100 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java @@ -6,6 +6,7 @@ import java.util.stream.Collectors; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonValue; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; public class ListRequirementDataDefinition extends ListDataDefinition { @@ -33,11 +34,8 @@ public class ListRequirementDataDefinition extends ListDataDefinition mapByName = listToMapByName(); - Map mapOtherByName = other.listToMapByName(); - mapByName.putAll(mapOtherByName); - return new ListRequirementDataDefinition(mapByName.values().stream().collect(Collectors.toList())); - } + + + } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java deleted file mode 100644 index 817fbebd5c..0000000000 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapAttributesDataDefinition.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.openecomp.sdc.be.datatypes.elements; - -import java.util.Map; - -import org.codehaus.jackson.annotate.JsonCreator; -import org.codehaus.jackson.annotate.JsonValue; - -public class MapAttributesDataDefinition extends MapDataDefinition{ - - private String parentName; - - public MapAttributesDataDefinition(MapDataDefinition cdt, String parentName) { - super(cdt); - this.parentName = parentName; - } - - @JsonCreator - public MapAttributesDataDefinition(Map mapToscaDataDefinition) { - super(mapToscaDataDefinition); - } - public MapAttributesDataDefinition() { - super(); - - } - @JsonValue - @Override - public Map getMapToscaDataDefinition() { - return mapToscaDataDefinition; - } - - - public void setMapToscaDataDefinition(Map mapToscaDataDefinition) { - this.mapToscaDataDefinition = mapToscaDataDefinition; - } - - public String getParentName() { - return parentName; - } - - public void setParentName(String parentName) { - this.parentName = parentName; - } - - -} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java index ed94ce0d87..4c798521c5 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.datatypes.elements; import java.io.Serializable; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -60,12 +61,11 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria private String value; private String label; - private Boolean hidden = Boolean.FALSE;; + protected Boolean hidden = Boolean.FALSE; private Boolean immutable = Boolean.FALSE; private String inputPath; - - + private String status; /** * The resource id which this property belongs to @@ -104,9 +104,10 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria this.setOwnerId(p.getOwnerId()); this.setGetInputValues(p.getInputValues); this.setInputPath(p.getInputPath()); + this.setStatus(p.getStatus()); } - + public String getInputPath() { return inputPath; } @@ -115,7 +116,6 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria this.inputPath = inputPath; } - public String getName() { return name; } @@ -238,6 +238,15 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria public void setGetInputValues(List getInputValues) { this.getInputValues = getInputValues; } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + @Override public String toString() { return "PropertyDataDefinition [uniqueId=" + uniqueId + ", type=" + type + ", required=" + required + ", defaultValue=" + defaultValue + ", description=" + description + ", entrySchema=" + schema + ", parentUniqueId=" + parentUniqueId + ", password=" + password + "]"; @@ -256,6 +265,7 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); result = prime * result + ((parentUniqueId == null) ? 0 : parentUniqueId.hashCode()); + result = prime * result + ((status == null) ? 0 : status.hashCode()); return result; } @@ -307,6 +317,11 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria return false; } else if (!uniqueId.equals(other.uniqueId)) return false; + if (status == null) { + if (other.status != null) + return false; + } else if (!status.equals(other.status)) + return false; return true; } @@ -332,34 +347,23 @@ public class PropertyDataDefinition extends ToscaDataDefinition implements Seria } } - protected T overrideDataDefinition(T other, boolean allowDefaultValueOverride){ - if(this.getType().equals(other.getType())){ + private boolean compareSchemaType(T other){ + return !"list".equals(type) && !"map".equals(type) || this.getSchema().getProperty().getType().equals(((PropertyDataDefinition)other).getSchema().getProperty().getType()); + } + + + @Override + public T mergeFunction(T other, boolean allowDefaultValueOverride){ + if(this.getType().equals(other.getType()) && compareSchemaType(other)){ other.setOwnerId(getOwnerId()); if(allowDefaultValueOverride) - other.setDefaultValue(getDefaultValue()); + other.setToscaPresentationValue(JsonPresentationFields.DEFAULT_VALUE, getDefaultValue()); return other; } return null; } - - - //return Either.right(propertyName) if an illegal merge was attempted (overriding data type is forbidden) - public static Either, String> mergeProperties(Map derivedProps, Map importedProps, boolean allowDefaultValueOverride){ - for(T property : importedProps.values()){ - derivedProps.merge(property.getName(), property, (derivedProp, importedProp) -> derivedProp.overrideDataDefinition(importedProp, allowDefaultValueOverride)); - //validate merge success - if(!derivedProps.containsKey(property.getName())) - return Either.right(property.getName()); - } - return Either.left(derivedProps); - } - - - public static Map listToMapByName(List propertiesList) { - return propertiesList.stream() - .collect(Collectors.toMap(p -> p.getName(), p -> p)); - } + } 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 6004e65949..f5cc2b661b 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 @@ -38,8 +38,8 @@ public enum JsonPresentationFields { CONTACT_ID ("contactId", null), PROJECT_CODE ("projectCode", null), DISTRIBUTION_STATUS ("distributionStatus", GraphPropertyEnum.DISTRIBUTION_STATUS), - DERIVED_FROM_GENERIC_TYPE("derivedFromGenericType", null), - DERIVED_FROM_GENERIC_VERSION("derivedFromGenericVersion", null), + DERIVED_FROM_GENERIC_TYPE ("derivedFromGenericType", null), + DERIVED_FROM_GENERIC_VERSION ("derivedFromGenericVersion", null), ////Artifact ARTIFACT_TYPE ("artifactType", null), @@ -68,7 +68,7 @@ public enum JsonPresentationFields { REQUIRED_ARTIFACTS ("requiredArtifacts", null), DUPLICATED ("duplicated", null), HEAT_PARAMETERS ("heatParameters", null), - GENERATED_FROM_ID ("generatedFromId", null), + GENERATED_FROM_ID ("generatedFromId", null), // end artifacts @@ -89,10 +89,11 @@ public enum JsonPresentationFields { COMPONENT_INSTANCES ("componentInstances", null), RELATIONS ("relations", null), - + //attribute + STATUS ("status", null), //capability VALID_SOURCE_TYPE ("validSourceTypes", null), - CREATION_TIME ("creationTime", null), + CREATION_TIME ("creationTime", null), MODIFICATION_TIME ("modificationTime", null), CAPABILITY_SOURCES ("capabilitySources", null), MAX_OCCURRENCES ("maxOccurrences", null), @@ -124,17 +125,17 @@ public enum JsonPresentationFields { GROUP_UUID ("groupUUID", null), GROUP_MEMBER ("members", null), GROUP_ARTIFACTS ("artifacts", null), - GROUP_ARTIFACTS_UUID (" artifactsUuid", null), - GROUP_PROPERTIES (" properties", null), - GROUP_UNIQUE_ID (" groupUid", null), - POS_X (" posX", null), - POS_Y (" posY", null), - PROPERTY_VALUE_COUNTER (" propertyValueCounter", null), - CUSTOMIZATION_UUID (" customizationUUID", null), - GROUP_NAME (" groupName", null), - GROUP_INSTANCE_ARTIFACTS (" groupInstanceArtifacts", null), - GROUP_INSTANCE_ARTIFACTS_UUID (" groupInstanceArtifactsUuid", null), - GROUP_INSTANCE_PROPERTIES (" groupInstancesProperties", null), + GROUP_ARTIFACTS_UUID ("artifactsUuid", null), + GROUP_PROPERTIES ("properties", null), + GROUP_UNIQUE_ID ("groupUid", null), + POS_X ("posX", null), + POS_Y ("posY", null), + PROPERTY_VALUE_COUNTER ("propertyValueCounter", null), + CUSTOMIZATION_UUID ("customizationUUID", null), + GROUP_NAME ("groupName", null), + GROUP_INSTANCE_ARTIFACTS ("groupInstanceArtifacts", null), + GROUP_INSTANCE_ARTIFACTS_UUID ("groupInstanceArtifactsUuid", null), + GROUP_INSTANCE_PROPERTIES ("groupInstancesProperties", null), ; 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 d0f480b588..bf51ba4e28 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 @@ -1,13 +1,19 @@ package org.openecomp.sdc.be.datatypes.tosca; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonValue; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import fj.data.Either; + public abstract class ToscaDataDefinition { protected Map toscaPresentation; @@ -47,4 +53,39 @@ public abstract class ToscaDataDefinition { public String getOwnerId(){ return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_ID); } + + + public String getType(){ + return (String) getToscaPresentationValue(JsonPresentationFields.TYPE); + } + + public String getName(){ + return (String) getToscaPresentationValue(JsonPresentationFields.NAME); + } + + //default merge function for merging data maps - implement where needed and use mergeDataMaps method where applicable instead of map1.putAll(map2) + public T mergeFunction(T other, boolean allowDefaultValueOverride){ + other.setOwnerId(getOwnerId()); + return other; + } + + public static Either, String> mergeDataMaps(Map map1, Map map2){ + return mergeDataMaps(map1, map2, false); + } + + //return Either.right(item key) if an illegal merge was attempted (overriding data type is forbidden) + public static Either, String> mergeDataMaps(Map map1, Map map2, boolean allowDefaultValueOverride){ + for(Entry entry : map2.entrySet()){ + map1.merge(entry.getKey(), entry.getValue(), (item1, item2) -> item1.mergeFunction(item2, allowDefaultValueOverride)); + //validate merge success + if(!map1.containsKey(entry.getKey())) + return Either.right(entry.getKey()); + } + return Either.left(map1); + } + + public static Map listToMapByName(List dataList) { + return null == dataList? new HashMap<>() : dataList.stream() + .collect(Collectors.toMap(p -> p.getName(), p -> p)); + } } diff --git a/common/openecomp-common-configuration-management/openecomp-configuration-management-cli/dependency-reduced-pom.xml b/common/openecomp-common-configuration-management/openecomp-configuration-management-cli/dependency-reduced-pom.xml deleted file mode 100644 index 6c03f26d52..0000000000 --- a/common/openecomp-common-configuration-management/openecomp-configuration-management-cli/dependency-reduced-pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - openecomp-common-configuration-management - org.openecomp.sdc.common - 1.1.0-SNAPSHOT - .. - - 4.0.0 - org.openecomp.sdc.common - openecomp-configuration-management-cli - openecomp-configuration-management-cli - - - - maven-shade-plugin - 1.5 - - - package - - shade - - - - - org.openecomp.config.gui.app.Configuration - - - - - - - - - - - org.testng - testng - 6.8.8 - test - - - bsh - org.beanshell - - - jcommander - com.beust - - - - - junit - junit - RELEASE - test - - - hamcrest-core - org.hamcrest - - - - - - diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java index 552e11e91d..c8e7be53d6 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/main/java/org/openecomp/sdc/generator/aai/AaiArtifactGenerator.java @@ -554,6 +554,7 @@ public class AaiArtifactGenerator implements ArtifactGenerator { ToscaTemplate tosca = null; if (checksum.equalsIgnoreCase(input.getChecksum())) { try { + log.debug("Input yaml name " + input.getName() + "payload " + new String(decodedInput)); tosca = GeneratorUtil.translateTosca(new String(decodedInput), ToscaTemplate.class); tosca.getMetadata().put("version", serviceVersion); return tosca; diff --git a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/test/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/test/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java index 0ebe41c9a4..01029e8adc 100644 --- a/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/test/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java +++ b/common/openecomp-sdc-artifact-generator-lib/openecomp-sdc-artifact-generator-core/src/test/java/org/openecomp/sdc/generator/ArtifactGenerationServiceTest.java @@ -863,7 +863,7 @@ public class ArtifactGenerationServiceTest { } } - //@Test +// @Test public void testErrorWhenAllottedResourceWithOutProvidingServiceId() { try { Map outputArtifactMap = new HashMap<>(); diff --git a/common/openecomp-tosca-datatype/src/main/resources/globalTypes/openecomp/nodes.yml b/common/openecomp-tosca-datatype/src/main/resources/globalTypes/openecomp/nodes.yml index c9c11a7da3..fd1a8e5f9a 100644 --- a/common/openecomp-tosca-datatype/src/main/resources/globalTypes/openecomp/nodes.yml +++ b/common/openecomp-tosca-datatype/src/main/resources/globalTypes/openecomp/nodes.yml @@ -408,7 +408,23 @@ node_types: type: list entry_schema: type: org.openecomp.datatypes.network.IpRequirements - required: true + required: true + network_role: + description: identical to VL network_role + type: string + required: false + order: + description: The order of the CP on the compute instance (e.g. eth2). + type: integer + required: false + exCP_naming: + description: CP Name + type: org.openecomp.datatypes.Naming + required: false + subnetpoolid: + description: subnet pool id + type: string + required: false capabilities: network.incoming.packets.rate: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VendorSoftwareProducts.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VendorSoftwareProducts.java index 3ead86dc14..53fe2af31d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VendorSoftwareProducts.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VendorSoftwareProducts.java @@ -141,7 +141,7 @@ public interface VendorSoftwareProducts extends VspEntities { notes = "Exports translated file to a zip file", response = File.class) Response getTranslatedFile(@PathParam("vspId") String vspId, - @QueryParam("version") String version, + @QueryParam("versionId") String versionId, @HeaderParam(USER_ID_HEADER_PARAM) String user); @GET diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java index 9f8f3d366f..c730066770 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java @@ -38,9 +38,20 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProd import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionInfo; import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspCreationDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto; import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapVersionedVendorSoftwareProductInfoToVspDetailsDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails; +import org.openecomp.sdcrests.vsp.rest.mapping.MspVspDetailsToVspCreationDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.openecomp.sdcrests.wrappers.StringWrapperResponse; import org.slf4j.MDC; @@ -59,49 +70,49 @@ import java.util.List; @Scope(value = "prototype") public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { - private VendorSoftwareProductManager vendorSoftwareProductManager = - VspManagerFactory.getInstance().createInterface(); + private VendorSoftwareProductManager vendorSoftwareProductManager = + VspManagerFactory.getInstance().createInterface(); - private static final Logger logger = - LoggerFactory.getLogger(VendorSoftwareProductsImpl.class); + private static final Logger logger = + LoggerFactory.getLogger(VendorSoftwareProductsImpl.class); - private ActivityLogManager activityLogManager = - ActivityLogManagerFactory.getInstance().createInterface(); + private ActivityLogManager activityLogManager = + ActivityLogManagerFactory.getInstance().createInterface(); - @Override - public Response createVsp(VspDescriptionDto vspDescriptionDto, String user) { - MdcUtil.initMdc(LoggerServiceName.Create_VSP.toString()); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_VSP + vspDescriptionDto.getName()); - - VspDetails vspDetails = - new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class); + @Override + public Response createVsp(VspDescriptionDto vspDescriptionDto, String user) { + MdcUtil.initMdc(LoggerServiceName.Create_VSP.toString()); + logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_VSP + vspDescriptionDto.getName()); - vspDetails = vendorSoftwareProductManager.createVsp(vspDetails, user); + VspDetails vspDetails = + new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class); - MspVspDetailsToVspCreationDto mapping = new MspVspDetailsToVspCreationDto(); - VspCreationDto vspCreationDto = mapping.applyMapping(vspDetails, VspCreationDto.class); + vspDetails = vendorSoftwareProductManager.createVsp(vspDetails, user); - return Response.ok(vspCreationDto).build(); - } + MspVspDetailsToVspCreationDto mapping = new MspVspDetailsToVspCreationDto(); + VspCreationDto vspCreationDto = mapping.applyMapping(vspDetails, VspCreationDto.class); - @Override - public Response listVsps(String versionFilter, String user) { - MdcUtil.initMdc(LoggerServiceName.List_VSP.toString()); - List vspList = - vendorSoftwareProductManager.listVsps(versionFilter, user); - - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - if (!vspList.isEmpty()) { - MapVersionedVendorSoftwareProductInfoToVspDetailsDto mapper = - new MapVersionedVendorSoftwareProductInfoToVspDetailsDto(); - for (VersionedVendorSoftwareProductInfo versionedVsp : vspList) { - results.add(mapper.applyMapping(versionedVsp, VspDetailsDto.class)); - } - } + return Response.ok(vspCreationDto).build(); + } - return Response.ok(results).build(); + @Override + public Response listVsps(String versionFilter, String user) { + MdcUtil.initMdc(LoggerServiceName.List_VSP.toString()); + List vspList = + vendorSoftwareProductManager.listVsps(versionFilter, user); + + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + if (!vspList.isEmpty()) { + MapVersionedVendorSoftwareProductInfoToVspDetailsDto mapper = + new MapVersionedVendorSoftwareProductInfoToVspDetailsDto(); + for (VersionedVendorSoftwareProductInfo versionedVsp : vspList) { + results.add(mapper.applyMapping(versionedVsp, VspDetailsDto.class)); + } } + return Response.ok(results).build(); + } + @Override public Response getVsp(String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Get_VSP.toString()); @@ -115,15 +126,15 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); // - if(vspDetails.getOldVersion()!=null && !"".equals(vspDetails.getOldVersion())) { + if (vspDetails.getOldVersion() != null && !"".equals(vspDetails.getOldVersion())) { if (Version.valueOf(versionId).equals(versionInfo.getActiveVersion())) { try { Version healedVersion = vendorSoftwareProductManager.callAutoHeal(vspId, versionInfo, - vspDetails , user); + vspDetails, user); vspDetails = vendorSoftwareProductManager .getVsp(vspId, resolveVspVersion(vspId, healedVersion.toString(), user, - VersionableEntityAction.Read),user); + VersionableEntityAction.Read), user); versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); } catch (Exception e) { //to do @@ -137,8 +148,8 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { .applyMapping(new VersionedVendorSoftwareProductInfo(vspDetails, versionInfo), VspDetailsDto.class); - return Response.ok(vspDetailsDto).build(); - } + return Response.ok(vspDetailsDto).build(); + } @Override public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, @@ -149,23 +160,23 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { vspDetails.setId(vspId); vspDetails.setVersion(resolveVspVersion(vspId, null, user, VersionableEntityAction.Write)); - vendorSoftwareProductManager.updateVsp(vspDetails, user); + vendorSoftwareProductManager.updateVsp(vspDetails, user); - return Response.ok().build(); - } + return Response.ok().build(); + } - @Override - public Response deleteVsp(String vspId, String user) { - MdcUtil.initMdc(LoggerServiceName.Delete_VSP.toString()); - vendorSoftwareProductManager.deleteVsp(vspId, user); + @Override + public Response deleteVsp(String vspId, String user) { + MdcUtil.initMdc(LoggerServiceName.Delete_VSP.toString()); + vendorSoftwareProductManager.deleteVsp(vspId, user); - return Response.ok().build(); - } + return Response.ok().build(); + } - @Override - public Response actOnVendorSoftwareProduct(String vspId, String versionId, - VersionSoftwareProductActionRequestDto request, - String user) throws IOException { + @Override + public Response actOnVendorSoftwareProduct(String vspId, String versionId, + VersionSoftwareProductActionRequestDto request, + String user) throws IOException { switch (request.getAction()) { case Checkout: @@ -207,89 +218,88 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { return Response.ok().build(); } - @Override - public Response getValidationVsp(String user) - throws Exception { - String validationVspId = vendorSoftwareProductManager.fetchValidationVsp(user); - StringWrapperResponse response = new StringWrapperResponse(validationVspId); - return Response.ok(response).build(); - } + @Override + public Response getValidationVsp(String user) + throws Exception { + String validationVspId = vendorSoftwareProductManager.fetchValidationVsp(user); + StringWrapperResponse response = new StringWrapperResponse(validationVspId); + return Response.ok(response).build(); + } - @Override - public Response getOrchestrationTemplate(String vspId, String versionId, String user) { - MdcUtil.initMdc(LoggerServiceName.Get_Uploaded_File.toString()); - byte[] orchestrationTemplateFile = - vendorSoftwareProductManager - .getOrchestrationTemplateFile(vspId, - resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + @Override + public Response getOrchestrationTemplate(String vspId, String versionId, String user) { + MdcUtil.initMdc(LoggerServiceName.Get_Uploaded_File.toString()); + byte[] orchestrationTemplateFile = + vendorSoftwareProductManager + .getOrchestrationTemplateFile(vspId, + resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); - if (orchestrationTemplateFile == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile); - response.header("Content-Disposition", "attachment; filename=LatestHeatPackage.zip"); - return response.build(); + if (orchestrationTemplateFile == null) { + return Response.status(Response.Status.NOT_FOUND).build(); } + Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile); + response.header("Content-Disposition", "attachment; filename=LatestHeatPackage.zip"); + return response.build(); + } - @Override - public Response listPackages(String category, String subCategory, String user) { - MdcUtil.initMdc(LoggerServiceName.List_Packages.toString()); - List packageInfoList = - vendorSoftwareProductManager.listPackages(category, subCategory); + @Override + public Response listPackages(String category, String subCategory, String user) { + MdcUtil.initMdc(LoggerServiceName.List_Packages.toString()); + List packageInfoList = + vendorSoftwareProductManager.listPackages(category, subCategory); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto(); - if (packageInfoList != null) { - for (PackageInfo packageInfo : packageInfoList) { - results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class)); - } - } - return Response.ok(results).build(); + if (packageInfoList != null) { + for (PackageInfo packageInfo : packageInfoList) { + results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class)); + } } + return Response.ok(results).build(); + } @Override - public Response getTranslatedFile(String vspId, String version, String user) { + public Response getTranslatedFile(String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Get_Translated_File.toString()); - File zipFile = - vendorSoftwareProductManager.getTranslatedFile(vspId,Version.valueOf(version), user); - Version versionObj = Version.valueOf(version); - Version resolvedVersion = versionObj == null + Version version = Version.valueOf(versionId); + Version resolvedVersion = version == null ? getVersionInfo(vspId, VersionableEntityAction.Read, user).getLatestFinalVersion() - : versionObj; - + : version; - Response.ResponseBuilder response = Response.ok(zipFile); - if (zipFile == null) { - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId); - return Response.status(Response.Status.NOT_FOUND).build(); - } - response.header("Content-Disposition", "attachment; filename=" + zipFile.getName()); + File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, resolvedVersion, user); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId); - return response.build(); + Response.ResponseBuilder response = Response.ok(zipFile); + if (zipFile == null) { + logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId); + return Response.status(Response.Status.NOT_FOUND).build(); } + response.header("Content-Disposition", "attachment; filename=" + zipFile.getName()); - @Override - public Response getQuestionnaire(String vspId, String versionId, String user) { - MdcUtil.initMdc(LoggerServiceName.Get_Questionnaire_VSP.toString()); - QuestionnaireResponse questionnaireResponse = - vendorSoftwareProductManager.getVspQuestionnaire(vspId, - resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); - - if (questionnaireResponse.getErrorMessage() != null) { - return Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build(); - } + logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId); + return response.build(); + } - QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); - return Response.ok(result).build(); + @Override + public Response getQuestionnaire(String vspId, String versionId, String user) { + MdcUtil.initMdc(LoggerServiceName.Get_Questionnaire_VSP.toString()); + QuestionnaireResponse questionnaireResponse = + vendorSoftwareProductManager.getVspQuestionnaire(vspId, + resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + + if (questionnaireResponse.getErrorMessage() != null) { + return Response.status(Response.Status.EXPECTATION_FAILED).entity( + new MapQuestionnaireResponseToQuestionnaireResponseDto() + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build(); } + QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); + return Response.ok(result).build(); + } + @Override public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) { @@ -300,26 +310,26 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { return Response.ok().build(); } - @Override - public Response heal(String vspId, String versionId, String user) { - vendorSoftwareProductManager.heal(vspId, Version.valueOf(versionId), user); - - return Response.ok().build(); - } + @Override + public Response heal(String vspId, String versionId, String user) { + vendorSoftwareProductManager.heal(vspId, Version.valueOf(versionId), user); - @Override - public Response getVspInformationArtifact(String vspId, String versionId, String user) { - MdcUtil.initMdc(LoggerServiceName.Get_Information_Artifact.toString()); - File textInformationArtifact = - vendorSoftwareProductManager.getInformationArtifact(vspId, - resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + return Response.ok().build(); + } - Response.ResponseBuilder response = Response.ok(textInformationArtifact); - if (textInformationArtifact == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - response - .header("Content-Disposition", "attachment; filename=" + textInformationArtifact.getName()); - return response.build(); + @Override + public Response getVspInformationArtifact(String vspId, String versionId, String user) { + MdcUtil.initMdc(LoggerServiceName.Get_Information_Artifact.toString()); + File textInformationArtifact = + vendorSoftwareProductManager.getInformationArtifact(vspId, + resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + + Response.ResponseBuilder response = Response.ok(textInformationArtifact); + if (textInformationArtifact == null) { + return Response.status(Response.Status.NOT_FOUND).build(); } + response + .header("Content-Disposition", "attachment; filename=" + textInformationArtifact.getName()); + return response.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java index 451415c5ea..eb559f2e62 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java @@ -25,6 +25,8 @@ import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -87,6 +89,8 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { LicenseKeyGroupDaoFactory.getInstance().createInterface(); private ActivityLogManager activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static final Logger logger = + LoggerFactory.getLogger(VendorLicenseManagerImpl.class); private static void sortVlmListByModificationTimeDescOrder( List vendorLicenseModels) { @@ -178,14 +182,21 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { version.setStatus(VersionStatus.Locked); } - VendorLicenseModelEntity vlm = - vendorLicenseModelDao.get(new VendorLicenseModelEntity(entry.getKey(), version)); - if (vlm != null) { - VersionedVendorLicenseModel versionedVlm = new VersionedVendorLicenseModel(); - versionedVlm.setVendorLicenseModel(vlm); - versionedVlm.setVersionInfo(versionInfo); - vendorLicenseModels.add(versionedVlm); - } + try { + VendorLicenseModelEntity vlm = + vendorLicenseModelDao.get(new VendorLicenseModelEntity(entry.getKey(), version)); + if (vlm != null) { + VersionedVendorLicenseModel versionedVlm = new VersionedVendorLicenseModel(); + versionedVlm.setVendorLicenseModel(vlm); + versionedVlm.setVersionInfo(versionInfo); + vendorLicenseModels.add(versionedVlm); + } + }catch(RuntimeException rte){ + logger.error("Error trying to retrieve vlm["+entry.getKey()+"] version["+version.toString + ()+"] " + + "message:"+rte + .getMessage()); + } } sortVlmListByModificationTimeDescOrder(vendorLicenseModels); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/VSPPackage.zip b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/VSPPackage.zip deleted file mode 100644 index ca55484a3c..0000000000 Binary files a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/VSPPackage.zip and /dev/null differ diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java index 65aab2d9f4..77d496f0c8 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java @@ -26,7 +26,11 @@ import org.openecomp.sdc.activitylog.dao.ActivityLogDaoFactory; import org.openecomp.sdc.healing.factory.HealingManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.MibDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; @@ -45,6 +49,10 @@ public class OrchestrationTemplateCandidateManagerFactoryImpl extends CompositionDataExtractorFactory.getInstance().createInterface(), ServiceModelDaoFactory.getInstance().createInterface(), CompositionEntityDataManagerFactory.getInstance().createInterface(), + NicDaoFactory.getInstance().createInterface(), + ComponentDaoFactory.getInstance().createInterface(), + MibDaoFactory.getInstance().createInterface(), + ProcessDaoFactory.getInstance().createInterface(), ActivityLogManagerFactory.getInstance().createInterface()); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java index 9373bfb3a6..99a438f3a8 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java @@ -19,11 +19,15 @@ */ package org.openecomp.sdc.vendorsoftwareproduct.impl; - +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.GENERAL_COMPONENT_ID; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues + .PROCESS_NAME; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; +import org.apache.xalan.xslt.Process; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.types.ServiceElement; +import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; @@ -51,10 +55,16 @@ import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.validation.util.ValidationManagerUtil; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.MibDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.MibEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.errors.OrchestrationTemplateNotFoundErrorBuilder; @@ -69,7 +79,8 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStru import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdcrests.activitylog.types.ActivityType; - +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -78,6 +89,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Collection; public class OrchestrationTemplateCandidateManagerImpl implements OrchestrationTemplateCandidateManager { @@ -93,7 +105,11 @@ public class OrchestrationTemplateCandidateManagerImpl private CompositionDataExtractor compositionDataExtractor; private ServiceModelDao serviceModelDao; private CompositionEntityDataManager compositionEntityDataManager; + private NicDao nicDao; + private ComponentDao componentDao; + private MibDao mibDao; private ActivityLogManager activityLogManager; + private ProcessDao processDao; public OrchestrationTemplateCandidateManagerImpl( VendorSoftwareProductDao vendorSoftwareProductDao, VendorSoftwareProductInfoDao @@ -103,6 +119,10 @@ public class OrchestrationTemplateCandidateManagerImpl CompositionDataExtractor compositionDataExtractor, ServiceModelDao serviceModelDao, CompositionEntityDataManager compositionEntityDataManager, + NicDao nicDao, + ComponentDao componentDao, + MibDao mibDao, + ProcessDao processDao, ActivityLogManager activityLogManager) { this.vendorSoftwareProductDao = vendorSoftwareProductDao; this.vspInfoDao = vspInfoDao; @@ -112,6 +132,10 @@ public class OrchestrationTemplateCandidateManagerImpl this.compositionDataExtractor = compositionDataExtractor; this.serviceModelDao = serviceModelDao; this.compositionEntityDataManager = compositionEntityDataManager; + this.nicDao = nicDao; + this.componentDao = componentDao; + this.mibDao = mibDao; + this.processDao = processDao; this.activityLogManager = activityLogManager; } @@ -220,6 +244,15 @@ public class OrchestrationTemplateCandidateManagerImpl if (!zipByteArrayInputStream.isPresent()) { return response; } + Map componentsQustanniare = new HashMap<>(); + Map> componentNicsQustanniare = new HashMap<>(); + Map> componentMIBList = new HashMap<>(); + Map> processes = new HashMap<>(); + Map processArtifact = new HashMap<>(); + + backupComponentsQuestionnaireBeforeDelete(vspId, version, componentsQustanniare, + componentNicsQustanniare, componentMIBList, processes, processArtifact); + deleteUploadDataAndContent(vspId, version); saveHotData(vspId, version, zipByteArrayInputStream.get(), fileContentMap, tree); @@ -230,6 +263,8 @@ public class OrchestrationTemplateCandidateManagerImpl serviceModelDao.storeServiceModel(vspId, version, toscaServiceModel); compositionEntityDataManager.saveCompositionData(vspId, version, compositionDataExtractor.extractServiceCompositionData(toscaServiceModel)); + retainComponentQuestionnaireData(vspId, version, componentsQustanniare, + componentNicsQustanniare, componentMIBList, processes, processArtifact); } uploadFileResponse.addStructureErrors(uploadErrors); @@ -330,6 +365,133 @@ public class OrchestrationTemplateCandidateManagerImpl .ofNullable(candidateService.getOrchestrationTemplateCandidate(vspId, version)); } + private void retainComponentQuestionnaireData(String vspId, Version activeVersion, + Map componentsQustanniare, + Map> componentNicsQustanniare, + Map> componentMIBList, + Map> processes, + Map processArtifact) { + //VSP processes + restoreProcess(vspId, activeVersion, GENERAL_COMPONENT_ID, GENERAL_COMPONENT_ID, processes, + processArtifact); + Collection + components = vendorSoftwareProductDao.listComponents(vspId, activeVersion); + components.forEach(componentEntity -> { + String componentName = componentEntity.getComponentCompositionData().getName(); + if( componentsQustanniare.containsKey(componentName) ){ + componentDao.updateQuestionnaireData(vspId, activeVersion, + componentEntity.getId(),componentsQustanniare.get(componentEntity.getComponentCompositionData() + .getName())); + if( componentNicsQustanniare.containsKey(componentName) ){ + Map nicsQustanniare=componentNicsQustanniare.get(componentName); + Collection + nics=nicDao.list(new NicEntity(vspId, activeVersion, componentEntity.getId(), null)); + nics.forEach(nicEntity -> { + if(nicsQustanniare.containsKey(nicEntity.getNicCompositionData().getName())){ + nicDao.updateQuestionnaireData(vspId, activeVersion,componentEntity.getId + (),nicEntity.getId(),nicsQustanniare.get(nicEntity.getNicCompositionData().getName())); + } + }); + } + //MIB + if(componentMIBList.containsKey(componentName)) { + Collection mibList = componentMIBList.get(componentName); + mibList.forEach(mib -> { + mib.setComponentId(componentEntity.getId()); + mibDao.create(mib); + }); + } + //VFC processes + restoreProcess(vspId, activeVersion, componentEntity.getId(), componentName, processes, + processArtifact); + } + }); + } + + private void backupComponentsQuestionnaireBeforeDelete(String vspId, Version activeVersion, + Map componentsQustanniare, + Map> + componentNicsQustanniare, + Map> + componentMIBList, + Map> componentProcesses, + Map processArtifact) { + //backup VSP processes + backupProcess(vspId, activeVersion, GENERAL_COMPONENT_ID, GENERAL_COMPONENT_ID, + componentProcesses,processArtifact); + Collection componentsCompositionAndQuestionnaire= vendorSoftwareProductDao + .listComponentsCompositionAndQuestionnaire(vspId, + activeVersion); + componentsCompositionAndQuestionnaire.forEach(componentEntity ->{ + String componentName=componentEntity.getComponentCompositionData().getName(); + componentsQustanniare.put(componentName,componentEntity + .getQuestionnaireData()); + Collection + nics=nicDao.list(new NicEntity(vspId, activeVersion,componentEntity.getId(),null)); + //backup mib + Collection componentMIB = mibDao.listArtifacts(new + MibEntity(vspId, activeVersion, componentEntity.getId(), null)); + if(CollectionUtils.isNotEmpty(componentMIB)){ + componentMIBList.put(componentName,componentMIB); + } + + //backup component processes + backupProcess(vspId, activeVersion, componentEntity.getId(), componentName, + componentProcesses,processArtifact); + if(CollectionUtils.isNotEmpty(nics)) { + Map nicsQustanniare = new HashMap<>(); + nics.forEach(nicEntity -> { + NicEntity nic = nicDao.get(new NicEntity(vspId, activeVersion, componentEntity.getId(), + nicEntity.getId())); + NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId,activeVersion, + componentEntity.getId(),nicEntity.getId()); + + nicsQustanniare + .put(nicEntity.getNicCompositionData().getName(), nicQuestionnaire.getQuestionnaireData()); + }); + componentNicsQustanniare.put(componentName, nicsQustanniare); + } + }); + } + + private void backupProcess(String vspId, Version activeVersion, String componentId, + String componentName, Map> processes, + Map processArtifact){ + Collection processList = vendorSoftwareProductDao.listProcesses(vspId, + activeVersion, componentId); + if(!processList.isEmpty()){ + processes.put(componentName,processList); + processList.forEach(process -> { + //ProcessArtifactEntity artifact = vendorSoftwareProductDao.getProcessArtifact(vspId, + // activeVersion, componentId, process.getId()); + ProcessEntity artifact = processDao.get(new ProcessEntity(vspId,activeVersion,componentId,process.getId())); + if(artifact.getArtifact()!=null) { + processArtifact.put(process.getId(), artifact); + } + }); + } + } + + private void restoreProcess(String vspId, Version activeVersion, String componentId, + String componentName, Map> processes, + Map processArtifact){ + if(processes.containsKey(componentName)) { + Collection processList = processes.get(componentName); + processList.forEach(process -> { + //Reatin VFC process + if (!GENERAL_COMPONENT_ID.equals(componentId) && processArtifact.containsKey(process.getId + ())) { + ProcessEntity artifact = processArtifact.get(process.getId()); + artifact.setComponentId(componentId); + UniqueValueUtil.createUniqueValue(PROCESS_NAME, vspId, activeVersion.toString(), + componentId, process.getName()); + vendorSoftwareProductDao.createProcess(artifact); + } + }); + } + } + private HeatStructureTree createAndValidateHeatTree(OrchestrationTemplateActionResponse response, FileContentHandler fileContentMap) { VendorSoftwareProductUtils.addFileNamesToUploadFileResponse(fileContentMap, response); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java index 0d2023f387..2d1b62cd40 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java @@ -472,10 +472,17 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa if (user.equals(versionInfo.getLockingUser())) { version.setStatus(VersionStatus.Locked); } - VspDetails vsp = vspInfoDao.get(new VspDetails(entry.getKey(), version)); - if (vsp != null && !vsp.getId().equals(VALIDATION_VSP_ID)) { - vsp.setValidationDataStructure(null); - vsps.add(new VersionedVendorSoftwareProductInfo(vsp, versionInfo)); + try { + VspDetails vsp = vspInfoDao.get(new VspDetails(entry.getKey(), version)); + if (vsp != null && !vsp.getId().equals(VALIDATION_VSP_ID)) { + vsp.setValidationDataStructure(null); + vsps.add(new VersionedVendorSoftwareProductInfo(vsp, versionInfo)); + } + }catch(RuntimeException rte){ + logger.error("Error trying to retrieve vsp["+entry.getKey()+"] version["+version.toString + ()+"] " + + "message:"+rte + .getMessage()); } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java index 0be6a55df6..f850afbab8 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java @@ -35,7 +35,7 @@ public enum Messages { MANIFEST_NOT_EXIST("Manifest doesn't exist"), FILE_TYPE_NOT_LEGAL("File type not legal as data for other file"), MODULE_IN_MANIFEST_NO_YAML("Module '%s', has no yaml file reference"), - NO_MODULES_IN_MANIFEST("At least on Base/Module must be defined \n"), + NO_MODULES_IN_MANIFEST("At least one Base/Module must be defined \n"), MODULE_IN_MANIFEST_VOL_ENV_NO_VOL("Module '%s', has volume Env. reference with no Volume " + "reference"), ILLEGAL_MANIFEST("Illegal Manifest"), diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml index bab8bc0e01..08a09273c6 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml @@ -31,7 +31,7 @@ com.amdocs.zusammen zusammen-adaptor-inbound-api - 0.0.1-SNAPSHOT + 0.0.1 org.openecomp.sdc diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/pom.xml index 9bb1e1dbc0..c1870d8c64 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/pom.xml @@ -21,17 +21,17 @@ com.amdocs.zusammen zusammen-commons-utils - 0.0.1-SNAPSHOT + 0.0.1 com.amdocs.zusammen zusammen-adaptor-inbound-api - 0.0.1-SNAPSHOT + 0.0.1 com.amdocs.zusammen zusammen-adaptor-inbound-impl - 0.0.1-SNAPSHOT + 0.0.1 runtime @@ -53,7 +53,7 @@ com.amdocs.zusammen.plugin zusammen-search-index-empty-plugin - 0.0.1-SNAPSHOT + 0.0.1 runtime diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml index ff45d1fa56..57f92f1b09 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml @@ -15,23 +15,23 @@ com.amdocs.zusammen zusammen-sdk - 0.0.1-SNAPSHOT + 0.0.1 com.amdocs.zusammen zusammen-commons-db-api - 0.0.1-SNAPSHOT + 0.0.1 com.amdocs.zusammen zusammen-commons-db-impl - 0.0.1-SNAPSHOT + 0.0.1 runtime com.amdocs.zusammen.plugin zusammen-state-store-cassandra-plugin - 0.0.1-SNAPSHOT + 0.0.1 diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java index 283f6c83b6..99e0a0ac6c 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java @@ -172,7 +172,9 @@ public class CompositionDataHealer implements Healer { JsonUtil.json2Object(component.getCompositionData(), ComponentData.class); componentData .setDisplayName(compositionDataExtractor.getComponentDisplayName(componentData.getName())); - componentData.setVfcCode(componentData.getDisplayName()); + String displayName = componentData.getDisplayName(); + componentData.setName(displayName); + componentData.setVfcCode(displayName); component.setCompositionData(JsonUtil.object2Json(componentData)); mdcDataDebugMessage.debugExitMessage("VSP id, component id", component.getVspId(), component diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java index 3c27a0fac8..fb0622cd67 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java @@ -26,6 +26,8 @@ import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.enrichment.inter.Enricher; import org.openecomp.sdc.enrichment.inter.ExternalArtifactEnricherInterface; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import java.io.InputStream; @@ -43,6 +45,7 @@ public class ExternalArtifactEnricher extends Enricher { "An Error has occured during enrichment of external artifacts "; private static Collection implementingClasses = getExternalArtifactEnrichedImplClassesList(); + private static Logger logger = LoggerFactory.getLogger(ExternalArtifactEnricher.class); private static Collection getExternalArtifactEnrichedImplClassesList() { InputStream externalArtifactEnrichConfigurationJson = @@ -68,7 +71,8 @@ public class ExternalArtifactEnricher extends Enricher { externalArtifactEnricherInstance.enrich(this.data); } } catch (Exception e) { - e.printStackTrace(); //// FIXME: 29-Nov-16 + e.printStackTrace(); + logger.error(e.getMessage()); } mdcDataDebugMessage.debugExitMessage(null, null); diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java index b4a2815d69..a5f6529bbb 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java @@ -80,14 +80,15 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac componentId, entity.getId());*/ processes.stream() - .filter(entity -> entity.getType().equals(ProcessType.Lifecycle_Operations)) .forEach(entity -> { ProcessEntity artifactEntity = new ProcessEntity(vspId, version, componentId, entity.getId()); ProcessEntity artifactProcessEntity = getProcessDao().get(artifactEntity); //ProcessArtifactEntity artifact = getProcessArtifactDao().get(artifactEntity); - if (artifactProcessEntity != null) { + if (artifactProcessEntity != null && ProcessType.Lifecycle_Operations.equals( + artifactProcessEntity.getType()) + && artifactProcessEntity.getArtifactName() != null ) { String componentName = componentEntity.getComponentCompositionData().getName(); String path = componentName + File.separator + ArtifactCategory.DEPLOYMENT.getDisplayName() + File.separator diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java index d75c83f24c..93c4e67fc9 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java @@ -59,6 +59,7 @@ public class AbstractSubstituteToscaEnricher { final Map node_templates = serviceTemplate.getTopology_template().getNode_templates(); + if(node_templates == null) return errors; final Map> componentDisplayNameToNodeTempalteIds = populateAllNodeTemplateIdForComponent(node_templates, serviceTemplate, toscaModel); diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java index cfb241483a..aeefc91aa3 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java @@ -28,6 +28,7 @@ import java.util.Collection; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; public class ProcessArtifactEnricherTest { @@ -56,7 +57,6 @@ public class ProcessArtifactEnricherTest { version.setMinor(0); ComponentEntity componentEntity = getComponentEntity(vspId, version, componentId); - setMockToEnrichComponent(vspId, componentId, version); ProcessEntity entity = new ProcessEntity(vspId, version, componentId, null); ProcessEntity processEntity = new ProcessEntity(); @@ -64,6 +64,8 @@ public class ProcessArtifactEnricherTest { processEntity.setVspId(vspId); processEntity.setVersion(version); processEntity.setComponentId(componentId); + processEntity.setArtifactName("artifact_1kb.txt"); + processEntity.setArtifact(getMibByteBuffer("/mock/enrichProcess/artifact_1kb.txt")); Collection componentList = new ArrayList(); componentList.add(componentEntity); @@ -73,6 +75,8 @@ public class ProcessArtifactEnricherTest { list.add(processEntity); when(processDaoMock.list(entity)).thenReturn(list); + when(processDaoMock.get(anyObject())).thenReturn(processEntity); + EnrichmentInfo info = new EnrichmentInfo(); info.setVersion(version); info.setKey(vspId); @@ -92,19 +96,6 @@ public class ProcessArtifactEnricherTest { } - private void setMockToEnrichComponent(String vspId, String componentId, Version version) { - ProcessEntity returnedArtifact = new ProcessEntity(); - returnedArtifact.setVspId(vspId); - returnedArtifact.setVersion(version); - returnedArtifact.setComponentId(componentId); - returnedArtifact.setArtifactName("artifact_1kb.txt"); - returnedArtifact.setArtifact(getMibByteBuffer("/mock/enrichProcess/artifact_1kb.txt")); - - Mockito.when(processDaoMock.get(anyObject())) - .thenReturn(returnedArtifact); - Mockito.doNothing().when(enrichedServiceModelDaoMock).storeExternalArtifact(anyObject()); - } - private ComponentEntity getComponentEntity(String vspId, Version version, String componentId) { ComponentEntity componentEntity = new ComponentEntity(); componentEntity.setId(componentId); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java index 736318bcab..c036e39c21 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java @@ -42,8 +42,11 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -58,6 +61,7 @@ public class TranslationContext { private static Map nameExtractorImplMap; private static Map supportedConsolidationComputeResources; private static Map supportedConsolidationPortResources; + private static List enrichPortResourceProperties; static { Configuration config = ConfigurationManager.lookup(); @@ -77,11 +81,19 @@ public class TranslationContext { supportedConsolidationPortResources = config.populateMap(ConfigConstants .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants .SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, ImplementationConfiguration.class); + enrichPortResourceProperties = config.getAsStringValues(ConfigConstants + .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants + .ENRICH_PORT_RESOURCE_PROP); } private Map unifiedSubstitutionData = new HashMap<>(); private ManifestFile manifest; + + public static List getEnrichPortResourceProperties() { + return enrichPortResourceProperties; + } + private FileContentHandler files = new FileContentHandler(); private Map manifestFiles = new HashMap<>(); //Key - file name, value - file type @@ -242,6 +254,19 @@ public class TranslationContext { return translatedIds; } + public Set getAllTranslatedResourceIdsFromDiffNestedFiles(String + nestedHeatFileNameToSkip){ + Set allTranslatedResourceIds = new HashSet<>(); + + this.translatedIds.entrySet().stream().filter( + heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey() + .equals(nestedHeatFileNameToSkip)).forEach(heatFileNameToTranslatedIdsEntry -> { + allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet()); + }); + + return allTranslatedResourceIds; + } + // get tosca name from mapping configuration file //element type - parameter/attribute // element name - heat parameter/attribute name @@ -449,4 +474,6 @@ public class TranslationContext { return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex (computeType); } + + } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java index f6918e382b..ca9f21b79a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java @@ -40,6 +40,9 @@ public class ConfigConstants { "supportedConsolidationComputeResources"; public static final String SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY = "supportedConsolidationPortResources"; + public static final String ENRICH_PORT_RESOURCE_PROP = + "enrichPortResourceProperties"; + //others public static final String TRANS_MAPPING_DELIMITER_CHAR = "#"; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java index a89d08bcf6..148e754cfd 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java @@ -2,6 +2,8 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.math.NumberUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -141,13 +143,21 @@ public class ConsolidationDataUtil { * * @param context the context * @param serviceTemplate the service template - * @param nestedNodeTemplateId the nested node template id - * @return the nested template consolidation data + * @param nestedHeatFileName + *@param nestedNodeTemplateId the nested node template id @return the nested template consolidation data */ public static NestedTemplateConsolidationData getNestedTemplateConsolidationData( TranslationContext context, ServiceTemplate serviceTemplate, - String nestedNodeTemplateId) { + String nestedHeatFileName, String nestedNodeTemplateId) { + + if(isNestedResourceIdOccuresInDifferentNestedFiles(context, nestedHeatFileName, + nestedNodeTemplateId)){ + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage("Resource with id " + + nestedNodeTemplateId + " occures more than once in different addOn " + + "files").build()); + } ConsolidationData consolidationData = context.getConsolidationData(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); @@ -176,6 +186,12 @@ public class ConsolidationDataUtil { return nestedTemplateConsolidationData; } + private static boolean isNestedResourceIdOccuresInDifferentNestedFiles(TranslationContext context, + String nestedHeatFileName, + String nestedNodeTemplateId) { + return context.getAllTranslatedResourceIdsFromDiffNestedFiles(nestedHeatFileName).contains(nestedNodeTemplateId); + } + /** * Update group id information in consolidation data. * @@ -372,7 +388,7 @@ public class ConsolidationDataUtil { } else if (consolidationEntityType == ConsolidationEntityType.NESTED || consolidationEntityType == ConsolidationEntityType.VFC_NESTED) { entityConsolidationData = getNestedTemplateConsolidationData(translationContext, - serviceTemplate, dependentNodeTemplateId); + serviceTemplate, translateTo.getHeatFileName(), dependentNodeTemplateId); } if (entityConsolidationData.getNodesConnectedIn() == null) { @@ -530,7 +546,8 @@ public class ConsolidationDataUtil { public static void updateNestedNodeTemplateId(TranslateTo translateTo) { TranslationContext context = translateTo.getContext(); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - getNestedTemplateConsolidationData(context, serviceTemplate, translateTo.getTranslatedId()); + getNestedTemplateConsolidationData( + context, serviceTemplate, translateTo.getHeatFileName(), translateTo.getTranslatedId()); } public static void removeSharedResource(ServiceTemplate serviceTemplate, diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java index 471b1475d6..336d56a77f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java @@ -46,6 +46,7 @@ import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.NodeType; import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; import org.openecomp.sdc.tosca.datatypes.model.PropertyType; import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; @@ -66,6 +67,7 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FilePortConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; @@ -346,12 +348,13 @@ public class UnifiedCompositionService { List unifiedCompositionDataList, TranslationContext context) { handleUnifiedNestedNodeType(mainServiceTemplate, nestedServiceTemplate, context); - updateUnifiedNestedTemplates(mainServiceTemplate, nestedServiceTemplate, unifiedCompositionDataList, context); + updateUnifiedNestedTemplates(mainServiceTemplate, nestedServiceTemplate, + unifiedCompositionDataList, context); } private void handleGetAttrInConnectivity(ServiceTemplate serviceTemplate, - Set unifiedNodeIds, - TranslationContext context) { + Set unifiedNodeIds, + TranslationContext context) { Map nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); @@ -387,7 +390,7 @@ public class UnifiedCompositionService { context.getGlobalSubstitutionServiceTemplate(); newNestedNodeTypeId.ifPresent( - newNestedNodeTypeIdVal -> updateNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, + newNestedNodeTypeIdVal -> handleNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, nestedServiceTemplate, mainServiceTemplate, globalSubstitutionServiceTemplate, context)); @@ -403,26 +406,97 @@ public class UnifiedCompositionService { ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); } + private void handleNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, + ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + updateNestedServiceTemplate(nestedServiceTemplate, context); + updateNestedNodeType(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, + mainServiceTemplate, + globalSubstitutionServiceTemplate, context); + + + } + + private void updateNestedServiceTemplate(ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + enrichPortProperties(nestedServiceTemplate, context); + } + + private void enrichPortProperties(ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + String nestedServiceTemplateFileName = + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); + FilePortConsolidationData filePortConsolidationData = + context.getConsolidationData().getPortConsolidationData().getFilePortConsolidationData + (nestedServiceTemplateFileName); + + if (Objects.nonNull(filePortConsolidationData)) { + Set portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); + if (Objects.nonNull(portNodeTemplateIds)) { + for (String portNodeTemplateId : portNodeTemplateIds) { + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(nestedServiceTemplate, + portNodeTemplateId); + List portEntityConsolidationDataList = new ArrayList<>(); + portEntityConsolidationDataList.add(filePortConsolidationData + .getPortTemplateConsolidationData(portNodeTemplateId)); + + handleNodeTypeProperties(nestedServiceTemplate, + portEntityConsolidationDataList, portNodeTemplate, UnifiedCompositionEntity.Port, + null, context); + } + } + } + } + private void updateNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { + String indexedNewNestedNodeTypeId = + updateNodeTypeId(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, + mainServiceTemplate, + globalSubstitutionServiceTemplate, context); + + updateNodeTypeProperties(nestedServiceTemplate, globalSubstitutionServiceTemplate, + indexedNewNestedNodeTypeId); + } + + private void updateNodeTypeProperties(ServiceTemplate nestedServiceTemplate, + ServiceTemplate globalSubstitutionServiceTemplate, + String nodeTypeId) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Map nodeTypePropertiesDefinition = + toscaAnalyzerService.manageSubstitutionNodeTypeProperties(nestedServiceTemplate); + NodeType nestedNodeType = + DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, nodeTypeId); + nestedNodeType.setProperties(nodeTypePropertiesDefinition); + } + + private String updateNodeTypeId(String nodeTypeId, String newNestedNodeTypeId, + ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { context.addNestedFileToUsedNestedComputeType( - ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), - newNestedNodeTypeId); - String indexedNodeType = + ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), + newNestedNodeTypeId); + String indexedNewNestedNodeTypeId = handleNestedNodeTypeInGlobalSubstitutionTemplate(nodeTypeId, newNestedNodeTypeId, mainServiceTemplate, globalSubstitutionServiceTemplate, context); - handleSubstitutionMappingInNestedServiceTemplate(indexedNodeType, nestedServiceTemplate); + handleSubstitutionMappingInNestedServiceTemplate(indexedNewNestedNodeTypeId, + nestedServiceTemplate); context .updateHandledComputeType( ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), newNestedNodeTypeId); + return indexedNewNestedNodeTypeId; } private String handleNestedNodeTypeInGlobalSubstitutionTemplate(String nodeTypeId, @@ -458,7 +532,9 @@ public class UnifiedCompositionService { if (Objects.isNull(nestedTemplateConsolidationData)) { continue; } - handleNestedNodeTemplateInMainServiceTemplate(nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, nestedServiceTemplate, context); + handleNestedNodeTemplateInMainServiceTemplate( + nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, + nestedServiceTemplate, context); } } @@ -1566,9 +1642,29 @@ public class UnifiedCompositionService { ComputeTemplateConsolidationData computeTemplateConsolidationData, List unifiedCompositionDataList, TranslationContext context) { - List propertiesWithIdenticalVal = consolidationService.getPropertiesWithIdenticalVal(); + nodeTemplate.setProperties(new HashedMap()); + handleNodeTemplateProperties(serviceTemplate, nodeTemplate, substitutionServiceTemplate, + unifiedCompositionEntity, entityConsolidationDataList, computeTemplateConsolidationData, + unifiedCompositionDataList, context); + //Add enrich properties from openecomp node type as input to global and substitution ST + handleNodeTypeProperties(substitutionServiceTemplate, + entityConsolidationDataList, nodeTemplate, unifiedCompositionEntity, + computeTemplateConsolidationData, context); + + } + private void handleNodeTemplateProperties(ServiceTemplate serviceTemplate, + NodeTemplate nodeTemplate, + ServiceTemplate substitutionServiceTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, + List + entityConsolidationDataList, + ComputeTemplateConsolidationData + computeTemplateConsolidationData, + List unifiedCompositionDataList, + TranslationContext context) { + List propertiesWithIdenticalVal = consolidationService.getPropertiesWithIdenticalVal(); for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); Map properties = @@ -1588,7 +1684,6 @@ public class UnifiedCompositionService { unifiedCompositionEntity, computeTemplateConsolidationData, unifiedCompositionDataList, context); - //todo - define list of type which will match the node property type (instead of string) NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil.getNodeTypeWithFlatHierarchy(nodeTemplate.getType(), serviceTemplate, @@ -1596,30 +1691,82 @@ public class UnifiedCompositionService { String propertyType = nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()) .getType(); + addPropertyInputParameter(propertyType, substitutionServiceTemplate, parameterId); + } + } + } + } + + private void handleNodeTypeProperties(ServiceTemplate substitutionServiceTemplate, + List entityConsolidationDataList, + NodeTemplate nodeTemplate, + UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData + computeTemplateConsolidationData, + TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Optional enrichNodeType = Optional.empty(); + List enrichProperties = new ArrayList<>(); + + if (compositionEntity.equals(UnifiedCompositionEntity.Port)) { + enrichNodeType = + toscaAnalyzerService.fetchNodeType(ToscaNodeType.NETWORK_PORT, + context.getGlobalServiceTemplates().values()); + enrichProperties = context.getEnrichPortResourceProperties(); + if (!enrichNodeType.isPresent() || Objects.isNull(enrichProperties)) { + return; + } + } else { + return; + } - if (propertyType.equalsIgnoreCase(PropertyType.STRING.getDisplayName()) - || propertyType.equalsIgnoreCase(PropertyType.INTEGER.getDisplayName()) - || propertyType.equalsIgnoreCase(PropertyType.FLOAT.getDisplayName()) - || propertyType.equalsIgnoreCase(PropertyType.BOOLEAN.getDisplayName())) { - parameterId - .ifPresent(parameterIdValue -> addInputParameter(parameterIdValue, - PropertyType.LIST.getDisplayName(), - DataModelUtil - .createEntrySchema(propertyType.toLowerCase(), null, null), - substitutionServiceTemplate)); - } else { - parameterId - .ifPresent(parameterIdValue -> addInputParameter(parameterIdValue, - PropertyType.LIST.getDisplayName(), - DataModelUtil - .createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), - substitutionServiceTemplate)); + Map nodeTemplateProperties = nodeTemplate.getProperties(); + Map enrichNodeTypeProperties = enrichNodeType.get().getProperties(); + if (Objects.nonNull(enrichNodeTypeProperties)) { + for (String enrichPropertyName : enrichProperties) { + if (!nodeTemplateProperties.containsKey(enrichPropertyName)) { + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + String inputParamId = + getParameterId(nodeTemplateId, nodeTemplate, enrichPropertyName, + compositionEntity, computeTemplateConsolidationData); + Map> propertyVal = getPropertyValueInputParam(nodeTemplateId, + nodeTemplate, inputParamId); + nodeTemplate.getProperties().put(enrichPropertyName, propertyVal); + String propertyType = + enrichNodeType.get().getProperties().get(enrichPropertyName).getType(); + addPropertyInputParameter(propertyType, substitutionServiceTemplate, + Optional.of(inputParamId)); } } } } } + + private void addPropertyInputParameter(String propertyType, + ServiceTemplate substitutionServiceTemplate, + Optional parameterId) { + if (propertyType.equalsIgnoreCase(PropertyType.STRING.getDisplayName()) + || propertyType.equalsIgnoreCase(PropertyType.INTEGER.getDisplayName()) + || propertyType.equalsIgnoreCase(PropertyType.FLOAT.getDisplayName()) + || propertyType.equalsIgnoreCase(PropertyType.BOOLEAN.getDisplayName())) { + parameterId + .ifPresent(parameterIdValue -> addInputParameter(parameterIdValue, + PropertyType.LIST.getDisplayName(), + DataModelUtil + .createEntrySchema(propertyType.toLowerCase(), null, null), + substitutionServiceTemplate)); + } else { + parameterId + .ifPresent(parameterIdValue -> addInputParameter(parameterIdValue, + PropertyType.LIST.getDisplayName(), + DataModelUtil + .createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), + substitutionServiceTemplate)); + } + } + private void handleConsolidationEntitiesRequirementConnectivity(String nodeTemplateId, NodeTemplate nodeTemplate, ServiceTemplate @@ -1716,17 +1863,24 @@ public class UnifiedCompositionService { unifiedCompositionDataList, context)) { return Optional.empty(); } - - Map> propertyVal = new HashMap<>(); - List getInputFuncParams = new ArrayList<>(); String inputParamId = getParameterId(nodeTemplateId, nodeTemplate, propertyEntry.getKey(), compositionEntity, computeTemplateConsolidationData); + Map> propertyVal = getPropertyValueInputParam(nodeTemplateId, + nodeTemplate, inputParamId); + nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); + return Optional.of(inputParamId); + } + + private Map> getPropertyValueInputParam(String nodeTemplateId, + NodeTemplate nodeTemplate, + String inputParamId) { + Map> propertyVal = new HashMap<>(); + List getInputFuncParams = new ArrayList<>(); getInputFuncParams.add(inputParamId); getInputFuncParams.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); propertyVal.put(ToscaFunctions.GET_INPUT.getDisplayName(), getInputFuncParams); - nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); - return Optional.of(inputParamId); + return propertyVal; } private boolean handleGetAttrFromConsolidationNodes( @@ -1863,7 +2017,8 @@ public class UnifiedCompositionService { + getComputeTypeSuffix(nodeTemplate.getType()) + "_" + propertyId; case Port: String portType = ConsolidationDataUtil.getPortType(nodeTemplateId); - if (computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + if (Objects.isNull(computeTemplateConsolidationData) + || computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { return UnifiedCompositionEntity.Port.name().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; } @@ -2015,7 +2170,13 @@ public class UnifiedCompositionService { default: break; } - abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + //Add the property only if it has at least one non-null value + for (Object val : abstractPropertyValue) { + if (Objects.nonNull(val)) { + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + break; + } + } } return Optional.ofNullable(abstractSubstituteProperties); } @@ -2184,7 +2345,8 @@ public class UnifiedCompositionService { context.getHandledNestedComputeNodeTemplateIndex(mainServiceTemplateName, newNestedNodeTypeId); String newNodeTemplateId = - Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) + "_" + index; + Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) + + "_" + index; nestedNodeTemplate.setType(newNestedNodeTypeId); mainServiceTemplate.getTopology_template().getNode_templates().remove(nestedNodeTemplateId); @@ -2388,7 +2550,9 @@ public class UnifiedCompositionService { if (propertyName.isPresent()) { NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, portNodeTemplateId); - return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); + if (Objects.nonNull(portNodeTemplate)) { + return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); + } } return Optional.empty(); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java index cc188d71a6..823daa53c8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java @@ -276,7 +276,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { .getPortTemplateConsolidationData(context, serviceTemplate, resourceId)); } else if (HeatToToscaUtil.isNestedResource(resource)) { return Optional.of(ConsolidationDataUtil - .getNestedTemplateConsolidationData(context, serviceTemplate, resourceId)); + .getNestedTemplateConsolidationData(context, serviceTemplate, heatFileName, resourceId)); } return Optional.empty(); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-heatToToscaMapping.json b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-heatToToscaMapping.json index 384847351e..d329b92b9f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-heatToToscaMapping.json +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-heatToToscaMapping.json @@ -74,7 +74,7 @@ }, "attributes": { "name": "name", - "virtual_machine_intefrace_mac_addresses": "virtual_machine_intefrace_mac_addresses", + "virtual_machine_interface_mac_addresses": "virtual_machine_interface_mac_addresses", "virtual_machine_interface_mac_addresses#virtual_machine_interface_mac_addresses_mac_address": "mac_address", "virtual_network_refs": "virtual_network_refs", "port_tuple_refs": "port_tuple_refs", diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-mandatory-unifiedModel.json b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-mandatory-unifiedModel.json index d4df0699f5..2b8f484705 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-mandatory-unifiedModel.json +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/resources/config-mandatory-unifiedModel.json @@ -26,6 +26,17 @@ "enable": true } }, + "enrichPortResourceProperties": [ + "network_role_tag", + "mac_requirements", + "vlan_requirements", + "ip_requirements", + "network_role", + "order", + "exCP_naming", + "subnetpoolid" + ] + , "_config": { "namespace": "mandatoryUnifiedModel" } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionNestedSingleComputeFullTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionNestedSingleComputeFullTest.java index 0001ec8d54..9f3232eaca 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionNestedSingleComputeFullTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionNestedSingleComputeFullTest.java @@ -24,8 +24,19 @@ public class UnifiedCompositionNestedSingleComputeFullTest extends BaseFullTrans testTranslationWithInit(); } + @Test + public void testNestedWithOneComputeSamePortType() throws IOException { + inputFilesPath = + "/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in"; + outputFilesPath = + "/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out"; + + testTranslationWithInit(); + } + @Test public void testOneNestedWithTwoComputesOfSameType() throws IOException { + //Not pattern 4 (Complex VFC) inputFilesPath = "/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoComputesOfSameType/in"; outputFilesPath = @@ -36,6 +47,7 @@ public class UnifiedCompositionNestedSingleComputeFullTest extends BaseFullTrans @Test public void testOneNestedWithTwoDiffComputeTypes() throws IOException { + //Not pattern 4 (Complex VFC) inputFilesPath = "/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in"; outputFilesPath = @@ -124,6 +136,7 @@ public class UnifiedCompositionNestedSingleComputeFullTest extends BaseFullTrans @Test public void testMultiLevelNestedComposition() throws IOException { + //Not pattern 4 (Multi level Complex VFC) inputFilesPath = "/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedMultiLevels/in"; outputFilesPath = diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml index c47881c827..19e88a77fb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance1: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml index b3fd08ad7f..0f74dfe252 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml @@ -250,32 +250,22 @@ topology_template: service_instance3: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list groups: service_instance3_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml index 031d40e78f..bb8a6c0324 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml @@ -250,32 +250,22 @@ topology_template: service_instance4: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list groups: service_instance4_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml index a80565137c..72b97b69a9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance1: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml index 1ba7cd1567..1798f33fde 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance2: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/MainServiceTemplate.yaml index 3fc99fd2e7..f4dda7cefd 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/MainServiceTemplate.yaml @@ -51,7 +51,77 @@ topology_template: get_input: Internal1_forwarding_mode network_name: get_input: Internal1_net_name - test_nested: + test_nested0: + type: org.openecomp.resource.abstract.nodes.heat.OCS-fw + directives: + - substitutable + properties: + network_param2: Internal2-net + service_template_filter: + substitute_service_template: OCS-fwServiceTemplate.yaml + network_param1: Internal1-net + requirements: + - link_port_0_service_instance2: + capability: tosca.capabilities.network.Linkable + node: Internal2-net + relationship: tosca.relationships.network.LinksTo + - link_port_1_service_instance2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_2_service_instance2: + capability: tosca.capabilities.network.Linkable + node: Internal2-net + relationship: tosca.relationships.network.LinksTo + - link_port_0_service_instance1: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_1_service_instance1: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_2_service_instance1: + capability: tosca.capabilities.network.Linkable + node: Internal2-net + relationship: tosca.relationships.network.LinksTo + - link_port_0_service_instance1_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal2-net + relationship: tosca.relationships.network.LinksTo + - link_port_1_service_instance1_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_2_service_instance1_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal2-net + relationship: tosca.relationships.network.LinksTo + - link_port_0_service_instance4_test_nested3_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_1_service_instance4_test_nested3_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_2_service_instance4_test_nested3_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_0_service_instance3_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_1_service_instance3_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal1-net + relationship: tosca.relationships.network.LinksTo + - link_port_2_service_instance3_test_nested2: + capability: tosca.capabilities.network.Linkable + node: Internal2-net + relationship: tosca.relationships.network.LinksTo + test_nested1: type: org.openecomp.resource.abstract.nodes.heat.OCS-fw directives: - substitutable @@ -130,7 +200,7 @@ topology_template: members: - Internal2-net - Internal1-net - - test_nested + - test_nested0 addOn_group: type: org.openecomp.groups.heat.HeatStack properties: @@ -139,4 +209,4 @@ topology_template: members: - Internal2-net - Internal1-net - - test_nested \ No newline at end of file + - test_nested1 \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml index c47881c827..19e88a77fb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance1ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance1: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml index b3fd08ad7f..0f74dfe252 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw2_service_instance3ServiceTemplate.yaml @@ -250,32 +250,22 @@ topology_template: service_instance3: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list groups: service_instance3_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml index 031d40e78f..bb8a6c0324 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw3_service_instance4ServiceTemplate.yaml @@ -250,32 +250,22 @@ topology_template: service_instance4: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list groups: service_instance4_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml index a80565137c..72b97b69a9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance1ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance1: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml index 1ba7cd1567..1798f33fde 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/expectedoutputfiles/OCS-fw_service_instance2ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance2: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/addOn.yml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/addOn.yml index 2785688607..7747ff6719 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/addOn.yml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/addOn.yml @@ -30,7 +30,7 @@ resources: forwarding_mode: { get_param: Internal1_forwarding_mode } shared: { get_param: Internal1_shared } - test_nested: + test_nested1: type: OCS-fw.yml properties: network_param1: { get_resource: Internal1-net} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/base.yml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/base.yml index 2785688607..235cf5e4cf 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/base.yml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/connectToNetworkSharedMultiNested/inputfiles/base.yml @@ -30,7 +30,7 @@ resources: forwarding_mode: { get_param: Internal1_forwarding_mode } shared: { get_param: Internal1_shared } - test_nested: + test_nested0: type: OCS-fw.yml properties: network_param1: { get_resource: Internal1-net} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml index 69d73f9034..9c7de5309f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance_1: type: org.openecomp.resource.vfc.nodes.heat.compute_service_template_1 properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml index 1a0f590d58..6ccd3c4a0e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/diffServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance_2: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/oneServiceInstance/expectedoutputfiles/lcp1_mss.oam-fw_si_service_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/oneServiceInstance/expectedoutputfiles/lcp1_mss.oam-fw_si_service_instanceServiceTemplate.yaml index 53cb41cc75..c7685c951b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/oneServiceInstance/expectedoutputfiles/lcp1_mss.oam-fw_si_service_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/oneServiceInstance/expectedoutputfiles/lcp1_mss.oam-fw_si_service_instanceServiceTemplate.yaml @@ -294,32 +294,22 @@ topology_template: service_instance: type: org.openecomp.resource.vfc.nodes.heat.st properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list groups: service_instance_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml index de34c8fba8..413aa7b724 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_1ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance_1: type: org.openecomp.resource.vfc.nodes.heat.compute_service_template properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml index 818e411705..a20cb55608 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sameServiceTemplate/expectedoutputfiles/OCS-fw_service_instance_2ServiceTemplate.yaml @@ -130,32 +130,22 @@ topology_template: service_instance_2: type: org.openecomp.resource.vfc.nodes.heat.compute_service_template properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list port_0: type: org.openecomp.resource.cp.nodes.heat.network.contrail.Port properties: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sharedNetworkMulti/expectedoutputfiles/OCS-fw_service_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sharedNetworkMulti/expectedoutputfiles/OCS-fw_service_instanceServiceTemplate.yaml index 1980b18393..e99b179375 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sharedNetworkMulti/expectedoutputfiles/OCS-fw_service_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/contrail2serviceinstance/sharedNetworkMulti/expectedoutputfiles/OCS-fw_service_instanceServiceTemplate.yaml @@ -330,32 +330,22 @@ topology_template: service_instance: type: org.openecomp.resource.vfc.nodes.heat.compute_service_template properties: - availability_zone: - get_input: availability_zone - static_routes_list: - get_input: static_routes_list - availability_zone_enable: - get_input: availability_zone_enable - service_template_name: - get_input: service_template_name - ordered_interfaces: - get_input: ordered_interfaces flavor: get_input: flavor image_name: get_input: image_name + availability_zone: + get_input: availability_zone service_type: get_input: service_type - service_interface_type_list: - get_input: service_interface_type_list + availability_zone_enable: + get_input: availability_zone_enable + service_template_name: + get_input: service_template_name service_instance_name: get_input: service_instance_name - interface_list: - get_input: interface_list service_mode: get_input: service_mode - shared_ip_list: - get_input: shared_ip_list groups: service_instance_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/GlobalSubstitutionTypesServiceTemplate.yaml index 549e488839..3f0bbea5ee 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,30 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -399,6 +435,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -421,30 +487,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -790,6 +862,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -812,30 +914,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list required: true status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/MainServiceTemplate.yaml index 700ca62ca3..b3be41a76f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/MainServiceTemplate.yaml @@ -77,6 +77,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 2 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -90,14 +98,6 @@ topology_template: is_required: false port_pd01_port_network: - packet_internal_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 2 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: @@ -118,6 +118,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -131,14 +139,6 @@ topology_template: is_required: false port_pd01_port_network: - packet_internal_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: @@ -159,6 +159,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -172,14 +180,6 @@ topology_template: is_required: false port_pd01_port_network: - packet_internal_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_0ServiceTemplate.yaml index 5ef1764a63..6a96d70747 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_0ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_1ServiceTemplate.yaml index a0da89fcd1..1efd8dcca0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_1ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_2ServiceTemplate.yaml index 8e6fc1636e..08e5895c0e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeDiffImageName/out/Nested_pd_server_2ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml index 89cc273c46..b85ce67d05 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -411,6 +441,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -433,36 +493,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -808,6 +868,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -830,36 +920,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/MainServiceTemplate.yaml index e320ad820d..89aa2d4fbf 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/MainServiceTemplate.yaml @@ -171,6 +171,18 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_attribute: + - abstract_pd_server_0 + - pd_server_show + compute_pd_server_name: + - get_input: + - pd_server_names + - 2 + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -184,18 +196,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_attribute: - - abstract_pd_server_0 - - pd_server_show - compute_pd_server_name: - - get_input: - - pd_server_names - - 2 - vm_flavor_name: - get_attribute: - - network_policy_server - - name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -218,6 +218,16 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -231,16 +241,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_attribute: - - network_policy_server - - name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -258,6 +258,16 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -271,16 +281,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - vm_flavor_name: - get_attribute: - - network_policy_server - - name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_0ServiceTemplate.yaml index afa6a85603..3d11cad564 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_0ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_1ServiceTemplate.yaml index 5b0eb7e992..1efd8dcca0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_1ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_2ServiceTemplate.yaml index 1b487934d1..08e5895c0e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypeGetAttrBetweenThem/out/Nested_pd_server_2ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/GlobalSubstitutionTypesServiceTemplate.yaml index 549e488839..3f0bbea5ee 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,30 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -399,6 +435,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -421,30 +487,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -790,6 +862,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -812,30 +914,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list required: true status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/MainServiceTemplate.yaml index db618f7af0..4187b3bb39 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/MainServiceTemplate.yaml @@ -76,6 +76,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 2 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -89,14 +97,6 @@ topology_template: is_required: false port_pd01_port_network: - packet_external_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 2 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: @@ -122,6 +122,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -135,14 +143,6 @@ topology_template: is_required: false port_pd01_port_network: - packet_internal_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: @@ -163,6 +163,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -176,14 +184,6 @@ topology_template: is_required: false port_pd01_port_network: - packet_internal_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_0ServiceTemplate.yaml index 5ef1764a63..6a96d70747 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_0ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_1ServiceTemplate.yaml index a0da89fcd1..1efd8dcca0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_1ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_2ServiceTemplate.yaml index 8e6fc1636e..08e5895c0e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/catalogInstances/threeComputesSameTypePortsConnectedToDiffNetworks/out/Nested_pd_server_2ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/GlobalSubstitutionTypesServiceTemplate.yaml index da7b5979f9..a921a8e328 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -926,29 +926,92 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - server_group: - type: string - required: true - status: SUPPORTED - connectivityChk: - type: json + port_pcm_port_0_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name required: true status: SUPPORTED - oam_net_gw: - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + server_group: + type: string + required: true + status: SUPPORTED + connectivityChk: + type: json + required: true + status: SUPPORTED + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED security_group_name: type: string description: the name of security group @@ -959,6 +1022,12 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance @@ -969,21 +1038,11 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED - pcm_server_name: - type: string - description: PCRF CM server name - required: true - status: SUPPORTED cps_net_name: type: string description: CPS network name required: true status: SUPPORTED - cps_net_mask: - type: string - description: CPS network mask - required: true - status: SUPPORTED oam_net_ip: type: string description: OAM network ip @@ -994,11 +1053,12 @@ node_types: description: CPS network mask required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name + port_pcm_port_1_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer attributes: server_pcm_id: type: string @@ -1421,7 +1481,13 @@ node_types: org.openecomp.resource.abstract.nodes.1c1_scalling_instance: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_1c1_t1_port_fixed_ips: + port_1c1_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -1433,24 +1499,80 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1c1_t2_port_ip_requirements: + port_1c1_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c1_t1_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1c1_t1_port_mac_requirements: + vm_image_name: + type: string + required: true + status: SUPPORTED + compute_1c1_scalling_instance_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t2_port_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - port_1c1_t2_port_network_role_tag: + port_1c1_t2_port_network: type: list required: true status: SUPPORTED entry_schema: type: string + port_1c1_t1_port_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -1459,80 +1581,84 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1c1_t2_port_mac_requirements: + port_1c1_t2_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_flavor_name: - type: string + type: string + port_1c1_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c1_t2_port_mac_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_1c1_scalling_instance_availability_zone: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_1c1_t2_port_name: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED compute_1c1_scalling_instance_scheduler_hints: type: list required: true status: SUPPORTED entry_schema: type: json - compute_1c1_scalling_instance_metadata: + port_1c1_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json - compute_1c1_scalling_instance_name: + compute_1c1_scalling_instance_metadata: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1c1_t1_port_name: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t2_port_fixed_ips: + port_1c1_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1c1_t2_port_network: + type: string + port_1c1_t1_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string + type: integer attributes: 1c1_scalling_instance_1c1_t1_port_tenant_id: type: list @@ -1972,6 +2098,74 @@ node_types: status: SUPPORTED entry_schema: type: json + port_1a_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -1992,50 +2186,48 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true status: SUPPORTED - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true status: SUPPORTED entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -2482,6 +2674,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_1b_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -2508,16 +2768,18 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1b_t1_port_value_specs: type: list required: true @@ -2530,16 +2792,12 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -2552,12 +2810,12 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -2998,12 +3256,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -3018,12 +3350,6 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: - type: list - required: true - status: SUPPORTED - entry_schema: - type: string compute_1c2_catalog_instance_metadata: type: list required: true @@ -3036,10 +3362,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1c2_t1_port_exCP_naming: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_network: type: list required: true @@ -3052,11 +3380,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -3514,12 +3838,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -3534,22 +3932,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED + type: json port_1c2_t1_port_network: type: list required: true @@ -3562,11 +3956,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -4024,6 +4414,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_1b_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -4050,32 +4508,36 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: - type: string - required: true - status: SUPPORTED - port_1b_t1_port_ip_requirements: + port_1b_t2_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string + port_1b_t1_port_network_role_tag: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_b_single_1b_metadata: type: list required: true status: SUPPORTED entry_schema: type: json + port_1b_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -4088,12 +4550,12 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json compute_b_single_1b_name: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/MainServiceTemplate.yaml index 7a12426fa6..700c94ba91 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/MainServiceTemplate.yaml @@ -143,6 +143,52 @@ topology_template: directives: - substitutable properties: + compute_1c1_scalling_instance_user_data_format: + - RAW2 + - RAW1 + port_1c1_t2_port_network_role_tag: + - ppds + - ppds + vm_flavor_name: + get_input: pd_flavor_name + port_1c1_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_1c1_scalling_instance_name: + - get_input: + - 1c1_scalling_instance_names + - 2 + - get_input: + - 1c1_scalling_instance_names + - 1 + port_1c1_t1_port_name: + - 1c1_t1_port_1 + - 1c1_t1_port_0 + port_1c1_t1_port_network: + - 1c1_scalling_instance_network + - 1c1_scalling_instance_network + port_1c1_t2_port_fixed_ips: + - - ip_address: + get_input: + - myIPs + - 4 + - - ip_address: + get_input: + - myIPs + - 2 + port_1c1_t2_port_network: + - get_input: ppds_net_name + - get_input: ppds_net_name port_1c1_t1_port_fixed_ips: - - ip_address: get_input: @@ -152,9 +198,6 @@ topology_template: get_input: - myIPs - 1 - compute_1c1_scalling_instance_user_data_format: - - RAW2 - - RAW1 port_1c1_t2_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -171,35 +214,17 @@ topology_template: is_required: false - mac_count_required: is_required: false - port_1c1_t2_port_network_role_tag: - - ppds - - ppds port_1c1_t2_port_mac_requirements: - mac_count_required: is_required: false - mac_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name compute_1c1_scalling_instance_availability_zone: - get_input: availabilityzone_name - get_input: availabilityzone_name - port_1c1_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false port_1c1_t2_port_name: - 1c1_t2_port_1 - 1c1_t2_port_0 - vm_image_name: - get_input: pd_image_name compute_1c1_scalling_instance_scheduler_hints: - group: BE_Affinity_group - group: BE_Affinity_group @@ -233,31 +258,6 @@ topology_template: get_attribute: - abstract_b_single_1b_0 - b_single_1b_instance_name - compute_1c1_scalling_instance_name: - - get_input: - - 1c1_scalling_instance_names - - 2 - - get_input: - - 1c1_scalling_instance_names - - 1 - port_1c1_t1_port_name: - - 1c1_t1_port_1 - - 1c1_t1_port_0 - port_1c1_t1_port_network: - - 1c1_scalling_instance_network - - 1c1_scalling_instance_network - port_1c1_t2_port_fixed_ips: - - - ip_address: - get_input: - - myIPs - - 4 - - - ip_address: - get_input: - - myIPs - - 2 - port_1c1_t2_port_network: - - get_input: ppds_net_name - - get_input: ppds_net_name service_template_filter: substitute_service_template: Nested_1c1_scalling_instanceServiceTemplate.yaml count: 2 @@ -276,6 +276,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_1b_user_data_format: + - RAW port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false @@ -289,16 +301,6 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name compute_b_single_1b_metadata: - connectivityTo4PNested: get_attribute: @@ -329,8 +331,6 @@ topology_template: is_required: false port_1b_t2_port_network: - b_single_1b_network - compute_b_single_1b_user_data_format: - - RAW compute_b_single_1b_name: - get_input: - b_single_1b_names @@ -358,13 +358,23 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_metadata: - connectivityTo4PNested: get_attribute: @@ -398,21 +408,11 @@ topology_template: - get_input: - 1c2_catalog_instance_names - 1 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - RAW1 port_1c2_t1_port_network_role_tag: @@ -443,32 +443,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 2 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - get_attribute: - abstract_1c2_catalog_instance_0 @@ -661,10 +661,6 @@ topology_template: get_attribute: - abstract_1c1_scalling_instance - 1c1_scalling_instance_1c1_t2_port_tenant_id - compute_a_single_1a_availability_zone: - - get_input: availabilityzone_name - compute_a_single_1a_scheduler_hints: - - group: BE_Affinity_group port_1a_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -690,6 +686,10 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + compute_a_single_1a_availability_zone: + - get_input: availabilityzone_name + compute_a_single_1a_scheduler_hints: + - group: BE_Affinity_group compute_a_single_1a_user_data_format: - RAW compute_a_single_1a_name: @@ -877,6 +877,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_1b_user_data_format: + - RAW port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false @@ -890,29 +902,17 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name port_1b_t1_port_value_specs: - get_attribute: - abstract_a_single_1a - a_single_1a_1a_t1_port_tenant_id port_1b_t1_port_network_role_tag: - oam - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false port_1b_t2_port_network: - b_single_1b_network - compute_b_single_1b_user_data_format: - - RAW port_1b_t1_port_network: - get_input: oam_net_name compute_b_single_1b_name: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c1_scalling_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c1_scalling_instanceServiceTemplate.yaml index aa6bcaf443..f6b0a50917 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c1_scalling_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c1_scalling_instanceServiceTemplate.yaml @@ -11,7 +11,12 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_1c1_t1_port_fixed_ips: + port_1c1_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c1_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -21,21 +26,67 @@ topology_template: required: true entry_schema: type: string - port_1c1_t2_port_ip_requirements: + port_1c1_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c1_t1_port_ip_requirements: type: list required: true entry_schema: type: json - port_1c1_t1_port_mac_requirements: + vm_image_name: + type: string + required: true + compute_1c1_scalling_instance_name: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_name: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1c1_t2_port_fixed_ips: type: list required: true entry_schema: type: json - port_1c1_t2_port_network_role_tag: + port_1c1_t2_port_network: type: list required: true entry_schema: type: string + port_1c1_t1_port_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1c1_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -43,79 +94,107 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_1c1_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1c1_t2_port_order: + type: list + required: true + entry_schema: + type: integer port_1c1_t2_port_mac_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string - required: true compute_1c1_scalling_instance_availability_zone: type: list required: true entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t2_port_subnetpoolid: type: list required: true entry_schema: - type: json + type: string port_1c1_t2_port_name: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true compute_1c1_scalling_instance_scheduler_hints: type: list required: true entry_schema: type: json - compute_1c1_scalling_instance_metadata: + port_1c1_t2_port_exCP_naming: type: list required: true entry_schema: type: json - compute_1c1_scalling_instance_name: + compute_1c1_scalling_instance_metadata: type: list required: true entry_schema: - type: string - port_1c1_t1_port_name: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_network_role_tag: type: list required: true entry_schema: type: string - port_1c1_t2_port_fixed_ips: + port_1c1_t1_port_network_role: type: list required: true entry_schema: - type: json - port_1c1_t2_port_network: + type: string + port_1c1_t1_port_order: type: list required: true entry_schema: - type: string + type: integer node_templates: 1c1_scalling_instance_1c1_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c1_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c1_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t1_port_order + - index_value + network_role: + get_input: + - port_1c1_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t1_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t1_port_fixed_ips @@ -163,6 +242,14 @@ topology_template: 1c1_scalling_instance_1c1_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t2_port_ip_requirements @@ -175,6 +262,18 @@ topology_template: get_input: - port_1c1_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t2_port_order + - index_value + network_role: + get_input: + - port_1c1_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t2_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t2_port_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml index 67305b71ce..7a439484d6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,11 +89,6 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: - type: list - required: true - entry_schema: - type: string compute_1c2_catalog_instance_metadata: type: list required: true @@ -43,9 +99,11 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1c2_t1_port_exCP_naming: + type: list required: true + entry_schema: + type: json port_1c2_t1_port_network: type: list required: true @@ -56,10 +114,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -115,14 +170,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -135,6 +214,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -147,6 +234,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml index 213939c88e..ab88e26fa7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_a_single_1aServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_a_single_1aServiceTemplate.yaml index 409bf1d35f..c0ea9ef793 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_a_single_1aServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_a_single_1aServiceTemplate.yaml @@ -16,6 +16,62 @@ topology_template: required: true entry_schema: type: json + port_1a_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1a_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + port_1a_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -33,42 +89,41 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -88,14 +143,38 @@ topology_template: a_single_1a_1a_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1a_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1a_t1_port_mac_requirements - index_value + order: + get_input: + - port_1a_t1_port_order + - index_value + network_role: + get_input: + - port_1a_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t1_port_subnetpoolid + - index_value network: get_input: - port_1a_t1_port_network @@ -135,6 +214,14 @@ topology_template: a_single_1a_1a_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t2_port_ip_requirements @@ -147,6 +234,18 @@ topology_template: get_input: - port_1a_t2_port_mac_requirements - index_value + order: + get_input: + - port_1a_t2_port_order + - index_value + network_role: + get_input: + - port_1a_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t2_port_subnetpoolid + - index_value network: get_input: - port_1a_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_0ServiceTemplate.yaml index 97428c699a..1b859d537f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_0ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -33,27 +89,31 @@ topology_template: required: true entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string - required: true - port_1b_t1_port_ip_requirements: + port_1b_t2_port_ip_requirements: type: list required: true entry_schema: type: json - vm_image_name: - type: string + port_1b_t1_port_network_role_tag: + type: list required: true + entry_schema: + type: string compute_b_single_1b_metadata: type: list required: true entry_schema: type: json + port_1b_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -64,11 +124,11 @@ topology_template: required: true entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json compute_b_single_1b_name: type: list required: true @@ -105,14 +165,38 @@ topology_template: b_single_1b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_attribute: - b_single_1b @@ -125,14 +209,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_1ServiceTemplate.yaml index 78243244fa..1feba0fca7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/Nested_b_single_1b_1ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -33,14 +89,16 @@ topology_template: required: true entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true + entry_schema: + type: json port_1b_t1_port_value_specs: type: list required: true @@ -51,14 +109,11 @@ topology_template: required: true entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true entry_schema: - type: json - vm_image_name: - type: string - required: true + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -69,11 +124,11 @@ topology_template: required: true entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -115,6 +170,14 @@ topology_template: get_input: - port_1b_t1_port_value_specs - index_value + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements @@ -127,6 +190,18 @@ topology_template: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_input: - port_1b_t1_port_network @@ -139,14 +214,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/nested-pcm_v0.1ServiceTemplate.yaml index d6dd992034..a8e64880b2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/connectivityBetweenPatterns/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,32 +11,90 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - server_group: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string + availabilityzone_name: + label: availabilityzone name hidden: false immutable: false type: string - connectivityChk: + description: availabilityzone name + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + pcm_image_name: + label: image name hidden: false immutable: false - type: json - availabilityzone_name: - label: availabilityzone name + type: string + description: PCRF CM image name + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_server_name: + label: PCRF CM server name hidden: false immutable: false type: string - description: availabilityzone name - oam_net_gw: - label: CPS network gateway + description: PCRF CM server name + cps_net_mask: + label: CPS network mask hidden: false immutable: false type: string - description: CPS network gateway - pcm_image_name: - label: image name + description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + oam_net_name: + label: OAM network name hidden: false immutable: false type: string - description: PCRF CM image name + description: OAM network name + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string + server_group: + hidden: false + immutable: false + type: string + connectivityChk: + hidden: false + immutable: false + type: json + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway security_group_name: label: security group name hidden: false @@ -49,6 +107,11 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false @@ -61,24 +124,12 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume - pcm_server_name: - label: PCRF CM server name - hidden: false - immutable: false - type: string - description: PCRF CM server name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -91,12 +142,11 @@ topology_template: immutable: false type: string description: CPS network mask - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -109,15 +159,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -150,15 +220,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/GlobalSubstitutionTypesServiceTemplate.yaml index 3213f601da..536511a641 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -922,6 +922,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string server_group: type: string required: true @@ -936,6 +942,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -951,11 +963,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -986,11 +1022,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string @@ -1413,7 +1473,13 @@ node_types: org.openecomp.resource.abstract.nodes.1c1_scalling_instance: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_1c1_t1_port_fixed_ips: + port_1c1_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -1425,24 +1491,80 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1c1_t2_port_ip_requirements: + port_1c1_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c1_t1_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1c1_t1_port_mac_requirements: + vm_image_name: + type: string + required: true + status: SUPPORTED + compute_1c1_scalling_instance_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t2_port_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - port_1c1_t2_port_network_role_tag: + port_1c1_t2_port_network: type: list required: true status: SUPPORTED entry_schema: type: string + port_1c1_t1_port_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -1451,74 +1573,78 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1c1_t2_port_mac_requirements: + port_1c1_t2_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_flavor_name: - type: string + type: string + port_1c1_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c1_t2_port_mac_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_1c1_scalling_instance_availability_zone: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_1c1_t2_port_name: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED compute_1c1_scalling_instance_scheduler_hints: type: list required: true status: SUPPORTED entry_schema: type: json - compute_1c1_scalling_instance_name: + port_1c1_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1c1_t1_port_name: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t2_port_fixed_ips: + port_1c1_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1c1_t2_port_network: + type: string + port_1c1_t1_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string + type: integer attributes: 1c1_scalling_instance_instance_name: type: list @@ -1947,6 +2073,74 @@ node_types: org.openecomp.resource.abstract.nodes.a_single_1a: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1a_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -1967,50 +2161,48 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true status: SUPPORTED - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true status: SUPPORTED entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -2457,6 +2649,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_1b_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -2483,32 +2743,30 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1b_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -2521,12 +2779,12 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -2967,12 +3225,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -2987,22 +3319,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED + type: json port_1c2_t1_port_network: type: list required: true @@ -3015,11 +3343,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -3477,12 +3801,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -3497,22 +3895,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED + type: json port_1c2_t1_port_network: type: list required: true @@ -3525,11 +3919,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -4056,16 +4446,6 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t1_port_ip_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED compute_b_single_1b_availability_zone: type: list required: true @@ -4086,6 +4466,62 @@ node_types: status: SUPPORTED entry_schema: type: json + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t2_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -4098,7 +4534,19 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1b_t2_port_ip_requirements: + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -4110,16 +4558,30 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1b_t2_port_exCP_naming: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_b_single_1b_name: type: list required: true status: SUPPORTED entry_schema: type: string + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: b_single_1b_instance_name: type: list diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/MainServiceTemplate.yaml index 5108b6f4f0..68f812e15d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/MainServiceTemplate.yaml @@ -115,47 +115,14 @@ topology_template: directives: - substitutable properties: - port_1c1_t1_port_fixed_ips: - - - ip_address: - get_input: - - myIPs - - 3 - - - ip_address: - get_input: - - myIPs - - 1 compute_1c1_scalling_instance_user_data_format: - RAW2 - RAW1 - port_1c1_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false - port_1c1_t1_port_mac_requirements: - - mac_count_required: - is_required: false - - mac_count_required: - is_required: false port_1c1_t2_port_network_role_tag: - ppds - ppds - port_1c1_t2_port_mac_requirements: - - mac_count_required: - is_required: false - - mac_count_required: - is_required: false vm_flavor_name: get_input: pd_flavor_name - compute_1c1_scalling_instance_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name port_1c1_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -167,14 +134,8 @@ topology_template: is_required: true floating_ip_count_required: is_required: false - port_1c1_t2_port_name: - - 1c1_t2_port_1 - - 1c1_t2_port_0 vm_image_name: get_input: pd_image_name - compute_1c1_scalling_instance_scheduler_hints: - - group: BE_Affinity_group - - group: BE_Affinity_group compute_1c1_scalling_instance_name: - get_input: - 1c1_scalling_instance_names @@ -200,6 +161,45 @@ topology_template: port_1c1_t2_port_network: - get_input: ppds_net_name - get_input: ppds_net_name + port_1c1_t1_port_fixed_ips: + - - ip_address: + get_input: + - myIPs + - 3 + - - ip_address: + get_input: + - myIPs + - 1 + port_1c1_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + port_1c1_t1_port_mac_requirements: + - mac_count_required: + is_required: false + - mac_count_required: + is_required: false + port_1c1_t2_port_mac_requirements: + - mac_count_required: + is_required: false + - mac_count_required: + is_required: false + compute_1c1_scalling_instance_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + port_1c1_t2_port_name: + - 1c1_t2_port_1 + - 1c1_t2_port_0 + compute_1c1_scalling_instance_scheduler_hints: + - group: BE_Affinity_group + - group: BE_Affinity_group service_template_filter: substitute_service_template: Nested_1c1_scalling_instanceServiceTemplate.yaml count: 2 @@ -225,6 +225,18 @@ topology_template: port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false + compute_b_single_1b_availability_zone: + - get_input: availabilityzone_name + compute_b_single_1b_scheduler_hints: + - group: BE_Affinity_group + port_1b_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_flavor_name: + get_input: pd_flavor_name port_1b_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -233,25 +245,13 @@ topology_template: is_required: false vm_image_name: get_input: pd_image_name - compute_b_single_1b_availability_zone: - - get_input: availabilityzone_name - compute_b_single_1b_scheduler_hints: - - group: BE_Affinity_group port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false port_1b_t2_port_network: - b_single_1b_network - port_1b_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_b_single_1b_user_data_format: - RAW - vm_flavor_name: - get_input: pd_flavor_name compute_b_single_1b_name: - get_input: - b_single_1b_names @@ -292,32 +292,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 1 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - RAW1 port_1c2_t1_port_network_role_tag: @@ -352,32 +352,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 2 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - get_attribute: - abstract_1c2_catalog_instance_0 @@ -588,10 +588,6 @@ topology_template: directives: - substitutable properties: - compute_a_single_1a_availability_zone: - - get_input: availabilityzone_name - compute_a_single_1a_scheduler_hints: - - group: BE_Affinity_group port_1a_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -617,6 +613,10 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + compute_a_single_1a_availability_zone: + - get_input: availabilityzone_name + compute_a_single_1a_scheduler_hints: + - group: BE_Affinity_group compute_a_single_1a_user_data_format: - RAW compute_a_single_1a_name: @@ -780,6 +780,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_1b_user_data_format: + - RAW port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false @@ -793,25 +805,13 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name port_1b_t1_port_network_role_tag: - oam - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false port_1b_t2_port_network: - b_single_1b_network - compute_b_single_1b_user_data_format: - - RAW port_1b_t1_port_network: - get_input: oam_net_name compute_b_single_1b_name: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c1_scalling_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c1_scalling_instanceServiceTemplate.yaml index 2c43ee2c01..3a93e4c8b9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c1_scalling_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c1_scalling_instanceServiceTemplate.yaml @@ -11,7 +11,12 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_1c1_t1_port_fixed_ips: + port_1c1_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c1_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -21,21 +26,67 @@ topology_template: required: true entry_schema: type: string - port_1c1_t2_port_ip_requirements: + port_1c1_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c1_t1_port_ip_requirements: type: list required: true entry_schema: type: json - port_1c1_t1_port_mac_requirements: + vm_image_name: + type: string + required: true + compute_1c1_scalling_instance_name: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_name: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1c1_t2_port_fixed_ips: type: list required: true entry_schema: type: json - port_1c1_t2_port_network_role_tag: + port_1c1_t2_port_network: type: list required: true entry_schema: type: string + port_1c1_t1_port_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1c1_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -43,74 +94,102 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_1c1_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1c1_t2_port_order: + type: list + required: true + entry_schema: + type: integer port_1c1_t2_port_mac_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string - required: true compute_1c1_scalling_instance_availability_zone: type: list required: true entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t2_port_subnetpoolid: type: list required: true entry_schema: - type: json + type: string port_1c1_t2_port_name: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true compute_1c1_scalling_instance_scheduler_hints: type: list required: true entry_schema: type: json - compute_1c1_scalling_instance_name: + port_1c1_t2_port_exCP_naming: type: list required: true entry_schema: - type: string - port_1c1_t1_port_name: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_network_role_tag: type: list required: true entry_schema: type: string - port_1c1_t2_port_fixed_ips: + port_1c1_t1_port_network_role: type: list required: true entry_schema: - type: json - port_1c1_t2_port_network: + type: string + port_1c1_t1_port_order: type: list required: true entry_schema: - type: string + type: integer node_templates: 1c1_scalling_instance_1c1_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c1_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c1_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t1_port_order + - index_value + network_role: + get_input: + - port_1c1_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t1_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t1_port_fixed_ips @@ -154,6 +233,14 @@ topology_template: 1c1_scalling_instance_1c1_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t2_port_ip_requirements @@ -166,6 +253,18 @@ topology_template: get_input: - port_1c1_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t2_port_order + - index_value + network_role: + get_input: + - port_1c1_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t2_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t2_port_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml index dd75d5837c..80b876b5ce 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml index 213939c88e..ab88e26fa7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_a_single_1aServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_a_single_1aServiceTemplate.yaml index dcfab01851..33152e6824 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_a_single_1aServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_a_single_1aServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1a_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1a_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + port_1a_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -28,42 +84,41 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -83,14 +138,38 @@ topology_template: a_single_1a_1a_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1a_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1a_t1_port_mac_requirements - index_value + order: + get_input: + - port_1a_t1_port_order + - index_value + network_role: + get_input: + - port_1a_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t1_port_subnetpoolid + - index_value network: get_input: - port_1a_t1_port_network @@ -126,6 +205,14 @@ topology_template: a_single_1a_1a_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t2_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1a_t2_port_mac_requirements - index_value + order: + get_input: + - port_1a_t2_port_order + - index_value + network_role: + get_input: + - port_1a_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t2_port_subnetpoolid + - index_value network: get_input: - port_1a_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_0ServiceTemplate.yaml index cefe2d2db0..cbfebea739 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_0ServiceTemplate.yaml @@ -16,14 +16,6 @@ topology_template: required: true entry_schema: type: json - port_1b_t1_port_ip_requirements: - type: list - required: true - entry_schema: - type: json - vm_image_name: - type: string - required: true compute_b_single_1b_availability_zone: type: list required: true @@ -41,6 +33,52 @@ topology_template: required: true entry_schema: type: json + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t2_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -51,7 +89,17 @@ topology_template: required: true entry_schema: type: string - port_1b_t2_port_ip_requirements: + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: @@ -61,14 +109,26 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1b_t2_port_exCP_naming: + type: list required: true + entry_schema: + type: json compute_b_single_1b_name: type: list required: true entry_schema: type: string + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string node_templates: b_single_1b: type: org.openecomp.resource.vfc.nodes.heat.b_single_1b @@ -96,14 +156,38 @@ topology_template: b_single_1b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_attribute: - b_single_1b @@ -116,14 +200,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_1ServiceTemplate.yaml index 158df6fc9f..23f23830ac 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/Nested_b_single_1b_1ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -33,27 +89,26 @@ topology_template: required: true entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true + entry_schema: + type: json port_1b_t1_port_network_role_tag: type: list required: true entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true entry_schema: - type: json - vm_image_name: - type: string - required: true + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -64,11 +119,11 @@ topology_template: required: true entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -106,6 +161,14 @@ topology_template: b_single_1b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements @@ -118,6 +181,18 @@ topology_template: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_input: - port_1b_t1_port_network @@ -130,14 +205,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/nested-pcm_v0.1ServiceTemplate.yaml index 10064c8155..caa366f570 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/dependencyConnectivity/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string server_group: hidden: false immutable: false @@ -27,6 +32,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -45,12 +55,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -87,12 +117,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -105,15 +155,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -146,15 +216,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/GlobalSubstitutionTypesServiceTemplate.yaml index 5b8093e870..f0a9da57b6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -922,6 +922,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string server_group: type: string required: true @@ -936,6 +942,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -951,11 +963,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -986,11 +1022,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string @@ -1413,7 +1473,13 @@ node_types: org.openecomp.resource.abstract.nodes.1c1_scalling_instance: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_1c1_t1_port_fixed_ips: + port_1c1_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -1425,24 +1491,80 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1c1_t2_port_ip_requirements: + port_1c1_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c1_t1_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1c1_t1_port_mac_requirements: + vm_image_name: + type: string + required: true + status: SUPPORTED + compute_1c1_scalling_instance_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t2_port_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - port_1c1_t2_port_network_role_tag: + port_1c1_t2_port_network: type: list required: true status: SUPPORTED entry_schema: type: string + port_1c1_t1_port_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -1451,74 +1573,78 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1c1_t2_port_mac_requirements: + port_1c1_t2_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_flavor_name: - type: string + type: string + port_1c1_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c1_t2_port_mac_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_1c1_scalling_instance_availability_zone: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_1c1_t2_port_name: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED compute_1c1_scalling_instance_scheduler_hints: type: list required: true status: SUPPORTED entry_schema: type: json - compute_1c1_scalling_instance_name: + port_1c1_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1c1_t1_port_name: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t2_port_fixed_ips: + port_1c1_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1c1_t2_port_network: + type: string + port_1c1_t1_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string + type: integer attributes: 1c1_scalling_instance_instance_name: type: list @@ -1947,6 +2073,74 @@ node_types: org.openecomp.resource.abstract.nodes.a_single_1a: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1a_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -1967,50 +2161,48 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true status: SUPPORTED - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true status: SUPPORTED entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -2457,6 +2649,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_1b_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -2483,32 +2743,30 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1b_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -2521,12 +2779,12 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -2967,12 +3225,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -2987,22 +3319,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED + type: json port_1c2_t1_port_network: type: list required: true @@ -3015,11 +3343,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -3477,12 +3801,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -3497,22 +3895,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED + type: json port_1c2_t1_port_network: type: list required: true @@ -3525,11 +3919,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -3993,16 +4383,6 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t1_port_ip_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED compute_b_single_1b_availability_zone: type: list required: true @@ -4023,6 +4403,62 @@ node_types: status: SUPPORTED entry_schema: type: json + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t2_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -4035,7 +4471,19 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1b_t2_port_ip_requirements: + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -4047,16 +4495,30 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1b_t2_port_exCP_naming: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_b_single_1b_name: type: list required: true status: SUPPORTED entry_schema: type: string + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: b_single_1b_instance_name: type: list diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/MainServiceTemplate.yaml index 9322fa81fc..26ab893506 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/MainServiceTemplate.yaml @@ -111,47 +111,14 @@ topology_template: directives: - substitutable properties: - port_1c1_t1_port_fixed_ips: - - - ip_address: - get_input: - - myIPs - - 3 - - - ip_address: - get_input: - - myIPs - - 1 compute_1c1_scalling_instance_user_data_format: - RAW2 - RAW1 - port_1c1_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false - port_1c1_t1_port_mac_requirements: - - mac_count_required: - is_required: false - - mac_count_required: - is_required: false port_1c1_t2_port_network_role_tag: - ppds - ppds - port_1c1_t2_port_mac_requirements: - - mac_count_required: - is_required: false - - mac_count_required: - is_required: false vm_flavor_name: get_input: pd_flavor_name - compute_1c1_scalling_instance_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name port_1c1_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -163,14 +130,8 @@ topology_template: is_required: true floating_ip_count_required: is_required: false - port_1c1_t2_port_name: - - 1c1_t2_port_1 - - 1c1_t2_port_0 vm_image_name: get_input: pd_image_name - compute_1c1_scalling_instance_scheduler_hints: - - group: BE_Affinity_group - - group: BE_Affinity_group compute_1c1_scalling_instance_name: - get_input: - 1c1_scalling_instance_names @@ -196,6 +157,45 @@ topology_template: port_1c1_t2_port_network: - get_input: ppds_net_name - get_input: ppds_net_name + port_1c1_t1_port_fixed_ips: + - - ip_address: + get_input: + - myIPs + - 3 + - - ip_address: + get_input: + - myIPs + - 1 + port_1c1_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + port_1c1_t1_port_mac_requirements: + - mac_count_required: + is_required: false + - mac_count_required: + is_required: false + port_1c1_t2_port_mac_requirements: + - mac_count_required: + is_required: false + - mac_count_required: + is_required: false + compute_1c1_scalling_instance_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + port_1c1_t2_port_name: + - 1c1_t2_port_1 + - 1c1_t2_port_0 + compute_1c1_scalling_instance_scheduler_hints: + - group: BE_Affinity_group + - group: BE_Affinity_group service_template_filter: substitute_service_template: Nested_1c1_scalling_instanceServiceTemplate.yaml count: 2 @@ -217,6 +217,18 @@ topology_template: port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false + compute_b_single_1b_availability_zone: + - get_input: availabilityzone_name + compute_b_single_1b_scheduler_hints: + - group: BE_Affinity_group + port_1b_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_flavor_name: + get_input: pd_flavor_name port_1b_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -225,25 +237,13 @@ topology_template: is_required: false vm_image_name: get_input: pd_image_name - compute_b_single_1b_availability_zone: - - get_input: availabilityzone_name - compute_b_single_1b_scheduler_hints: - - group: BE_Affinity_group port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false port_1b_t2_port_network: - b_single_1b_network - port_1b_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_b_single_1b_user_data_format: - RAW - vm_flavor_name: - get_input: pd_flavor_name compute_b_single_1b_name: - get_input: - b_single_1b_names @@ -271,32 +271,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 1 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - RAW1 port_1c2_t1_port_network_role_tag: @@ -327,32 +327,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 2 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - get_attribute: - abstract_1c2_catalog_instance_0 @@ -509,10 +509,6 @@ topology_template: directives: - substitutable properties: - compute_a_single_1a_availability_zone: - - get_input: availabilityzone_name - compute_a_single_1a_scheduler_hints: - - group: BE_Affinity_group port_1a_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -538,6 +534,10 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + compute_a_single_1a_availability_zone: + - get_input: availabilityzone_name + compute_a_single_1a_scheduler_hints: + - group: BE_Affinity_group compute_a_single_1a_user_data_format: - RAW compute_a_single_1a_name: @@ -693,6 +693,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_1b_user_data_format: + - RAW port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false @@ -706,25 +718,13 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name port_1b_t1_port_network_role_tag: - oam - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false port_1b_t2_port_network: - b_single_1b_network - compute_b_single_1b_user_data_format: - - RAW port_1b_t1_port_network: - get_input: oam_net_name compute_b_single_1b_name: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c1_scalling_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c1_scalling_instanceServiceTemplate.yaml index 2c43ee2c01..3a93e4c8b9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c1_scalling_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c1_scalling_instanceServiceTemplate.yaml @@ -11,7 +11,12 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_1c1_t1_port_fixed_ips: + port_1c1_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c1_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -21,21 +26,67 @@ topology_template: required: true entry_schema: type: string - port_1c1_t2_port_ip_requirements: + port_1c1_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c1_t1_port_ip_requirements: type: list required: true entry_schema: type: json - port_1c1_t1_port_mac_requirements: + vm_image_name: + type: string + required: true + compute_1c1_scalling_instance_name: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_name: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1c1_t2_port_fixed_ips: type: list required: true entry_schema: type: json - port_1c1_t2_port_network_role_tag: + port_1c1_t2_port_network: type: list required: true entry_schema: type: string + port_1c1_t1_port_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1c1_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -43,74 +94,102 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_1c1_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1c1_t2_port_order: + type: list + required: true + entry_schema: + type: integer port_1c1_t2_port_mac_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string - required: true compute_1c1_scalling_instance_availability_zone: type: list required: true entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t2_port_subnetpoolid: type: list required: true entry_schema: - type: json + type: string port_1c1_t2_port_name: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true compute_1c1_scalling_instance_scheduler_hints: type: list required: true entry_schema: type: json - compute_1c1_scalling_instance_name: + port_1c1_t2_port_exCP_naming: type: list required: true entry_schema: - type: string - port_1c1_t1_port_name: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_network_role_tag: type: list required: true entry_schema: type: string - port_1c1_t2_port_fixed_ips: + port_1c1_t1_port_network_role: type: list required: true entry_schema: - type: json - port_1c1_t2_port_network: + type: string + port_1c1_t1_port_order: type: list required: true entry_schema: - type: string + type: integer node_templates: 1c1_scalling_instance_1c1_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c1_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c1_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t1_port_order + - index_value + network_role: + get_input: + - port_1c1_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t1_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t1_port_fixed_ips @@ -154,6 +233,14 @@ topology_template: 1c1_scalling_instance_1c1_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t2_port_ip_requirements @@ -166,6 +253,18 @@ topology_template: get_input: - port_1c1_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t2_port_order + - index_value + network_role: + get_input: + - port_1c1_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t2_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t2_port_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml index dd75d5837c..80b876b5ce 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml index 213939c88e..ab88e26fa7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_a_single_1aServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_a_single_1aServiceTemplate.yaml index dcfab01851..33152e6824 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_a_single_1aServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_a_single_1aServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1a_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1a_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + port_1a_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -28,42 +84,41 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -83,14 +138,38 @@ topology_template: a_single_1a_1a_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1a_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1a_t1_port_mac_requirements - index_value + order: + get_input: + - port_1a_t1_port_order + - index_value + network_role: + get_input: + - port_1a_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t1_port_subnetpoolid + - index_value network: get_input: - port_1a_t1_port_network @@ -126,6 +205,14 @@ topology_template: a_single_1a_1a_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t2_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1a_t2_port_mac_requirements - index_value + order: + get_input: + - port_1a_t2_port_order + - index_value + network_role: + get_input: + - port_1a_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t2_port_subnetpoolid + - index_value network: get_input: - port_1a_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_0ServiceTemplate.yaml index cefe2d2db0..cbfebea739 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_0ServiceTemplate.yaml @@ -16,14 +16,6 @@ topology_template: required: true entry_schema: type: json - port_1b_t1_port_ip_requirements: - type: list - required: true - entry_schema: - type: json - vm_image_name: - type: string - required: true compute_b_single_1b_availability_zone: type: list required: true @@ -41,6 +33,52 @@ topology_template: required: true entry_schema: type: json + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t2_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -51,7 +89,17 @@ topology_template: required: true entry_schema: type: string - port_1b_t2_port_ip_requirements: + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: @@ -61,14 +109,26 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1b_t2_port_exCP_naming: + type: list required: true + entry_schema: + type: json compute_b_single_1b_name: type: list required: true entry_schema: type: string + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string node_templates: b_single_1b: type: org.openecomp.resource.vfc.nodes.heat.b_single_1b @@ -96,14 +156,38 @@ topology_template: b_single_1b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_attribute: - b_single_1b @@ -116,14 +200,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_1ServiceTemplate.yaml index 158df6fc9f..23f23830ac 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/Nested_b_single_1b_1ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -33,27 +89,26 @@ topology_template: required: true entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true + entry_schema: + type: json port_1b_t1_port_network_role_tag: type: list required: true entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true entry_schema: - type: json - vm_image_name: - type: string - required: true + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -64,11 +119,11 @@ topology_template: required: true entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -106,6 +161,14 @@ topology_template: b_single_1b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements @@ -118,6 +181,18 @@ topology_template: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_input: - port_1b_t1_port_network @@ -130,14 +205,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/nested-pcm_v0.1ServiceTemplate.yaml index 10064c8155..caa366f570 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/oneAppearancePerPattern/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string server_group: hidden: false immutable: false @@ -27,6 +32,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -45,12 +55,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -87,12 +117,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -105,15 +155,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -146,15 +216,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml index 5f4738ca50..19dc9b133d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -926,6 +926,12 @@ node_types: org.openecomp.resource.abstract.nodes.1c12_scalling_instance: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c1_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_1c12_scalling_instance_scheduler_hints: type: list required: true @@ -944,10 +950,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_1c1_t1_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1c1_t1_port_mac_requirements: type: list required: true @@ -962,40 +970,68 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1c1_t1_port_name: + vm_flavor_name: + type: string + required: true + status: SUPPORTED + compute_1c12_scalling_instance_user_data_format: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: + port_1c1_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: type: string required: true status: SUPPORTED - compute_1c12_scalling_instance_availability_zone: + port_1c1_t1_port_name: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c12_scalling_instance_user_data_format: + port_1c1_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string + compute_1c12_scalling_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer attributes: 1c12_scalling_instance_1c1_t1_port_tenant_id: type: list @@ -1346,16 +1382,24 @@ node_types: org.openecomp.resource.abstract.nodes.1c11_scalling_instance: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c1_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c1_t1_port_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string + port_1c1_t1_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1c1_t1_port_mac_requirements: type: list required: true @@ -1370,52 +1414,80 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1c1_t1_port_name: + vm_flavor_name: + type: string + required: true + status: SUPPORTED + compute_1c11_scalling_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c11_scalling_instance_scheduler_hints: + compute_1c11_scalling_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_1c11_scalling_instance_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c1_t1_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: + vm_image_name: type: string required: true status: SUPPORTED - compute_1c11_scalling_instance_name: + port_1c1_t1_port_name: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_network: + compute_1c11_scalling_instance_scheduler_hints: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c11_scalling_instance_availability_zone: + port_1c1_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c11_scalling_instance_user_data_format: + port_1c1_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t1_port_network: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string + port_1c1_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer attributes: 1c11_scalling_instance_instance_name: type: list @@ -1766,29 +1838,92 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - server_group: - type: string - required: true - status: SUPPORTED - connectivityChk: - type: json + port_pcm_port_0_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name required: true status: SUPPORTED - oam_net_gw: - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + server_group: + type: string + required: true + status: SUPPORTED + connectivityChk: + type: json + required: true + status: SUPPORTED + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED security_group_name: type: string description: the name of security group @@ -1799,6 +1934,12 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance @@ -1809,21 +1950,11 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED - pcm_server_name: - type: string - description: PCRF CM server name - required: true - status: SUPPORTED cps_net_name: type: string description: CPS network name required: true status: SUPPORTED - cps_net_mask: - type: string - description: CPS network mask - required: true - status: SUPPORTED oam_net_ip: type: string description: OAM network ip @@ -1834,11 +1965,12 @@ node_types: description: CPS network mask required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name + port_pcm_port_1_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer attributes: server_pcm_id: type: string @@ -2261,22 +2393,18 @@ node_types: org.openecomp.resource.abstract.nodes.a_single_2a: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - compute_a_single_2a_name: + compute_a_single_2a_user_data_format: type: list required: true status: SUPPORTED entry_schema: type: string - compute_a_single_2a_user_data_format: + port_1a_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_image_name: - type: string - required: true - status: SUPPORTED + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -2291,12 +2419,30 @@ node_types: status: SUPPORTED entry_schema: type: json + port_1a_t1_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_a_single_2a_scheduler_hints: type: list required: true status: SUPPORTED entry_schema: type: json + port_1a_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer compute_a_single_2a_availability_zone: type: list required: true @@ -2307,24 +2453,46 @@ node_types: type: string required: true status: SUPPORTED - compute_a_single_2a_metadata: + port_1a_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1a_t1_port_mac_requirements: + port_1a_t1_port_network: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1a_t1_port_network: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_a_single_2a_name: type: list required: true status: SUPPORTED entry_schema: type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1a_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_a_single_2a_metadata: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json attributes: a_single_2a_instance_name: type: list @@ -2670,33 +2838,25 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_1c2_t1_port_mac_requirements: + port_1c2_t2_port_order: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1c2_t2_port_network: + type: integer + compute_1c2_catalog_instance_availability_zone: type: list required: true status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + port_1c2_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t2_port_network_role: type: list required: true status: SUPPORTED @@ -2706,13 +2866,13 @@ node_types: type: string required: true status: SUPPORTED - port_1c2_t1_port_network: + port_1c2_t2_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_1c2_t2_port_mac_requirements: + port_1c2_t1_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -2722,12 +2882,86 @@ node_types: type: string required: true status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_1c2_catalog_instance_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t2_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_1c2_catalog_instance_user_data_format: type: list required: true @@ -3181,6 +3415,74 @@ node_types: status: SUPPORTED entry_schema: type: json + port_1a_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1a_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -3201,50 +3503,48 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true status: SUPPORTED - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true status: SUPPORTED entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -3691,12 +3991,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_3: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -3711,22 +4085,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED + type: json port_1c2_t1_port_network: type: list required: true @@ -3739,11 +4109,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -4201,6 +4567,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_1b_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -4227,32 +4661,36 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: - type: string - required: true - status: SUPPORTED - port_1b_t1_port_ip_requirements: + port_1b_t2_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string + port_1b_t1_port_network_role_tag: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_b_single_1b_metadata: type: list required: true status: SUPPORTED entry_schema: type: json + port_1b_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -4265,12 +4703,12 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json compute_b_single_1b_name: type: list required: true @@ -4705,12 +5143,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -4725,12 +5237,6 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: - type: list - required: true - status: SUPPORTED - entry_schema: - type: string compute_1c2_catalog_instance_metadata: type: list required: true @@ -4743,10 +5249,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_1c2_t1_port_exCP_naming: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_network: type: list required: true @@ -4759,11 +5267,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -5221,12 +5725,86 @@ node_types: org.openecomp.resource.abstract.nodes.1c2_catalog_instance_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1c2_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1c2_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -5241,22 +5819,18 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: - type: list - required: true - status: SUPPORTED - entry_schema: - type: string compute_1c2_catalog_instance_name: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string + type: string + port_1c2_t1_port_exCP_naming: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1c2_t1_port_network: type: list required: true @@ -5269,11 +5843,7 @@ node_types: status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true status: SUPPORTED @@ -5726,6 +6296,80 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_2b_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + compute_b_single_2b_metadata: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + compute_b_single_2b_scheduler_hints: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_b_single_2b_availability_zone: type: list required: true @@ -5746,6 +6390,12 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_1b_t2_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1b_t2_port_ip_requirements: type: list required: true @@ -5758,50 +6408,42 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED compute_b_single_2b_user_data_format: type: list required: true status: SUPPORTED entry_schema: type: string - compute_b_single_2b_metadata: + port_1b_t1_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1b_t1_port_ip_requirements: + type: string + port_1b_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED + type: string port_1b_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - compute_b_single_2b_scheduler_hints: + port_1b_t2_port_network: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1b_t2_port_network: + type: string + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json attributes: b_single_2b_instance_name: type: list @@ -6225,6 +6867,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_1b_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -6251,16 +6961,18 @@ node_types: status: SUPPORTED entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_1b_t1_port_value_specs: type: list required: true @@ -6273,16 +6985,12 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -6295,12 +7003,12 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -6741,6 +7449,74 @@ node_types: org.openecomp.resource.abstract.nodes.b_single_2b_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_1b_t1_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_1b_t1_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + compute_b_single_2b_scheduler_hints: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_1b_t2_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_b_single_2b_availability_zone: type: list required: true @@ -6761,6 +7537,12 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_1b_t2_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_1b_t2_port_ip_requirements: type: list required: true @@ -6773,10 +7555,6 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED port_1b_t1_port_value_specs: type: list required: true @@ -6795,34 +7573,30 @@ node_types: status: SUPPORTED entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED + type: string port_1b_t1_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - compute_b_single_2b_scheduler_hints: + port_1b_t2_port_network: type: list required: true status: SUPPORTED entry_schema: - type: json - port_1b_t2_port_network: + type: string + port_1b_t1_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/MainServiceTemplate.yaml index 4c81d27afc..d61ea01cc8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/MainServiceTemplate.yaml @@ -284,32 +284,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 3 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - get_attribute: - abstract_1c2_catalog_instance_1 @@ -342,32 +342,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 2 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - get_attribute: - abstract_1c2_catalog_instance_0 @@ -400,13 +400,23 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_metadata: - connectivityTo4PNested_2: get_attribute: @@ -480,21 +490,11 @@ topology_template: - get_input: - 1c2_catalog_instance_names - 1 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - RAW1 port_1c2_t1_port_network_role_tag: @@ -525,32 +525,32 @@ topology_template: directives: - substitutable properties: + compute_1c2_catalog_instance_availability_zone: + - get_input: availabilityzone_name + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name + port_1c2_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_1c2_t1_port_mac_requirements: - mac_count_required: is_required: false port_1c2_t2_port_network: - 1c2_catalog_instance_network - compute_1c2_catalog_instance_availability_zone: - - get_input: availabilityzone_name compute_1c2_catalog_instance_name: - get_input: - 1c2_catalog_instance_names - 2 - vm_flavor_name: - get_input: pd_flavor_name port_1c2_t1_port_network: - get_input: oam_net_name port_1c2_t2_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: pd_image_name - port_1c2_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_1c2_catalog_instance_user_data_format: - RAW1 port_1c2_t1_port_network_role_tag: @@ -708,10 +708,6 @@ topology_template: get_attribute: - abstract_1c2_catalog_instance_1 - 1c2_catalog_instance_instance_name - compute_a_single_1a_availability_zone: - - get_input: availabilityzone_name - compute_a_single_1a_scheduler_hints: - - group: BE_Affinity_group port_1a_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -737,6 +733,10 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + compute_a_single_1a_availability_zone: + - get_input: availabilityzone_name + compute_a_single_1a_scheduler_hints: + - group: BE_Affinity_group compute_a_single_1a_user_data_format: - RAW compute_a_single_1a_name: @@ -860,6 +860,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_2b_scheduler_hints: + - group: BE_Affinity_group compute_b_single_2b_availability_zone: - get_input: availabilityzone_name port_1b_t2_port_mac_requirements: @@ -875,8 +887,6 @@ topology_template: - get_input: - b_single_2b_names - 1 - vm_flavor_name: - get_input: pd_flavor_name port_1b_t1_port_value_specs: - get_attribute: - abstract_a_single_1a @@ -885,19 +895,9 @@ topology_template: - RAW port_1b_t1_port_network_role_tag: - oam - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false - compute_b_single_2b_scheduler_hints: - - group: BE_Affinity_group port_1b_t2_port_network: - b_single_1b_network_2 port_1b_t1_port_network: @@ -1025,19 +1025,11 @@ topology_template: get_input: - myIPs - 1 - vm_image_name: - get_input: pd_image_name port_1c1_t1_port_mac_requirements: - mac_count_required: is_required: false - mac_count_required: is_required: false - port_1c1_t1_port_name: - - 1c1_t1_port_01 - - 1c1_t1_port_02 - compute_1c11_scalling_instance_scheduler_hints: - - group: BE_Affinity_group - - group: BE_Affinity_group vm_flavor_name: get_input: pd_flavor_name compute_1c11_scalling_instance_name: @@ -1047,9 +1039,6 @@ topology_template: - get_input: - 1c11_scalling_instance_names - 2 - port_1c1_t1_port_network: - - 1c1_scalling_instance_network - - 1c1_scalling_instance_network compute_1c11_scalling_instance_availability_zone: - get_input: availabilityzone_name - get_input: availabilityzone_name @@ -1067,6 +1056,17 @@ topology_template: is_required: true floating_ip_count_required: is_required: false + vm_image_name: + get_input: pd_image_name + port_1c1_t1_port_name: + - 1c1_t1_port_01 + - 1c1_t1_port_02 + compute_1c11_scalling_instance_scheduler_hints: + - group: BE_Affinity_group + - group: BE_Affinity_group + port_1c1_t1_port_network: + - 1c1_scalling_instance_network + - 1c1_scalling_instance_network service_template_filter: substitute_service_template: Nested_1c11_scalling_instanceServiceTemplate.yaml count: 2 @@ -1085,25 +1085,8 @@ topology_template: directives: - substitutable properties: - compute_b_single_2b_availability_zone: - - get_input: availabilityzone_name - port_1b_t2_port_mac_requirements: - - mac_count_required: - is_required: false - port_1b_t2_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - compute_b_single_2b_name: - - get_input: - - b_single_2b_names - - 0 vm_flavor_name: get_input: pd_flavor_name - compute_b_single_2b_user_data_format: - - RAW compute_b_single_2b_metadata: - connectivityTo4PNested_2: get_attribute: @@ -1177,11 +1160,28 @@ topology_template: is_required: false vm_image_name: get_input: pd_image_name + compute_b_single_2b_scheduler_hints: + - group: BE_Affinity_group + compute_b_single_2b_availability_zone: + - get_input: availabilityzone_name + port_1b_t2_port_mac_requirements: + - mac_count_required: + is_required: false + port_1b_t2_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + compute_b_single_2b_name: + - get_input: + - b_single_2b_names + - 0 + compute_b_single_2b_user_data_format: + - RAW port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false - compute_b_single_2b_scheduler_hints: - - group: BE_Affinity_group port_1b_t2_port_network: - b_single_1b_network_2 service_template_filter: @@ -1231,24 +1231,13 @@ topology_template: - get_input: - 1c12_scalling_instance_names - 2 - vm_image_name: - get_input: pd_image_name port_1c1_t1_port_mac_requirements: - mac_count_required: is_required: false - mac_count_required: is_required: false - port_1c1_t1_port_name: - - 1c1_t1_port_11 - - 1c1_t1_port_12 vm_flavor_name: get_input: pd_flavor_name - compute_1c12_scalling_instance_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - port_1c1_t1_port_network: - - 1c1_scalling_instance_network - - 1c1_scalling_instance_network compute_1c12_scalling_instance_user_data_format: - RAW1 - RAW1 @@ -1263,6 +1252,17 @@ topology_template: is_required: true floating_ip_count_required: is_required: false + vm_image_name: + get_input: pd_image_name + port_1c1_t1_port_name: + - 1c1_t1_port_11 + - 1c1_t1_port_12 + compute_1c12_scalling_instance_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + port_1c1_t1_port_network: + - 1c1_scalling_instance_network + - 1c1_scalling_instance_network service_template_filter: substitute_service_template: Nested_1c12_scalling_instanceServiceTemplate.yaml count: 2 @@ -1411,14 +1411,8 @@ topology_template: directives: - substitutable properties: - compute_a_single_2a_name: - - get_input: - - a_single_2a_names - - 0 compute_a_single_2a_user_data_format: - RAW - vm_image_name: - get_input: pd_image_name port_1a_t1_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -1431,6 +1425,17 @@ topology_template: - get_input: availabilityzone_name vm_flavor_name: get_input: pd_flavor_name + port_1a_t1_port_mac_requirements: + - mac_count_required: + is_required: false + port_1a_t1_port_network: + - a_single_1a_network + compute_a_single_2a_name: + - get_input: + - a_single_2a_names + - 0 + vm_image_name: + get_input: pd_image_name compute_a_single_2a_metadata: - connectivityTo4PNested_2: get_attribute: @@ -1495,11 +1500,6 @@ topology_template: get_attribute: - abstract_1c2_catalog_instance_1 - 1c2_catalog_instance_instance_name - port_1a_t1_port_mac_requirements: - - mac_count_required: - is_required: false - port_1a_t1_port_network: - - a_single_1a_network service_template_filter: substitute_service_template: Nested_a_single_2aServiceTemplate.yaml count: 1 @@ -1518,6 +1518,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_1b_user_data_format: + - RAW port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false @@ -1531,29 +1543,17 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name port_1b_t1_port_value_specs: - get_attribute: - abstract_a_single_1a - a_single_1a_1a_t1_port_tenant_id port_1b_t1_port_network_role_tag: - oam - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name port_1b_t1_port_mac_requirements: - mac_count_required: is_required: false port_1b_t2_port_network: - b_single_1b_network_1 - compute_b_single_1b_user_data_format: - - RAW port_1b_t1_port_network: - get_input: oam_net_name compute_b_single_1b_name: @@ -1762,6 +1762,18 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: pd_flavor_name + port_1b_t1_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + compute_b_single_1b_user_data_format: + - RAW port_1b_t2_port_mac_requirements: - mac_count_required: is_required: false @@ -1775,16 +1787,6 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: pd_flavor_name - port_1b_t1_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pd_image_name compute_b_single_1b_metadata: - connectivityTo4PNested_2: get_attribute: @@ -1855,8 +1857,6 @@ topology_template: is_required: false port_1b_t2_port_network: - b_single_1b_network_1 - compute_b_single_1b_user_data_format: - - RAW compute_b_single_1b_name: - get_input: - b_single_1b_names diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c11_scalling_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c11_scalling_instanceServiceTemplate.yaml index 610b8d7a56..a249ecf5cc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c11_scalling_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c11_scalling_instanceServiceTemplate.yaml @@ -11,14 +11,21 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c1_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json port_1c1_t1_port_fixed_ips: type: list required: true entry_schema: type: json - vm_image_name: - type: string + port_1c1_t1_port_vlan_requirements: + type: list required: true + entry_schema: + type: json port_1c1_t1_port_mac_requirements: type: list required: true @@ -31,44 +38,67 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_1c1_t1_port_name: + vm_flavor_name: + type: string + required: true + compute_1c11_scalling_instance_name: type: list required: true entry_schema: type: string - compute_1c11_scalling_instance_scheduler_hints: + compute_1c11_scalling_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_1c11_scalling_instance_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_ip_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: + vm_image_name: type: string required: true - compute_1c11_scalling_instance_name: + port_1c1_t1_port_name: type: list required: true entry_schema: type: string - port_1c1_t1_port_network: + compute_1c11_scalling_instance_scheduler_hints: + type: list + required: true + entry_schema: + type: json + port_1c1_t1_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_1c11_scalling_instance_availability_zone: + port_1c1_t1_port_network_role_tag: type: list required: true entry_schema: type: string - compute_1c11_scalling_instance_user_data_format: + port_1c1_t1_port_network_role: type: list required: true entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t1_port_network: type: list required: true entry_schema: - type: json + type: string + port_1c1_t1_port_order: + type: list + required: true + entry_schema: + type: integer node_templates: 1c11_scalling_instance: type: org.openecomp.resource.vfc.nodes.heat.1c11_scalling_instance @@ -96,14 +126,38 @@ topology_template: 1c11_scalling_instance_1c1_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c1_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c1_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t1_port_order + - index_value + network_role: + get_input: + - port_1c1_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t1_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t1_port_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c12_scalling_instanceServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c12_scalling_instanceServiceTemplate.yaml index 09698482d3..90c0f22132 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c12_scalling_instanceServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c12_scalling_instanceServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c1_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json compute_1c12_scalling_instance_scheduler_hints: type: list required: true @@ -26,9 +31,11 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string + port_1c1_t1_port_vlan_requirements: + type: list required: true + entry_schema: + type: json port_1c1_t1_port_mac_requirements: type: list required: true @@ -41,46 +48,93 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_1c1_t1_port_name: + vm_flavor_name: + type: string + required: true + compute_1c12_scalling_instance_user_data_format: type: list required: true entry_schema: type: string - vm_flavor_name: + port_1c1_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: type: string required: true - compute_1c12_scalling_instance_availability_zone: + port_1c1_t1_port_name: type: list required: true entry_schema: type: string - port_1c1_t1_port_network: + port_1c1_t1_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_1c12_scalling_instance_user_data_format: + port_1c1_t1_port_network_role_tag: type: list required: true entry_schema: type: string - port_1c1_t1_port_ip_requirements: + port_1c1_t1_port_network_role: type: list required: true entry_schema: - type: json + type: string + compute_1c12_scalling_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1c1_t1_port_order: + type: list + required: true + entry_schema: + type: integer node_templates: 1c12_scalling_instance_1c1_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c1_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c1_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c1_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c1_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c1_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c1_t1_port_order + - index_value + network_role: + get_input: + - port_1c1_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c1_t1_port_subnetpoolid + - index_value fixed_ips: get_input: - port_1c1_t1_port_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml index 67305b71ce..7a439484d6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_0ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,11 +89,6 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: - type: list - required: true - entry_schema: - type: string compute_1c2_catalog_instance_metadata: type: list required: true @@ -43,9 +99,11 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1c2_t1_port_exCP_naming: + type: list required: true + entry_schema: + type: json port_1c2_t1_port_network: type: list required: true @@ -56,10 +114,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -115,14 +170,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -135,6 +214,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -147,6 +234,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml index 278dffc4ff..e384bc3dc4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_1ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_2ServiceTemplate.yaml index edff50ac2e..1ff0c9b441 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_2ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_3ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_3ServiceTemplate.yaml index 5d93924142..ea49f9743e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_3ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_1c2_catalog_instance_3ServiceTemplate.yaml @@ -11,11 +11,72 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1c2_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_1c2_catalog_instance_availability_zone: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1c2_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1c2_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1c2_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1c2_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1c2_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_1c2_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json port_1c2_t1_port_mac_requirements: type: list required: true entry_schema: type: json + port_1c2_t1_port_network_role: + type: list + required: true + entry_schema: + type: string port_1c2_t2_port_network: type: list required: true @@ -28,19 +89,16 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - compute_1c2_catalog_instance_availability_zone: + compute_1c2_catalog_instance_name: type: list required: true entry_schema: type: string - compute_1c2_catalog_instance_name: + port_1c2_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true + type: json port_1c2_t1_port_network: type: list required: true @@ -51,10 +109,7 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string - required: true - port_1c2_t2_port_ip_requirements: + port_1c2_t2_port_vlan_requirements: type: list required: true entry_schema: @@ -106,14 +161,38 @@ topology_template: 1c2_catalog_instance_1c2_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1c2_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1c2_t2_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t2_port_order + - index_value + network_role: + get_input: + - port_1c2_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t2_port_subnetpoolid + - index_value network: get_input: - port_1c2_t2_port_network @@ -126,6 +205,14 @@ topology_template: 1c2_catalog_instance_1c2_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1c2_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1c2_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1c2_t1_port_ip_requirements @@ -138,6 +225,18 @@ topology_template: get_input: - port_1c2_t1_port_mac_requirements - index_value + order: + get_input: + - port_1c2_t1_port_order + - index_value + network_role: + get_input: + - port_1c2_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1c2_t1_port_subnetpoolid + - index_value network: get_input: - port_1c2_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_1aServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_1aServiceTemplate.yaml index 409bf1d35f..c0ea9ef793 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_1aServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_1aServiceTemplate.yaml @@ -16,6 +16,62 @@ topology_template: required: true entry_schema: type: json + port_1a_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_1a_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1a_t2_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_network: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + port_1a_t2_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_1a_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json compute_a_single_1a_availability_zone: type: list required: true @@ -33,42 +89,41 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_1a_t1_port_ip_requirements: + port_1a_t1_port_network_role_tag: type: list required: true entry_schema: - type: json - port_1a_t2_port_network_role_tag: + type: string + port_1a_t1_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_1a_t1_port_order: + type: list required: true - port_1a_t2_port_network: + entry_schema: + type: integer + port_1a_t2_port_exCP_naming: type: list required: true entry_schema: - type: string - port_1a_t1_port_mac_requirements: + type: json + port_1a_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - port_1a_t1_port_network: + port_1a_t2_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true - port_1a_t2_port_ip_requirements: + port_1a_t2_port_order: type: list required: true entry_schema: - type: json + type: integer compute_a_single_1a_user_data_format: type: list required: true @@ -88,14 +143,38 @@ topology_template: a_single_1a_1a_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1a_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1a_t1_port_mac_requirements - index_value + order: + get_input: + - port_1a_t1_port_order + - index_value + network_role: + get_input: + - port_1a_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t1_port_subnetpoolid + - index_value network: get_input: - port_1a_t1_port_network @@ -135,6 +214,14 @@ topology_template: a_single_1a_1a_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t2_port_ip_requirements @@ -147,6 +234,18 @@ topology_template: get_input: - port_1a_t2_port_mac_requirements - index_value + order: + get_input: + - port_1a_t2_port_order + - index_value + network_role: + get_input: + - port_1a_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t2_port_subnetpoolid + - index_value network: get_input: - port_1a_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_2aServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_2aServiceTemplate.yaml index cfd54f1688..800932c2ed 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_2aServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_a_single_2aServiceTemplate.yaml @@ -11,19 +11,16 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - compute_a_single_2a_name: + compute_a_single_2a_user_data_format: type: list required: true entry_schema: type: string - compute_a_single_2a_user_data_format: + port_1a_t1_port_exCP_naming: type: list required: true entry_schema: - type: string - vm_image_name: - type: string - required: true + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -36,11 +33,26 @@ topology_template: required: true entry_schema: type: json + port_1a_t1_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1a_t1_port_network_role: + type: list + required: true + entry_schema: + type: string compute_a_single_2a_scheduler_hints: type: list required: true entry_schema: type: json + port_1a_t1_port_order: + type: list + required: true + entry_schema: + type: integer compute_a_single_2a_availability_zone: type: list required: true @@ -49,21 +61,39 @@ topology_template: vm_flavor_name: type: string required: true - compute_a_single_2a_metadata: + port_1a_t1_port_mac_requirements: type: list required: true entry_schema: type: json - port_1a_t1_port_mac_requirements: + port_1a_t1_port_network: type: list required: true entry_schema: - type: json - port_1a_t1_port_network: + type: string + port_1a_t1_port_subnetpoolid: type: list required: true entry_schema: type: string + compute_a_single_2a_name: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + port_1a_t1_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + compute_a_single_2a_metadata: + type: list + required: true + entry_schema: + type: json node_templates: a_single_2a: type: org.openecomp.resource.vfc.nodes.heat.a_single_2a @@ -95,14 +125,38 @@ topology_template: a_single_2a_1a_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1a_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1a_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1a_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1a_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1a_t1_port_mac_requirements - index_value + order: + get_input: + - port_1a_t1_port_order + - index_value + network_role: + get_input: + - port_1a_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1a_t1_port_subnetpoolid + - index_value network: get_input: - port_1a_t1_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_0ServiceTemplate.yaml index b274d6c05d..d7831802db 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_0ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -33,14 +89,16 @@ topology_template: required: true entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string + port_1b_t2_port_ip_requirements: + type: list required: true + entry_schema: + type: json port_1b_t1_port_value_specs: type: list required: true @@ -51,14 +109,11 @@ topology_template: required: true entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true entry_schema: - type: json - vm_image_name: - type: string - required: true + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -69,11 +124,11 @@ topology_template: required: true entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -115,6 +170,14 @@ topology_template: get_input: - port_1b_t1_port_value_specs - index_value + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements @@ -127,6 +190,18 @@ topology_template: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_input: - port_1b_t1_port_network @@ -139,14 +214,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_1ServiceTemplate.yaml index 36ead5cbaf..b80c2db770 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_1b_1ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + compute_b_single_1b_user_data_format: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t2_port_mac_requirements: type: list required: true @@ -33,27 +89,31 @@ topology_template: required: true entry_schema: type: json - port_1b_t2_port_ip_requirements: + port_1b_t2_port_vlan_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string - required: true - port_1b_t1_port_ip_requirements: + port_1b_t2_port_ip_requirements: type: list required: true entry_schema: type: json - vm_image_name: - type: string + port_1b_t1_port_network_role_tag: + type: list required: true + entry_schema: + type: string compute_b_single_1b_metadata: type: list required: true entry_schema: type: json + port_1b_t1_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_1b_t1_port_mac_requirements: type: list required: true @@ -64,11 +124,11 @@ topology_template: required: true entry_schema: type: string - compute_b_single_1b_user_data_format: + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json compute_b_single_1b_name: type: list required: true @@ -105,14 +165,38 @@ topology_template: b_single_1b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_attribute: - b_single_1b @@ -125,14 +209,38 @@ topology_template: b_single_1b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_0ServiceTemplate.yaml index 8fb57944db..5ce31a4d71 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_0ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + compute_b_single_2b_scheduler_hints: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_b_single_2b_availability_zone: type: list required: true @@ -28,6 +84,11 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_1b_t2_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_1b_t2_port_ip_requirements: type: list required: true @@ -38,9 +99,6 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true port_1b_t1_port_value_specs: type: list required: true @@ -56,29 +114,26 @@ topology_template: required: true entry_schema: type: string - port_1b_t1_port_ip_requirements: + port_1b_t1_port_subnetpoolid: type: list required: true entry_schema: - type: json - vm_image_name: - type: string - required: true + type: string port_1b_t1_port_mac_requirements: type: list required: true entry_schema: type: json - compute_b_single_2b_scheduler_hints: + port_1b_t2_port_network: type: list required: true entry_schema: - type: json - port_1b_t2_port_network: + type: string + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json port_1b_t1_port_network: type: list required: true @@ -115,6 +170,14 @@ topology_template: get_input: - port_1b_t1_port_value_specs - index_value + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements @@ -127,6 +190,18 @@ topology_template: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_input: - port_1b_t1_port_network @@ -139,14 +214,38 @@ topology_template: b_single_2b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_1ServiceTemplate.yaml index f867345250..a8680d8869 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/Nested_b_single_2b_1ServiceTemplate.yaml @@ -11,6 +11,67 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_1b_t1_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t1_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t1_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + compute_b_single_2b_metadata: + type: list + required: true + entry_schema: + type: json + port_1b_t1_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + compute_b_single_2b_scheduler_hints: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_order: + type: list + required: true + entry_schema: + type: integer + port_1b_t2_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_1b_t2_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_1b_t2_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_b_single_2b_availability_zone: type: list required: true @@ -28,6 +89,11 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_1b_t2_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_1b_t2_port_ip_requirements: type: list required: true @@ -38,42 +104,36 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true compute_b_single_2b_user_data_format: type: list required: true entry_schema: type: string - compute_b_single_2b_metadata: + port_1b_t1_port_network_role_tag: type: list required: true entry_schema: - type: json - port_1b_t1_port_ip_requirements: + type: string + port_1b_t1_port_subnetpoolid: type: list required: true entry_schema: - type: json - vm_image_name: - type: string - required: true + type: string port_1b_t1_port_mac_requirements: type: list required: true entry_schema: type: json - compute_b_single_2b_scheduler_hints: + port_1b_t2_port_network: type: list required: true entry_schema: - type: json - port_1b_t2_port_network: + type: string + port_1b_t1_port_vlan_requirements: type: list required: true entry_schema: - type: string + type: json node_templates: b_single_2b: type: org.openecomp.resource.vfc.nodes.heat.b_single_2b @@ -105,14 +165,38 @@ topology_template: b_single_2b_1b_t1_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t1_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t1_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t1_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t1_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t1_port_mac_requirements - index_value + order: + get_input: + - port_1b_t1_port_order + - index_value + network_role: + get_input: + - port_1b_t1_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t1_port_subnetpoolid + - index_value network: get_attribute: - b_single_2b @@ -125,14 +209,38 @@ topology_template: b_single_2b_1b_t2_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_1b_t2_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_1b_t2_port_vlan_requirements + - index_value ip_requirements: get_input: - port_1b_t2_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_1b_t2_port_network_role_tag + - index_value mac_requirements: get_input: - port_1b_t2_port_mac_requirements - index_value + order: + get_input: + - port_1b_t2_port_order + - index_value + network_role: + get_input: + - port_1b_t2_port_network_role + - index_value + subnetpoolid: + get_input: + - port_1b_t2_port_subnetpoolid + - index_value network: get_input: - port_1b_t2_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/nested-pcm_v0.1ServiceTemplate.yaml index d6dd992034..a8e64880b2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/mixPatterns/twoAppearancePerPatternWithConnectivities/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,32 +11,90 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - server_group: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string + availabilityzone_name: + label: availabilityzone name hidden: false immutable: false type: string - connectivityChk: + description: availabilityzone name + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + pcm_image_name: + label: image name hidden: false immutable: false - type: json - availabilityzone_name: - label: availabilityzone name + type: string + description: PCRF CM image name + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_server_name: + label: PCRF CM server name hidden: false immutable: false type: string - description: availabilityzone name - oam_net_gw: - label: CPS network gateway + description: PCRF CM server name + cps_net_mask: + label: CPS network mask hidden: false immutable: false type: string - description: CPS network gateway - pcm_image_name: - label: image name + description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + oam_net_name: + label: OAM network name hidden: false immutable: false type: string - description: PCRF CM image name + description: OAM network name + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string + server_group: + hidden: false + immutable: false + type: string + connectivityChk: + hidden: false + immutable: false + type: json + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway security_group_name: label: security group name hidden: false @@ -49,6 +107,11 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false @@ -61,24 +124,12 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume - pcm_server_name: - label: PCRF CM server name - hidden: false - immutable: false - type: string - description: PCRF CM server name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -91,12 +142,11 @@ topology_template: immutable: false type: string description: CPS network mask - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -109,15 +159,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -150,15 +220,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml index 0138bf7b61..1155109ae9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -18,6 +24,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -33,11 +45,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -68,11 +104,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string @@ -495,6 +555,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -505,6 +571,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -520,11 +592,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -555,11 +651,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml index 1ab6da631d..1a50030cb0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml index a5e41ea4fa..e75b827856 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/diffNestedFilesWithSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedMultiLevels/out/Nested_jsaServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedMultiLevels/out/Nested_jsaServiceTemplate.yaml new file mode 100644 index 0000000000..80fe6dec9c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedMultiLevels/out/Nested_jsaServiceTemplate.yaml @@ -0,0 +1,171 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +metadata: + template_name: Nested_jsa +imports: +- openecomp_heat_index: + file: openecomp-heat/_index.yml +- GlobalSubstitutionTypes: + file: GlobalSubstitutionTypesServiceTemplate.yaml +node_types: + org.openecomp.resource.vfc.nodes.heat.jsa: + derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server +topology_template: + inputs: + compute_jsa_name: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + node_templates: + jsa: + type: org.openecomp.resource.vfc.nodes.heat.jsa + properties: + image: + get_input: vm_image_name + name: + get_input: + - compute_jsa_name + - index_value + substitution_mappings: + node_type: org.openecomp.resource.abstract.nodes.jsa + capabilities: + instance_jsa: + - jsa + - instance + disk.latency_jsa: + - jsa + - disk.latency + disk.device.usage_jsa: + - jsa + - disk.device.usage + disk.iops_jsa: + - jsa + - disk.iops + disk.read.bytes.rate_jsa: + - jsa + - disk.read.bytes.rate + disk.device.allocation_jsa: + - jsa + - disk.device.allocation + disk.write.bytes.rate_jsa: + - jsa + - disk.write.bytes.rate + disk.ephemeral.size_jsa: + - jsa + - disk.ephemeral.size + cpu_util_jsa: + - jsa + - cpu_util + disk.device.write.bytes.rate_jsa: + - jsa + - disk.device.write.bytes.rate + disk.read.bytes_jsa: + - jsa + - disk.read.bytes + disk.capacity_jsa: + - jsa + - disk.capacity + disk.write.bytes_jsa: + - jsa + - disk.write.bytes + memory.usage_jsa: + - jsa + - memory.usage + disk.device.read.bytes.rate_jsa: + - jsa + - disk.device.read.bytes.rate + disk.device.capacity_jsa: + - jsa + - disk.device.capacity + disk.device.read.requests_jsa: + - jsa + - disk.device.read.requests + endpoint_jsa: + - jsa + - endpoint + disk.read.requests_jsa: + - jsa + - disk.read.requests + memory.resident_jsa: + - jsa + - memory.resident + disk.device.write.requests.rate_jsa: + - jsa + - disk.device.write.requests.rate + scalable_jsa: + - jsa + - scalable + feature_jsa: + - jsa + - feature + cpu_jsa: + - jsa + - cpu + disk.usage_jsa: + - jsa + - disk.usage + disk.write.requests_jsa: + - jsa + - disk.write.requests + memory_jsa: + - jsa + - memory + disk.device.write.bytes_jsa: + - jsa + - disk.device.write.bytes + disk.root.size_jsa: + - jsa + - disk.root.size + cpu.delta_jsa: + - jsa + - cpu.delta + disk.device.write.requests_jsa: + - jsa + - disk.device.write.requests + disk.device.read.requests.rate_jsa: + - jsa + - disk.device.read.requests.rate + os_jsa: + - jsa + - os + disk.allocation_jsa: + - jsa + - disk.allocation + binding_jsa: + - jsa + - binding + disk.device.read.bytes_jsa: + - jsa + - disk.device.read.bytes + host_jsa: + - jsa + - host + disk.device.latency_jsa: + - jsa + - disk.device.latency + vcpus_jsa: + - jsa + - vcpus + disk.device.iops_jsa: + - jsa + - disk.device.iops + disk.write.requests.rate_jsa: + - jsa + - disk.write.requests.rate + requirements: + local_storage_jsa: + - jsa + - local_storage + dependency_jsa: + - jsa + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 45251124c8..a0430c354b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string p1: type: string description: UID of OAM network @@ -23,16 +29,73 @@ node_types: description: availabilityzone name required: true status: SUPPORTED - oam_net_gw: - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED security_group_name: type: string description: the name of security group @@ -43,6 +106,12 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance @@ -53,21 +122,11 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED - pcm_server_name: - type: string - description: PCRF CM server name - required: true - status: SUPPORTED cps_net_name: type: string description: CPS network name required: true status: SUPPORTED - cps_net_mask: - type: string - description: CPS network mask - required: true - status: SUPPORTED oam_net_ip: type: string description: OAM network ip @@ -78,11 +137,12 @@ node_types: description: CPS network mask required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name + port_pcm_port_1_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer attributes: server_pcm_id: type: string @@ -510,11 +570,67 @@ node_types: description: UID of OAM network required: true status: SUPPORTED + port_oam_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name required: true status: SUPPORTED + port_oam_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + oam_server_name: + type: string + description: oam server name + required: true + status: SUPPORTED + port_oam_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_oam_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_oam_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_oam_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_image_name: + type: string + description: oam image name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED oam_net_gw: type: string description: CPS network gateway @@ -535,29 +651,38 @@ node_types: description: CPS network ip required: true status: SUPPORTED - oam_server_name: - type: string - description: oam server name + port_oam_port_0_order: + type: list required: true status: SUPPORTED - pcm_vol: - type: string - description: CPS Cluman Cinder Volume + entry_schema: + type: integer + port_oam_port_0_vlan_requirements: + type: list required: true status: SUPPORTED - oam_image_name: - type: string - description: oam image name + entry_schema: + type: json + port_oam_port_1_exCP_naming: + type: list required: true status: SUPPORTED - cps_net_name: + entry_schema: + type: json + port_oam_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + pcm_vol: type: string - description: CPS network name + description: CPS Cluman Cinder Volume required: true status: SUPPORTED - cps_net_mask: + cps_net_name: type: string - description: CPS network mask + description: CPS network name required: true status: SUPPORTED oam_net_ip: @@ -575,11 +700,6 @@ node_types: description: UID of OAM network required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name - required: true - status: SUPPORTED attributes: server_oam_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-oam_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-oam_v0.1ServiceTemplate.yaml index 007006b550..2decadf3c7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-oam_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-oam_v0.1ServiceTemplate.yaml @@ -16,12 +16,66 @@ topology_template: immutable: false type: string description: UID of OAM network + port_oam_port_1_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false immutable: false type: string description: availabilityzone name + port_oam_port_0_network_role: + type: list + required: true + entry_schema: + type: string + oam_server_name: + label: oam server name + hidden: false + immutable: false + type: string + description: oam server name + port_oam_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_oam_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_oam_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_oam_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + oam_image_name: + label: image name + hidden: false + immutable: false + type: string + description: oam image name + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name oam_net_gw: label: CPS network gateway hidden: false @@ -46,36 +100,38 @@ topology_template: immutable: false type: string description: CPS network ip - oam_server_name: - label: oam server name - hidden: false - immutable: false - type: string - description: oam server name + port_oam_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_oam_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_oam_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_oam_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json pcm_vol: label: CPS Cluman Cinder Volume hidden: false immutable: false type: string description: CPS Cluman Cinder Volume - oam_image_name: - label: image name - hidden: false - immutable: false - type: string - description: oam image name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -93,12 +149,6 @@ topology_template: immutable: false type: string description: UID of OAM network - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name node_templates: oam_port_0: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -111,15 +161,35 @@ topology_template: is_required: false security_groups: - get_input: shared_security_group_id1 + network_role: + get_input: + - port_oam_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_oam_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_oam_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_oam_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_oam_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -149,15 +219,35 @@ topology_template: security_groups: - get_input: shared_security_group_id1 - get_input: security_group_name + network_role: + get_input: + - port_oam_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_oam_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_oam_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_oam_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_oam_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-pcm_v0.1ServiceTemplate.yaml index 458a0e54bb..b07c726b57 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesConnectedIn/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string p1: hidden: false immutable: false @@ -27,18 +32,71 @@ topology_template: immutable: false type: string description: availabilityzone name - oam_net_gw: - label: CPS network gateway - hidden: false - immutable: false - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false immutable: false type: string description: PCRF CM image name + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_server_name: + label: PCRF CM server name + hidden: false + immutable: false + type: string + description: PCRF CM server name + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway security_group_name: label: security group name hidden: false @@ -51,6 +109,11 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false @@ -63,24 +126,12 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume - pcm_server_name: - label: PCRF CM server name - hidden: false - immutable: false - type: string - description: PCRF CM server name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -93,12 +144,11 @@ topology_template: immutable: false type: string description: CPS network mask - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -111,15 +161,35 @@ topology_template: is_required: false security_groups: - get_input: p1 + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -150,15 +220,35 @@ topology_template: security_groups: - get_input: p1 - get_input: p2 + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 0e171ac23c..7fe923c53b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string metadata: type: string description: metadata @@ -18,16 +24,73 @@ node_types: description: availabilityzone name required: true status: SUPPORTED - oam_net_gw: - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED security_group_name: type: string description: the name of security group @@ -38,6 +101,12 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance @@ -58,21 +127,11 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED - pcm_server_name: - type: string - description: PCRF CM server name - required: true - status: SUPPORTED cps_net_name: type: string description: CPS network name required: true status: SUPPORTED - cps_net_mask: - type: string - description: CPS network mask - required: true - status: SUPPORTED oam_net_ip: type: string description: OAM network ip @@ -83,11 +142,12 @@ node_types: description: CPS network mask required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name + port_pcm_port_1_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer attributes: server_pcm_id: type: string @@ -510,6 +570,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.oam_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -520,6 +586,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_flavor_name: type: string description: flavor name of PCRF CM instance @@ -540,6 +612,30 @@ node_types: description: oam server name required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -570,11 +666,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_oam_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml index 0a5403054a..2c29cb26d5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json oam_flavor_name: label: PCRF CM flavor name hidden: false @@ -47,6 +57,26 @@ topology_template: immutable: false type: string description: oam server name + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: server_oam: type: org.openecomp.resource.vfc.nodes.heat.oam_server @@ -113,15 +163,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -138,15 +208,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml index a9df9055cd..26cd09769f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedNodesGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string metadata: label: metadata hidden: false @@ -23,18 +28,71 @@ topology_template: immutable: false type: string description: availabilityzone name - oam_net_gw: - label: CPS network gateway - hidden: false - immutable: false - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false immutable: false type: string description: PCRF CM image name + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_server_name: + label: PCRF CM server name + hidden: false + immutable: false + type: string + description: PCRF CM server name + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway security_group_name: label: security group name hidden: false @@ -47,6 +105,11 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false @@ -71,24 +134,12 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume - pcm_server_name: - label: PCRF CM server name - hidden: false - immutable: false - type: string - description: PCRF CM server name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -101,12 +152,11 @@ topology_template: immutable: false type: string description: CPS network mask - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -119,15 +169,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -157,15 +227,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 98d483a970..70506fc553 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string metadata: type: string description: metadata @@ -18,16 +24,73 @@ node_types: description: availabilityzone name required: true status: SUPPORTED - oam_net_gw: - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED security_group_name: type: string description: the name of security group @@ -38,6 +101,12 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance @@ -53,21 +122,11 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED - pcm_server_name: - type: string - description: PCRF CM server name - required: true - status: SUPPORTED cps_net_name: type: string description: CPS network name required: true status: SUPPORTED - cps_net_mask: - type: string - description: CPS network mask - required: true - status: SUPPORTED oam_net_ip: type: string description: OAM network ip @@ -78,11 +137,12 @@ node_types: description: CPS network mask required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name + port_pcm_port_1_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer attributes: server_pcm_id: type: string @@ -505,6 +565,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.oam_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -515,6 +581,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_flavor_name: type: string description: flavor name of PCRF CM instance @@ -535,6 +607,30 @@ node_types: description: oam server name required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -565,11 +661,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_oam_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml index 0a5403054a..2c29cb26d5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-oam_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json oam_flavor_name: label: PCRF CM flavor name hidden: false @@ -47,6 +57,26 @@ topology_template: immutable: false type: string description: oam server name + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: server_oam: type: org.openecomp.resource.vfc.nodes.heat.oam_server @@ -113,15 +163,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -138,15 +208,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml index 102cd3617d..ac4560a682 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedOutputParamGetAttrIn/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string metadata: label: metadata hidden: false @@ -23,18 +28,71 @@ topology_template: immutable: false type: string description: availabilityzone name - oam_net_gw: - label: CPS network gateway - hidden: false - immutable: false - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false immutable: false type: string description: PCRF CM image name + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_server_name: + label: PCRF CM server name + hidden: false + immutable: false + type: string + description: PCRF CM server name + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway security_group_name: label: security group name hidden: false @@ -47,6 +105,11 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false @@ -65,24 +128,12 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume - pcm_server_name: - label: PCRF CM server name - hidden: false - immutable: false - type: string - description: PCRF CM server name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -95,12 +146,11 @@ topology_template: immutable: false type: string description: CPS network mask - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -113,15 +163,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -151,15 +221,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/GlobalSubstitutionTypesServiceTemplate.yaml index 0f6c0e9f7a..fa86dbe5ce 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -18,6 +24,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -33,11 +45,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -68,11 +104,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/nested-pcm_v0.1ServiceTemplate.yaml index 05a21ce6d1..51429041fe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneCompute/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/MANIFEST.json b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/MANIFEST.json new file mode 100644 index 0000000000..609c38b28e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/MANIFEST.json @@ -0,0 +1,21 @@ +{ + "name": "vEP_JSA_Net", + "description": "Version 2.0 02-09-2016 (Authors: John Doe, user PROD)", + "version": "2013-05-23", + "data": [ + { + "file": "hot-nimbus-pcm_v0.4.yaml", + "type": "HEAT", + "data": [ + { + "file": "hot-nimbus-pcm_v0.4.env", + "type": "HEAT_ENV" + } + ] + }, + { + "file": "nested-pcm_v0.1.yaml", + "type": "HEAT" + } + ] +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.env b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.env new file mode 100644 index 0000000000..78cc03e2ea --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.env @@ -0,0 +1,14 @@ +parameters: + pcm_server_names: ZRDM1PCRF01PCM001 + pcm_image_name: rhel2 + pcm_flavor_name: cps + availabilityzone_name: nova + cps_net_name: int_pcrf_net_0 + cps_net_ips: 172.26.16.113 + cps_net_mask: 255.255.255.0 + oam_net_name: oam_protected_net_0 + oam_net_ips: 107.239.64.121 + oam_net_gw: 107.239.64.1 + oam_net_mask: 255.255.255.0 + pcm_volumes: 249cb355-8fdf-4382-9c3c-a2ebe767d45b + security_group_name: nimbus_security_group diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.yaml new file mode 100644 index 0000000000..dea5d4296c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/hot-nimbus-pcm_v0.4.yaml @@ -0,0 +1,103 @@ +heat_template_version: 2013-05-23 + +description: heat template that creates PCRF Cluman stack + +parameters: + pcm_server_names: + type: comma_delimited_list + label: PCRF CM server names + description: name of the PCRF CM instance + pcm_image_name: + type: string + label: PCRF CM image name + description: PCRF CM image name + pcm_flavor_name: + type: string + label: PCRF CM flavor name + description: flavor name of PCRF CM instance + availabilityzone_name: + type: string + label: availabilityzone name + description: availabilityzone name + cps_net_name: + type: string + label: CPS network name + description: CPS network name + cps_net_ips: + type: comma_delimited_list + label: CPS network ips + description: CPS network ips + cps_net_mask: + type: string + label: CPS network mask + description: CPS network mask + oam_net_name: + type: string + label: OAM network name + description: OAM network name + oam_net_ips: + type: comma_delimited_list + label: OAM network ips + description: OAM network ips + oam_net_gw: + type: string + label: CPS network gateway + description: CPS network gateway + oam_net_mask: + type: string + label: CPS network mask + description: CPS network mask + pcm_volumes: + type: comma_delimited_list + label: CPS Cluman Cinder Volume + description: CPS Cluman Cinder Volume + security_group_name: + type: string + label: security group name + description: the name of security group + compute_image_name: + type: string + net_name: + type: string + +resources: + server_pcm_001: + type: nested-pcm_v0.1.yaml + properties: + pcm_server_name: { get_param: [pcm_server_names, 0] } + pcm_image_name: { get_param: pcm_image_name } + pcm_flavor_name: { get_param: pcm_flavor_name } + availabilityzone_name: { get_param: availabilityzone_name } + security_group_name: { get_param: security_group_name } + pcm_vol: { get_param: [pcm_volumes, 0] } + cps_net_name: { get_param: cps_net_name } + cps_net_ip: { get_param: [cps_net_ips, 0] } + cps_net_mask: { get_param: cps_net_mask } + oam_net_name: { get_param: oam_net_name } + oam_net_ip: { get_param: [oam_net_ips, 0] } + oam_net_mask: { get_param: oam_net_mask } + oam_net_gw: { get_param: oam_net_gw } + + server_compute: + type: OS::Nova::Server + properties: + config_drive: {get_attr: [compute_port_0]} + name: { compute_name } + image: { get_param: compute_image_name } + flavor: { compute_flavor_name } + user_data_format: { get_attr: [server_pcm_001 , oam_net_gw] } + metadata: { get_attr: [server_pcm_001]} + + compute_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: net_name } + + packet_mirror_network: + type: OS::Neutron::Net + depends_on: + - server_pcm_001 + properties: + name: + get_param: net_name + diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/nested-pcm_v0.1.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/nested-pcm_v0.1.yaml new file mode 100644 index 0000000000..be8cb80777 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/in/nested-pcm_v0.1.yaml @@ -0,0 +1,101 @@ +heat_template_version: 2013-05-23 + +description: heat template that creates PCRF Cluman stack + +parameters: + pcm_server_name: + type: string + label: PCRF CM server name + description: PCRF CM server name + pcm_image_name: + type: string + label: image name + description: PCRF CM image name + pcm_flavor_name: + type: string + label: PCRF CM flavor name + description: flavor name of PCRF CM instance + availabilityzone_name: + type: string + label: availabilityzone name + description: availabilityzone name + cps_net_name: + type: string + label: CPS network name + description: CPS network name + cps_net_ip: + type: string + label: CPS network ip + description: CPS network ip + cps_net_mask: + type: string + label: CPS network mask + description: CPS network mask + oam_net_name: + type: string + label: OAM network name + description: OAM network name + oam_net_ip: + type: string + label: OAM network ip + description: OAM network ip + oam_net_gw: + type: string + label: CPS network gateway + description: CPS network gateway + oam_net_mask: + type: string + label: CPS network mask + description: CPS network mask + pcm_vol: + type: string + label: CPS Cluman Cinder Volume + description: CPS Cluman Cinder Volume + security_group_name: + type: string + label: security group name + description: the name of security group + +resources: + server_pcm: + type: OS::Nova::Server + properties: + config_drive: "True" + name: { get_param: pcm_server_name } + image: { get_param: pcm_image_name } + flavor: { get_param: pcm_flavor_name } + availability_zone: { get_param: availabilityzone_name } + networks: + - port: { get_resource: pcm_1port_0} + - port: { get_resource: pcm_2port_1} + block_device_mapping: + - device_name: vdb + volume_id: { get_param: pcm_vol} + user_data_format: RAW + + pcm_1port_0: + type: OS::Neutron::Port + properties: + network: { get_param: cps_net_name } + fixed_ips: + - ip_address: { get_param: cps_net_ip } + security_groups: [{ get_param: security_group_name }] + + pcm_2port_1: + type: OS::Neutron::Port + properties: + network: { get_param: oam_net_name } + fixed_ips: + - ip_address: { get_param: oam_net_ip } + security_groups: [{ get_param: security_group_name }] + + #pcm_vol_attachment: + # type: OS::Cinder::VolumeAttachment + # properties: + # volume_id: { get_param: pcm_vol } + # mountpoint: /dev/vdb + # instance_uuid: { get_resource: server_pcm } +outputs: + server_pcm_id: + description: the pcm nova service id + value: { get_resource: server_pcm } \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml new file mode 100644 index 0000000000..670f8d23ae --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -0,0 +1,855 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +metadata: + template_name: GlobalSubstitutionTypes +imports: +- openecomp_heat_index: + file: openecomp-heat/_index.yml +node_types: + org.openecomp.resource.abstract.nodes.heat.pcm_server: + derived_from: org.openecomp.resource.abstract.nodes.VFC + properties: + availabilityzone_name: + type: string + description: availabilityzone name + required: true + status: SUPPORTED + port_pcm_2port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED + pcm_image_name: + type: string + description: PCRF CM image name + required: true + status: SUPPORTED + port_pcm_1port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_1port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + security_group_name: + type: string + description: the name of security group + required: true + status: SUPPORTED + port_pcm_1port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + cps_net_ip: + type: string + description: CPS network ip + required: true + status: SUPPORTED + port_pcm_2port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_flavor_name: + type: string + description: flavor name of PCRF CM instance + required: true + status: SUPPORTED + port_pcm_2port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + pcm_vol: + type: string + description: CPS Cluman Cinder Volume + required: true + status: SUPPORTED + port_pcm_1port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_1port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_name: + type: string + description: CPS network name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + oam_net_ip: + type: string + description: OAM network ip + required: true + status: SUPPORTED + oam_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_2port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_2port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + attributes: + server_pcm_id: + type: string + description: the pcm nova service id + status: SUPPORTED + requirements: + - dependency_server_pcm: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - local_storage_server_pcm: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: + - 0 + - UNBOUNDED + - dependency_pcm_1port_0: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - link_pcm_1port_0: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: + - 1 + - 1 + - dependency_pcm_2port_1: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - link_pcm_2port_1: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: + - 1 + - 1 + capabilities: + binding_pcm_2port_1: + type: tosca.capabilities.network.Bindable + valid_source_types: + - org.openecomp.resource.cp.nodes.heat.network.contrailV2.VLANSubInterface + occurrences: + - 0 + - UNBOUNDED + cpu_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + attachment_pcm_2port_1: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + network.outgoing.bytes.rate_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + memory_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.write.requests_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.bytes_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + feature_pcm_1port_0: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + network.incoming.packets.rate_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.outpoing.packets_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.iops_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + memory.resident_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.requests_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.outgoing.packets.rate_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.usage_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.allocation_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.packets_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.outpoing.packets_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.usage_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.root.size_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.ephemeral.size_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.latency_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.bytes_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + memory.usage_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.read.requests_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.capacity_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + os_server_pcm: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.packets_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + endpoint_server_pcm: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + disk.device.read.requests.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + vcpus_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.iops_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.bytes.rate_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.allocation_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.packets.rate_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + feature_pcm_2port_1: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + scalable_server_pcm: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + network.outgoing.bytes.rate_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.outgoing.bytes_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + cpu_util_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + attachment_pcm_1port_0: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + disk.write.requests.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.incoming.bytes.rate_pcm_2port_1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + host_server_pcm: + type: tosca.capabilities.Container + valid_source_types: + - tosca.nodes.SoftwareComponent + occurrences: + - 1 + - UNBOUNDED + network.outgoing.bytes_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + binding_pcm_1port_0: + type: tosca.capabilities.network.Bindable + valid_source_types: + - org.openecomp.resource.cp.nodes.heat.network.contrailV2.VLANSubInterface + occurrences: + - 0 + - UNBOUNDED + cpu.delta_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + network.outgoing.packets.rate_pcm_1port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + binding_server_pcm: + type: tosca.capabilities.network.Bindable + occurrences: + - 1 + - UNBOUNDED + disk.device.capacity_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + instance_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.requests.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.latency_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.read.requests_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + feature_server_pcm: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes.rate_server_pcm: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + org.openecomp.resource.abstract.nodes.compute: + derived_from: org.openecomp.resource.abstract.nodes.VFC + properties: + compute_compute_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_compute_metadata: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_compute_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + compute_compute_config_drive: + type: list + required: true + status: SUPPORTED + entry_schema: + type: boolean + requirements: + - dependency_compute: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - local_storage_compute: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: + - 0 + - UNBOUNDED + capabilities: + disk.device.usage_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.write.requests_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + instance_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.ephemeral.size_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.latency_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + memory.resident_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + memory_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.iops_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.root.size_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.write.requests.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.read.requests_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.read.requests.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.usage_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + os_compute: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + vcpus_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.capacity_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + cpu_util_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.latency_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.requests_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.iops_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.requests.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + endpoint_compute: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + memory.usage_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + host_compute: + type: tosca.capabilities.Container + valid_source_types: + - tosca.nodes.SoftwareComponent + occurrences: + - 1 + - UNBOUNDED + feature_compute: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + cpu_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes.rate_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + scalable_compute: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + disk.device.read.requests_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.allocation_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.capacity_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.allocation_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + cpu.delta_compute: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + binding_compute: + type: tosca.capabilities.network.Bindable + occurrences: + - 1 + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/MainServiceTemplate.yaml new file mode 100644 index 0000000000..03d069f43d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/MainServiceTemplate.yaml @@ -0,0 +1,243 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +metadata: + template_name: Main +imports: +- openecomp_heat_index: + file: openecomp-heat/_index.yml +- GlobalSubstitutionTypes: + file: GlobalSubstitutionTypesServiceTemplate.yaml +topology_template: + inputs: + oam_net_ips: + label: OAM network ips + hidden: false + immutable: false + type: list + description: OAM network ips + default: + - 107.239.64.121 + entry_schema: + type: string + availabilityzone_name: + label: availabilityzone name + hidden: false + immutable: false + type: string + description: availabilityzone name + default: nova + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway + default: 107.239.64.1 + pcm_server_names: + label: PCRF CM server names + hidden: false + immutable: false + type: list + description: name of the PCRF CM instance + default: + - ZRDM1PCRF01PCM001 + entry_schema: + type: string + pcm_image_name: + label: PCRF CM image name + hidden: false + immutable: false + type: string + description: PCRF CM image name + default: rhel2 + cps_net_ips: + label: CPS network ips + hidden: false + immutable: false + type: list + description: CPS network ips + default: + - 172.26.16.113 + entry_schema: + type: string + security_group_name: + label: security group name + hidden: false + immutable: false + type: string + description: the name of security group + default: nimbus_security_group + pcm_volumes: + label: CPS Cluman Cinder Volume + hidden: false + immutable: false + type: list + description: CPS Cluman Cinder Volume + default: + - 249cb355-8fdf-4382-9c3c-a2ebe767d45b + entry_schema: + type: string + compute_image_name: + hidden: false + immutable: false + type: string + pcm_flavor_name: + label: PCRF CM flavor name + hidden: false + immutable: false + type: string + description: flavor name of PCRF CM instance + default: cps + net_name: + hidden: false + immutable: false + type: string + cps_net_name: + label: CPS network name + hidden: false + immutable: false + type: string + description: CPS network name + default: int_pcrf_net_0 + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + default: 255.255.255.0 + oam_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + default: 255.255.255.0 + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name + default: oam_protected_net_0 + node_templates: + abstract_pcm_server_0: + type: org.openecomp.resource.abstract.nodes.heat.pcm_server + directives: + - substitutable + properties: + availabilityzone_name: + get_input: availabilityzone_name + oam_net_gw: + get_input: oam_net_gw + pcm_image_name: + get_input: pcm_image_name + security_group_name: + get_input: security_group_name + cps_net_ip: + get_input: + - cps_net_ips + - 0 + pcm_flavor_name: + get_input: pcm_flavor_name + service_template_filter: + substitute_service_template: nested-pcm_v0.1ServiceTemplate.yaml + pcm_vol: + get_input: + - pcm_volumes + - 0 + pcm_server_name: + get_input: + - pcm_server_names + - 0 + cps_net_name: + get_input: cps_net_name + cps_net_mask: + get_input: cps_net_mask + oam_net_ip: + get_input: + - oam_net_ips + - 0 + oam_net_mask: + get_input: oam_net_mask + oam_net_name: + get_input: oam_net_name + packet_mirror_network: + type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net + properties: + network_name: + get_input: net_name + requirements: + - dependency: + capability: tosca.capabilities.Node + node: abstract_pcm_server_0 + relationship: tosca.relationships.DependsOn + compute_port_0: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + properties: + ip_requirements: + - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + mac_requirements: + mac_count_required: + is_required: false + network: + get_input: net_name + abstract_compute: + type: org.openecomp.resource.abstract.nodes.compute + directives: + - substitutable + properties: + compute_compute_user_data_format: + - get_attribute: + - abstract_pcm_server_0 + - oam_net_gw + vm_image_name: + get_input: compute_image_name + compute_compute_metadata: + - get_attribute: + - abstract_pcm_server_0 + - server_pcm_id + compute_compute_name: + - compute_name: null + vm_flavor_name: + compute_flavor_name: null + compute_compute_config_drive: + - get_attribute: + - compute_port_0 + - tenant_id + - port_security_enabled + - device_id + - qos_policy + - allowed_address_pairs + - show + - device_owner + - network + - security_groups + - fixed_ips + - mac_address + - admin_state_up + - name + - subnets + - status + service_template_filter: + substitute_service_template: Nested_computeServiceTemplate.yaml + count: 1 + index_value: + get_property: + - SELF + - service_template_filter + - index_value + groups: + hot-nimbus-pcm_v0.4_group: + type: org.openecomp.groups.heat.HeatStack + properties: + heat_file: ../Artifacts/hot-nimbus-pcm_v0.4.yaml + description: heat template that creates PCRF Cluman stack + members: + - packet_mirror_network + - compute_port_0 + - abstract_compute + - abstract_pcm_server_0 \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/Nested_computeServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/Nested_computeServiceTemplate.yaml new file mode 100644 index 0000000000..22bdef3d42 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/Nested_computeServiceTemplate.yaml @@ -0,0 +1,203 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +metadata: + template_name: Nested_compute +imports: +- openecomp_heat_index: + file: openecomp-heat/_index.yml +- GlobalSubstitutionTypes: + file: GlobalSubstitutionTypesServiceTemplate.yaml +node_types: + org.openecomp.resource.vfc.nodes.heat.compute: + derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server +topology_template: + inputs: + compute_compute_user_data_format: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_compute_metadata: + type: list + required: true + entry_schema: + type: json + compute_compute_name: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + compute_compute_config_drive: + type: list + required: true + entry_schema: + type: boolean + node_templates: + compute: + type: org.openecomp.resource.vfc.nodes.heat.compute + properties: + flavor: + get_input: vm_flavor_name + metadata: + get_input: + - compute_compute_metadata + - index_value + config_drive: + get_input: + - compute_compute_config_drive + - index_value + image: + get_input: vm_image_name + name: + get_input: + - compute_compute_name + - index_value + user_data_format: + get_input: + - compute_compute_user_data_format + - index_value + substitution_mappings: + node_type: org.openecomp.resource.abstract.nodes.compute + capabilities: + disk.device.usage_compute: + - compute + - disk.device.usage + disk.write.requests_compute: + - compute + - disk.write.requests + instance_compute: + - compute + - instance + disk.ephemeral.size_compute: + - compute + - disk.ephemeral.size + disk.device.read.bytes.rate_compute: + - compute + - disk.device.read.bytes.rate + disk.latency_compute: + - compute + - disk.latency + memory.resident_compute: + - compute + - memory.resident + memory_compute: + - compute + - memory + disk.iops_compute: + - compute + - disk.iops + disk.root.size_compute: + - compute + - disk.root.size + disk.write.requests.rate_compute: + - compute + - disk.write.requests.rate + disk.read.requests_compute: + - compute + - disk.read.requests + disk.device.read.requests.rate_compute: + - compute + - disk.device.read.requests.rate + disk.read.bytes_compute: + - compute + - disk.read.bytes + disk.device.read.bytes_compute: + - compute + - disk.device.read.bytes + disk.write.bytes_compute: + - compute + - disk.write.bytes + disk.usage_compute: + - compute + - disk.usage + os_compute: + - compute + - os + disk.write.bytes.rate_compute: + - compute + - disk.write.bytes.rate + vcpus_compute: + - compute + - vcpus + disk.capacity_compute: + - compute + - disk.capacity + cpu_util_compute: + - compute + - cpu_util + disk.read.bytes.rate_compute: + - compute + - disk.read.bytes.rate + disk.device.latency_compute: + - compute + - disk.device.latency + disk.device.write.requests_compute: + - compute + - disk.device.write.requests + disk.device.iops_compute: + - compute + - disk.device.iops + disk.device.write.requests.rate_compute: + - compute + - disk.device.write.requests.rate + endpoint_compute: + - compute + - endpoint + memory.usage_compute: + - compute + - memory.usage + host_compute: + - compute + - host + feature_compute: + - compute + - feature + disk.device.write.bytes_compute: + - compute + - disk.device.write.bytes + cpu_compute: + - compute + - cpu + disk.device.write.bytes.rate_compute: + - compute + - disk.device.write.bytes.rate + scalable_compute: + - compute + - scalable + disk.device.read.requests_compute: + - compute + - disk.device.read.requests + disk.allocation_compute: + - compute + - disk.allocation + disk.device.capacity_compute: + - compute + - disk.device.capacity + disk.device.allocation_compute: + - compute + - disk.device.allocation + cpu.delta_compute: + - compute + - cpu.delta + binding_compute: + - compute + - binding + requirements: + local_storage_compute: + - compute + - local_storage + dependency_compute: + - compute + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/nested-pcm_v0.1ServiceTemplate.yaml new file mode 100644 index 0000000000..ad1fe6a24e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithOneComputeDiffPortType/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -0,0 +1,470 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +metadata: + template_name: nested-pcm_v0.1 +imports: +- openecomp_heat_index: + file: openecomp-heat/_index.yml +- GlobalSubstitutionTypes: + file: GlobalSubstitutionTypesServiceTemplate.yaml +node_types: + org.openecomp.resource.vfc.nodes.heat.pcm_server: + derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server +topology_template: + inputs: + availabilityzone_name: + label: availabilityzone name + hidden: false + immutable: false + type: string + description: availabilityzone name + port_pcm_2port_1_network_role: + type: list + required: true + entry_schema: + type: string + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway + pcm_image_name: + label: image name + hidden: false + immutable: false + type: string + description: PCRF CM image name + port_pcm_1port_0_network_role: + type: list + required: true + entry_schema: + type: string + port_pcm_1port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + security_group_name: + label: security group name + hidden: false + immutable: false + type: string + description: the name of security group + port_pcm_1port_0_order: + type: list + required: true + entry_schema: + type: integer + cps_net_ip: + label: CPS network ip + hidden: false + immutable: false + type: string + description: CPS network ip + port_pcm_2port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_flavor_name: + label: PCRF CM flavor name + hidden: false + immutable: false + type: string + description: flavor name of PCRF CM instance + port_pcm_2port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + pcm_vol: + label: CPS Cluman Cinder Volume + hidden: false + immutable: false + type: string + description: CPS Cluman Cinder Volume + port_pcm_1port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pcm_1port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + pcm_server_name: + label: PCRF CM server name + hidden: false + immutable: false + type: string + description: PCRF CM server name + cps_net_name: + label: CPS network name + hidden: false + immutable: false + type: string + description: CPS network name + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + oam_net_ip: + label: OAM network ip + hidden: false + immutable: false + type: string + description: OAM network ip + oam_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name + port_pcm_2port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_2port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + node_templates: + server_pcm: + type: org.openecomp.resource.vfc.nodes.heat.pcm_server + properties: + flavor: + get_input: pcm_flavor_name + availability_zone: + get_input: availabilityzone_name + image: + get_input: pcm_image_name + config_drive: true + user_data_format: RAW + name: + get_input: pcm_server_name + pcm_1port_0: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + properties: + ip_requirements: + - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + security_groups: + - get_input: security_group_name + network_role: + get_input: + - port_pcm_1port_0_network_role + - index_value + fixed_ips: + - ip_address: + get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_1port_0_subnetpoolid + - index_value + mac_requirements: + mac_count_required: + is_required: false + exCP_naming: + get_input: + - port_pcm_1port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_1port_0_vlan_requirements + - index_value + network_role_tag: cps + network: + get_input: cps_net_name + order: + get_input: + - port_pcm_1port_0_order + - index_value + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: server_pcm + relationship: tosca.relationships.network.BindsTo + pcm_2port_1: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + properties: + ip_requirements: + - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + security_groups: + - get_input: security_group_name + network_role: + get_input: + - port_pcm_2port_1_network_role + - index_value + fixed_ips: + - ip_address: + get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_2port_1_subnetpoolid + - index_value + mac_requirements: + mac_count_required: + is_required: false + exCP_naming: + get_input: + - port_pcm_2port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_2port_1_vlan_requirements + - index_value + network_role_tag: oam + network: + get_input: oam_net_name + order: + get_input: + - port_pcm_2port_1_order + - index_value + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: server_pcm + relationship: tosca.relationships.network.BindsTo + groups: + nested-pcm_v0.1_group: + type: org.openecomp.groups.heat.HeatStack + properties: + heat_file: ../Artifacts/nested-pcm_v0.1.yaml + description: heat template that creates PCRF Cluman stack + members: + - server_pcm + - pcm_1port_0 + - pcm_2port_1 + outputs: + server_pcm_id: + description: the pcm nova service id + value: server_pcm + substitution_mappings: + node_type: org.openecomp.resource.abstract.nodes.heat.pcm_server + capabilities: + binding_pcm_2port_1: + - pcm_2port_1 + - binding + cpu_server_pcm: + - server_pcm + - cpu + attachment_pcm_2port_1: + - pcm_2port_1 + - attachment + network.outgoing.bytes.rate_pcm_2port_1: + - pcm_2port_1 + - network.outgoing.bytes.rate + memory_server_pcm: + - server_pcm + - memory + disk.write.requests_server_pcm: + - server_pcm + - disk.write.requests + network.incoming.bytes_pcm_2port_1: + - pcm_2port_1 + - network.incoming.bytes + feature_pcm_1port_0: + - pcm_1port_0 + - feature + network.incoming.packets.rate_pcm_2port_1: + - pcm_2port_1 + - network.incoming.packets.rate + network.outpoing.packets_pcm_2port_1: + - pcm_2port_1 + - network.outpoing.packets + disk.device.iops_server_pcm: + - server_pcm + - disk.device.iops + memory.resident_server_pcm: + - server_pcm + - memory.resident + disk.device.write.requests_server_pcm: + - server_pcm + - disk.device.write.requests + network.outgoing.packets.rate_pcm_2port_1: + - pcm_2port_1 + - network.outgoing.packets.rate + disk.device.usage_server_pcm: + - server_pcm + - disk.device.usage + disk.allocation_server_pcm: + - server_pcm + - disk.allocation + network.incoming.packets_pcm_2port_1: + - pcm_2port_1 + - network.incoming.packets + network.outpoing.packets_pcm_1port_0: + - pcm_1port_0 + - network.outpoing.packets + disk.usage_server_pcm: + - server_pcm + - disk.usage + disk.device.write.bytes_server_pcm: + - server_pcm + - disk.device.write.bytes + disk.root.size_server_pcm: + - server_pcm + - disk.root.size + disk.ephemeral.size_server_pcm: + - server_pcm + - disk.ephemeral.size + disk.device.latency_server_pcm: + - server_pcm + - disk.device.latency + network.incoming.bytes_pcm_1port_0: + - pcm_1port_0 + - network.incoming.bytes + memory.usage_server_pcm: + - server_pcm + - memory.usage + disk.read.requests_server_pcm: + - server_pcm + - disk.read.requests + disk.capacity_server_pcm: + - server_pcm + - disk.capacity + os_server_pcm: + - server_pcm + - os + disk.read.bytes_server_pcm: + - server_pcm + - disk.read.bytes + disk.device.read.bytes_server_pcm: + - server_pcm + - disk.device.read.bytes + network.incoming.packets_pcm_1port_0: + - pcm_1port_0 + - network.incoming.packets + endpoint_server_pcm: + - server_pcm + - endpoint + disk.device.read.requests.rate_server_pcm: + - server_pcm + - disk.device.read.requests.rate + vcpus_server_pcm: + - server_pcm + - vcpus + disk.write.bytes_server_pcm: + - server_pcm + - disk.write.bytes + disk.iops_server_pcm: + - server_pcm + - disk.iops + network.incoming.bytes.rate_pcm_1port_0: + - pcm_1port_0 + - network.incoming.bytes.rate + disk.read.bytes.rate_server_pcm: + - server_pcm + - disk.read.bytes.rate + disk.device.allocation_server_pcm: + - server_pcm + - disk.device.allocation + network.incoming.packets.rate_pcm_1port_0: + - pcm_1port_0 + - network.incoming.packets.rate + feature_pcm_2port_1: + - pcm_2port_1 + - feature + scalable_server_pcm: + - server_pcm + - scalable + network.outgoing.bytes.rate_pcm_1port_0: + - pcm_1port_0 + - network.outgoing.bytes.rate + network.outgoing.bytes_pcm_2port_1: + - pcm_2port_1 + - network.outgoing.bytes + disk.device.read.bytes.rate_server_pcm: + - server_pcm + - disk.device.read.bytes.rate + cpu_util_server_pcm: + - server_pcm + - cpu_util + attachment_pcm_1port_0: + - pcm_1port_0 + - attachment + disk.write.requests.rate_server_pcm: + - server_pcm + - disk.write.requests.rate + network.incoming.bytes.rate_pcm_2port_1: + - pcm_2port_1 + - network.incoming.bytes.rate + disk.device.write.bytes.rate_server_pcm: + - server_pcm + - disk.device.write.bytes.rate + host_server_pcm: + - server_pcm + - host + network.outgoing.bytes_pcm_1port_0: + - pcm_1port_0 + - network.outgoing.bytes + binding_pcm_1port_0: + - pcm_1port_0 + - binding + cpu.delta_server_pcm: + - server_pcm + - cpu.delta + network.outgoing.packets.rate_pcm_1port_0: + - pcm_1port_0 + - network.outgoing.packets.rate + binding_server_pcm: + - server_pcm + - binding + disk.device.capacity_server_pcm: + - server_pcm + - disk.device.capacity + instance_server_pcm: + - server_pcm + - instance + disk.device.write.requests.rate_server_pcm: + - server_pcm + - disk.device.write.requests.rate + disk.latency_server_pcm: + - server_pcm + - disk.latency + disk.device.read.requests_server_pcm: + - server_pcm + - disk.device.read.requests + feature_server_pcm: + - server_pcm + - feature + disk.write.bytes.rate_server_pcm: + - server_pcm + - disk.write.bytes.rate + requirements: + dependency_pcm_2port_1: + - pcm_2port_1 + - dependency + local_storage_server_pcm: + - server_pcm + - local_storage + link_pcm_1port_0: + - pcm_1port_0 + - link + dependency_pcm_1port_0: + - pcm_1port_0 + - dependency + dependency_server_pcm: + - server_pcm + - dependency + link_pcm_2port_1: + - pcm_2port_1 + - link \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/hot-nimbus-pcm_v0.4.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/hot-nimbus-pcm_v0.4.yaml index c1597faeff..0b1c25ee74 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/hot-nimbus-pcm_v0.4.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/hot-nimbus-pcm_v0.4.yaml @@ -73,7 +73,7 @@ parameters: type: string resources: - server_pcm: + server_pcm_1: type: nested-pcm_v0.1.yaml properties: pcm_server_name: { get_param: [pcm_server_names, 0] } @@ -90,7 +90,7 @@ resources: oam_net_mask: { get_param: oam_net_mask } oam_net_gw: { get_param: oam_net_gw } - server_pd: + server_pd_1: type: nested-pcm_v0.1.yaml properties: pcm_server_name: { get_param: [pd_server_names, 1] } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/nested-pcm_v0.1.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/nested-pcm_v0.1.yaml index 443a6886dc..5844fd6f02 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/nested-pcm_v0.1.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/in/nested-pcm_v0.1.yaml @@ -69,7 +69,7 @@ parameters: description: the name of security group resources: - server_pcm: + server_pcm_0: type: OS::Nova::Server properties: config_drive: "True" @@ -84,7 +84,7 @@ resources: volume_id: { get_param: pcm_vol} user_data_format: RAW - server_pd: + server_pd_0: type: OS::Nova::Server properties: config_drive: "True" @@ -117,8 +117,8 @@ resources: outputs: server_pcm_id_1: description: the pcm nova service id - value: { get_resource: server_pcm } + value: { get_resource: server_pcm_0 } server_pcm_id_2: description: the pcm nova service id - value: { get_resource: server_pd } \ No newline at end of file + value: { get_resource: server_pd_0 } \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/GlobalSubstitutionTypesServiceTemplate.yaml index 227c1af00a..ab2625118b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -98,41 +98,41 @@ node_types: description: the pcm nova service id status: SUPPORTED requirements: - - dependency_server_pcm: + - dependency_pcm_port_1: capability: tosca.capabilities.Node node: tosca.nodes.Root relationship: tosca.relationships.DependsOn occurrences: - 0 - UNBOUNDED - - local_storage_server_pcm: - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo + - link_pcm_port_1: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo occurrences: - - 0 - - UNBOUNDED - - dependency_pcm_port_1: + - 1 + - 1 + - dependency_server_pcm_0: capability: tosca.capabilities.Node node: tosca.nodes.Root relationship: tosca.relationships.DependsOn occurrences: - 0 - UNBOUNDED - - link_pcm_port_1: - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo + - local_storage_server_pcm_0: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo occurrences: - - 1 - - 1 - - dependency_server_pd: + - 0 + - UNBOUNDED + - dependency_server_pd_0: capability: tosca.capabilities.Node node: tosca.nodes.Root relationship: tosca.relationships.DependsOn occurrences: - 0 - UNBOUNDED - - local_storage_server_pd: + - local_storage_server_pd_0: capability: tosca.capabilities.Attachment node: tosca.nodes.BlockStorage relationship: tosca.relationships.AttachesTo @@ -159,13 +159,7 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.iops_server_pd: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED - disk.device.read.bytes.rate_server_pd: + disk.iops_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -177,12 +171,6 @@ node_types: occurrences: - 1 - UNBOUNDED - memory_server_pcm: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED network.outpoing.packets_pcm_port_1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. @@ -195,61 +183,37 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.device.read.requests_server_pd: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED - disk.device.iops_server_pcm: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED - disk.device.allocation_server_pd: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED - disk.allocation_server_pcm: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED - memory.usage_server_pd: + disk.write.bytes.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.read.bytes.rate_server_pd: + cpu.delta_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.usage_server_pcm: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + feature_server_pd_0: + type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - disk.root.size_server_pcm: + disk.capacity_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory_server_pd: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + host_server_pd_0: + type: tosca.capabilities.Container + valid_source_types: + - tosca.nodes.SoftwareComponent occurrences: - 1 - UNBOUNDED - disk.device.latency_server_pcm: + memory_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -261,13 +225,13 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.device.write.requests_server_pd: + network.incoming.bytes_pcm_port_1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes_pcm_port_1: + disk.usage_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -280,12 +244,6 @@ node_types: occurrences: - 0 - UNBOUNDED - memory.usage_server_pcm: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED binding_pcm_port_1: type: tosca.capabilities.network.Bindable valid_source_types: @@ -293,18 +251,29 @@ node_types: occurrences: - 0 - UNBOUNDED - disk.read.requests_server_pcm: + vcpus_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.read.bytes_server_pcm: + memory.resident_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED + disk.write.requests_server_pd_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + feature_server_pcm_0: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED network.outgoing.packets.rate_pcm_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. @@ -322,19 +291,13 @@ node_types: occurrences: - 1 - UNBOUNDED - network.outgoing.bytes_pcm_port_0: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED - disk.device.read.bytes_server_pcm: + disk.ephemeral.size_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.read.bytes_server_pd: + network.outgoing.bytes_pcm_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -351,6 +314,12 @@ node_types: occurrences: - 1 - UNBOUNDED + cpu_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED attachment_pcm_port_0: type: tosca.capabilities.Attachment occurrences: @@ -361,320 +330,345 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.device.read.bytes_server_pd: + disk.write.bytes_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.requests.rate_server_pcm: + disk.read.requests_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - vcpus_server_pcm: + disk.device.usage_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes_server_pcm: + disk.device.read.bytes_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - host_server_pd: + endpoint_server_pcm_0: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + host_server_pcm_0: type: tosca.capabilities.Container valid_source_types: - tosca.nodes.SoftwareComponent occurrences: - 1 - UNBOUNDED - disk.read.bytes.rate_server_pcm: + disk.write.requests.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - vcpus_server_pd: + disk.device.capacity_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.allocation_server_pcm: + disk.root.size_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.ephemeral.size_server_pd: + disk.latency_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests.rate_server_pd: + disk.device.iops_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - scalable_server_pcm: - type: tosca.capabilities.Scalable + disk.write.requests.rate_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu_util_server_pcm: + memory_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests_server_pd: + disk.device.read.bytes.rate_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - host_server_pcm: - type: tosca.capabilities.Container - valid_source_types: - - tosca.nodes.SoftwareComponent + instance_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu.delta_server_pcm: + disk.device.allocation_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - binding_server_pcm: - type: tosca.capabilities.network.Bindable + disk.usage_server_pd_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.write.bytes_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.capacity_server_pcm: + disk.device.read.requests.rate_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - binding_server_pd: + binding_server_pcm_0: type: tosca.capabilities.network.Bindable occurrences: - 1 - UNBOUNDED - disk.device.write.requests.rate_server_pcm: + disk.read.bytes.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.latency_server_pcm: + disk.write.bytes.rate_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.requests_server_pcm: + cpu_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - feature_server_pcm: - type: tosca.capabilities.Node + disk.root.size_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.root.size_server_pd: + vcpus_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.requests.rate_server_pd: + disk.iops_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes.rate_server_pcm: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + endpoint_server_pd_0: + type: tosca.capabilities.Endpoint.Admin occurrences: - 1 - UNBOUNDED - disk.device.write.bytes_server_pd: + disk.device.write.bytes.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu_server_pcm: + disk.device.capacity_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory.resident_server_pd: + disk.device.write.bytes.rate_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests_server_pcm: + disk.write.requests_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu_util_server_pd: + disk.read.bytes_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory.resident_server_pcm: + disk.device.latency_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.requests_server_pcm: + cpu_util_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.usage_server_pd: + disk.device.read.requests.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.usage_server_pcm: + disk.device.write.bytes_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.capacity_server_pd: + disk.allocation_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - endpoint_server_pd: - type: tosca.capabilities.Endpoint.Admin + memory.usage_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.capacity_server_pd: + instance_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.allocation_server_pd: + disk.allocation_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.bytes_server_pcm: + disk.device.read.bytes_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.ephemeral.size_server_pcm: + cpu_util_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.usage_server_pd: + disk.read.bytes.rate_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.capacity_server_pcm: + disk.device.iops_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - os_server_pcm: - type: tosca.capabilities.OperatingSystem + disk.device.write.bytes_server_pd_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - endpoint_server_pcm: - type: tosca.capabilities.Endpoint.Admin + disk.capacity_server_pd_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - instance_server_pd: + disk.device.read.bytes.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.iops_server_pcm: + cpu.delta_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu.delta_server_pd: + memory.resident_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.latency_server_pd: + disk.ephemeral.size_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.bytes.rate_server_pd: + disk.read.requests_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.bytes.rate_server_pcm: + disk.device.write.requests.rate_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests.rate_server_pcm: + disk.device.write.requests_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.bytes.rate_server_pcm: + binding_server_pd_0: + type: tosca.capabilities.network.Bindable + occurrences: + - 1 + - UNBOUNDED + scalable_server_pcm_0: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + disk.device.allocation_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.iops_server_pd: + disk.read.bytes_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.read.requests_server_pd: + disk.device.read.requests_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -692,70 +686,71 @@ node_types: occurrences: - 1 - UNBOUNDED - os_server_pd: - type: tosca.capabilities.OperatingSystem + disk.device.latency_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.latency_server_pd: + disk.device.usage_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outgoing.bytes.rate_pcm_port_0: + disk.latency_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.packets_pcm_port_1: + network.outgoing.bytes.rate_pcm_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - scalable_server_pd: - type: tosca.capabilities.Scalable + memory.usage_server_pd_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - instance_server_pcm: + network.incoming.packets_pcm_port_1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes_server_pd: + disk.device.write.requests_server_pcm_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes.rate_server_pd: + disk.device.write.requests.rate_server_pd_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - feature_server_pd: - type: tosca.capabilities.Node + disk.device.read.requests_server_pcm_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes.rate_pcm_port_0: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + scalable_server_pd_0: + type: tosca.capabilities.Scalable occurrences: - 1 - UNBOUNDED - disk.device.write.requests.rate_server_pd: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + os_server_pcm_0: + type: tosca.capabilities.OperatingSystem occurrences: - 1 - UNBOUNDED - cpu_server_pd: + network.incoming.bytes.rate_pcm_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -766,4 +761,9 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 + - UNBOUNDED + os_server_pd_0: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/MainServiceTemplate.yaml index e51dba5a7c..1dc9eebe59 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/MainServiceTemplate.yaml @@ -144,7 +144,7 @@ topology_template: description: OAM network name default: oam_protected_net_0 node_templates: - server_pcm: + server_pd_1: type: org.openecomp.resource.abstract.nodes.heat.nested-pcm_v0.1 directives: - substitutable @@ -154,7 +154,7 @@ topology_template: oam_net_gw: get_input: oam_net_gw pcm_image_name: - get_input: pcm_image_name + get_input: pd_image_name security_group_name: get_input: security_group_name cps_net_ip: @@ -162,7 +162,7 @@ topology_template: - cps_net_ips - 0 pcm_flavor_name: - get_input: pcm_flavor_name + get_input: pd_flavor_name service_template_filter: substitute_service_template: nested-pcm_v0.1ServiceTemplate.yaml pcm_vol: @@ -171,8 +171,8 @@ topology_template: - 0 pcm_server_name: get_input: - - pcm_server_names - - 0 + - pd_server_names + - 1 cps_net_name: get_input: cps_net_name cps_net_mask: @@ -185,21 +185,7 @@ topology_template: get_input: oam_net_mask oam_net_name: get_input: oam_net_name - compute_port_0: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - properties: - ip_requirements: - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - mac_requirements: - mac_count_required: - is_required: false - network: - get_input: net_name - server_pd: + server_pcm_1: type: org.openecomp.resource.abstract.nodes.heat.nested-pcm_v0.1 directives: - substitutable @@ -209,7 +195,7 @@ topology_template: oam_net_gw: get_input: oam_net_gw pcm_image_name: - get_input: pd_image_name + get_input: pcm_image_name security_group_name: get_input: security_group_name cps_net_ip: @@ -217,7 +203,7 @@ topology_template: - cps_net_ips - 0 pcm_flavor_name: - get_input: pd_flavor_name + get_input: pcm_flavor_name service_template_filter: substitute_service_template: nested-pcm_v0.1ServiceTemplate.yaml pcm_vol: @@ -226,8 +212,8 @@ topology_template: - 0 pcm_server_name: get_input: - - pd_server_names - - 1 + - pcm_server_names + - 0 cps_net_name: get_input: cps_net_name cps_net_mask: @@ -240,6 +226,20 @@ topology_template: get_input: oam_net_mask oam_net_name: get_input: oam_net_name + compute_port_0: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + properties: + ip_requirements: + - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + mac_requirements: + mac_count_required: + is_required: false + network: + get_input: net_name groups: hot-nimbus-pcm_v0.4_group: type: org.openecomp.groups.heat.HeatStack @@ -247,6 +247,6 @@ topology_template: heat_file: ../Artifacts/hot-nimbus-pcm_v0.4.yaml description: heat template that creates PCRF Cluman stack members: - - server_pcm - - compute_port_0 - - server_pd \ No newline at end of file + - server_pd_1 + - server_pcm_1 + - compute_port_0 \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/nested-pcm_v0.1ServiceTemplate.yaml index dce37eb21a..65088158c3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/nestedWithTwoDiffComputeTypes/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -110,19 +110,6 @@ topology_template: type: string description: OAM network name node_templates: - server_pcm: - type: org.openecomp.resource.vfc.nodes.heat.pcm_server - properties: - flavor: - get_input: pcm_flavor_name - availability_zone: - get_input: availabilityzone_name - image: - get_input: pcm_image_name - config_drive: true - user_data_format: RAW - name: - get_input: pcm_server_name pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: @@ -146,9 +133,22 @@ topology_template: requirements: - binding: capability: tosca.capabilities.network.Bindable - node: server_pd + node: server_pd_0 relationship: tosca.relationships.network.BindsTo - server_pd: + server_pcm_0: + type: org.openecomp.resource.vfc.nodes.heat.pcm_server + properties: + flavor: + get_input: pcm_flavor_name + availability_zone: + get_input: availabilityzone_name + image: + get_input: pcm_image_name + config_drive: true + user_data_format: RAW + name: + get_input: pcm_server_name + server_pd_0: type: org.openecomp.resource.vfc.nodes.heat.pd_server properties: flavor: @@ -184,7 +184,7 @@ topology_template: requirements: - binding: capability: tosca.capabilities.network.Bindable - node: server_pcm + node: server_pcm_0 relationship: tosca.relationships.network.BindsTo groups: nested-pcm_v0.1_group: @@ -193,95 +193,80 @@ topology_template: heat_file: ../Artifacts/nested-pcm_v0.1.yaml description: heat template that creates PCRF Cluman stack members: - - server_pcm - pcm_port_1 - - server_pd + - server_pcm_0 + - server_pd_0 - pcm_port_0 outputs: server_pcm_id_2: description: the pcm nova service id - value: server_pd + value: server_pd_0 server_pcm_id_1: description: the pcm nova service id - value: server_pcm + value: server_pcm_0 substitution_mappings: node_type: org.openecomp.resource.abstract.nodes.heat.nested-pcm_v0.1 capabilities: network.incoming.packets.rate_pcm_port_0: - pcm_port_0 - network.incoming.packets.rate - disk.iops_server_pd: - - server_pd + disk.iops_server_pd_0: + - server_pd_0 - disk.iops - disk.device.read.bytes.rate_server_pd: - - server_pd - - disk.device.read.bytes.rate network.incoming.packets.rate_pcm_port_1: - pcm_port_1 - network.incoming.packets.rate - memory_server_pcm: - - server_pcm - - memory network.outpoing.packets_pcm_port_1: - pcm_port_1 - network.outpoing.packets network.outpoing.packets_pcm_port_0: - pcm_port_0 - network.outpoing.packets - disk.device.read.requests_server_pd: - - server_pd - - disk.device.read.requests - disk.device.iops_server_pcm: - - server_pcm - - disk.device.iops - disk.device.allocation_server_pd: - - server_pd - - disk.device.allocation - disk.allocation_server_pcm: - - server_pcm - - disk.allocation - memory.usage_server_pd: - - server_pd - - memory.usage - disk.read.bytes.rate_server_pd: - - server_pd - - disk.read.bytes.rate - disk.usage_server_pcm: - - server_pcm - - disk.usage - disk.root.size_server_pcm: - - server_pcm - - disk.root.size - memory_server_pd: - - server_pd + disk.write.bytes.rate_server_pd_0: + - server_pd_0 + - disk.write.bytes.rate + cpu.delta_server_pd_0: + - server_pd_0 + - cpu.delta + feature_server_pd_0: + - server_pd_0 + - feature + disk.capacity_server_pcm_0: + - server_pcm_0 + - disk.capacity + host_server_pd_0: + - server_pd_0 + - host + memory_server_pd_0: + - server_pd_0 - memory - disk.device.latency_server_pcm: - - server_pcm - - disk.device.latency network.incoming.bytes_pcm_port_0: - pcm_port_0 - network.incoming.bytes - disk.device.write.requests_server_pd: - - server_pd - - disk.device.write.requests network.incoming.bytes_pcm_port_1: - pcm_port_1 - network.incoming.bytes + disk.usage_server_pcm_0: + - server_pcm_0 + - disk.usage binding_pcm_port_0: - pcm_port_0 - binding - memory.usage_server_pcm: - - server_pcm - - memory.usage binding_pcm_port_1: - pcm_port_1 - binding - disk.read.requests_server_pcm: - - server_pcm - - disk.read.requests - disk.read.bytes_server_pcm: - - server_pcm - - disk.read.bytes + vcpus_server_pcm_0: + - server_pcm_0 + - vcpus + memory.resident_server_pcm_0: + - server_pcm_0 + - memory.resident + disk.write.requests_server_pd_0: + - server_pd_0 + - disk.write.requests + feature_server_pcm_0: + - server_pcm_0 + - feature network.outgoing.packets.rate_pcm_port_0: - pcm_port_0 - network.outgoing.packets.rate @@ -291,255 +276,270 @@ topology_template: feature_pcm_port_1: - pcm_port_1 - feature + disk.ephemeral.size_server_pd_0: + - server_pd_0 + - disk.ephemeral.size network.outgoing.bytes_pcm_port_0: - pcm_port_0 - network.outgoing.bytes - disk.device.read.bytes_server_pcm: - - server_pcm - - disk.device.read.bytes - disk.read.bytes_server_pd: - - server_pd - - disk.read.bytes feature_pcm_port_0: - pcm_port_0 - feature network.outgoing.bytes_pcm_port_1: - pcm_port_1 - network.outgoing.bytes + cpu_server_pcm_0: + - server_pcm_0 + - cpu attachment_pcm_port_0: - pcm_port_0 - attachment attachment_pcm_port_1: - pcm_port_1 - attachment - disk.device.read.bytes_server_pd: - - server_pd - - disk.device.read.bytes - disk.device.read.requests.rate_server_pcm: - - server_pcm - - disk.device.read.requests.rate - vcpus_server_pcm: - - server_pcm - - vcpus - disk.write.bytes_server_pcm: - - server_pcm + disk.write.bytes_server_pd_0: + - server_pd_0 - disk.write.bytes - host_server_pd: - - server_pd + disk.read.requests_server_pd_0: + - server_pd_0 + - disk.read.requests + disk.device.usage_server_pd_0: + - server_pd_0 + - disk.device.usage + disk.device.read.bytes_server_pd_0: + - server_pd_0 + - disk.device.read.bytes + endpoint_server_pcm_0: + - server_pcm_0 + - endpoint + host_server_pcm_0: + - server_pcm_0 - host - disk.read.bytes.rate_server_pcm: - - server_pcm - - disk.read.bytes.rate - vcpus_server_pd: - - server_pd - - vcpus - disk.device.allocation_server_pcm: - - server_pcm - - disk.device.allocation - disk.ephemeral.size_server_pd: - - server_pd - - disk.ephemeral.size - disk.write.requests.rate_server_pd: - - server_pd + disk.write.requests.rate_server_pd_0: + - server_pd_0 - disk.write.requests.rate - scalable_server_pcm: - - server_pcm - - scalable - cpu_util_server_pcm: - - server_pcm - - cpu_util - disk.write.requests_server_pd: - - server_pd - - disk.write.requests - host_server_pcm: - - server_pcm - - host - cpu.delta_server_pcm: - - server_pcm - - cpu.delta - binding_server_pcm: - - server_pcm - - binding - disk.device.capacity_server_pcm: - - server_pcm + disk.device.capacity_server_pcm_0: + - server_pcm_0 - disk.device.capacity - binding_server_pd: - - server_pd - - binding - disk.device.write.requests.rate_server_pcm: - - server_pcm - - disk.device.write.requests.rate - disk.latency_server_pcm: - - server_pcm - - disk.latency - disk.device.read.requests_server_pcm: - - server_pcm - - disk.device.read.requests - feature_server_pcm: - - server_pcm - - feature - disk.root.size_server_pd: - - server_pd + disk.root.size_server_pd_0: + - server_pd_0 - disk.root.size - disk.device.read.requests.rate_server_pd: - - server_pd + disk.latency_server_pcm_0: + - server_pcm_0 + - disk.latency + disk.device.iops_server_pd_0: + - server_pd_0 + - disk.device.iops + disk.write.requests.rate_server_pcm_0: + - server_pcm_0 + - disk.write.requests.rate + memory_server_pcm_0: + - server_pcm_0 + - memory + disk.device.read.bytes.rate_server_pcm_0: + - server_pcm_0 + - disk.device.read.bytes.rate + instance_server_pcm_0: + - server_pcm_0 + - instance + disk.device.allocation_server_pcm_0: + - server_pcm_0 + - disk.device.allocation + disk.usage_server_pd_0: + - server_pd_0 + - disk.usage + disk.write.bytes_server_pcm_0: + - server_pcm_0 + - disk.write.bytes + disk.device.read.requests.rate_server_pcm_0: + - server_pcm_0 - disk.device.read.requests.rate - disk.write.bytes.rate_server_pcm: - - server_pcm + binding_server_pcm_0: + - server_pcm_0 + - binding + disk.read.bytes.rate_server_pd_0: + - server_pd_0 + - disk.read.bytes.rate + disk.write.bytes.rate_server_pcm_0: + - server_pcm_0 - disk.write.bytes.rate - disk.device.write.bytes_server_pd: - - server_pd - - disk.device.write.bytes - cpu_server_pcm: - - server_pcm + cpu_server_pd_0: + - server_pd_0 - cpu - memory.resident_server_pd: - - server_pd - - memory.resident - disk.write.requests_server_pcm: - - server_pcm - - disk.write.requests - cpu_util_server_pd: - - server_pd - - cpu_util - memory.resident_server_pcm: - - server_pcm - - memory.resident - disk.device.write.requests_server_pcm: - - server_pcm - - disk.device.write.requests - disk.usage_server_pd: - - server_pd - - disk.usage - disk.device.usage_server_pcm: - - server_pcm - - disk.device.usage - disk.capacity_server_pd: - - server_pd - - disk.capacity - endpoint_server_pd: - - server_pd + disk.root.size_server_pcm_0: + - server_pcm_0 + - disk.root.size + vcpus_server_pd_0: + - server_pd_0 + - vcpus + disk.iops_server_pcm_0: + - server_pcm_0 + - disk.iops + endpoint_server_pd_0: + - server_pd_0 - endpoint - disk.device.capacity_server_pd: - - server_pd + disk.device.write.bytes.rate_server_pd_0: + - server_pd_0 + - disk.device.write.bytes.rate + disk.device.capacity_server_pd_0: + - server_pd_0 - disk.device.capacity - disk.allocation_server_pd: - - server_pd + disk.device.write.bytes.rate_server_pcm_0: + - server_pcm_0 + - disk.device.write.bytes.rate + disk.write.requests_server_pcm_0: + - server_pcm_0 + - disk.write.requests + disk.read.bytes_server_pcm_0: + - server_pcm_0 + - disk.read.bytes + disk.device.latency_server_pd_0: + - server_pd_0 + - disk.device.latency + cpu_util_server_pcm_0: + - server_pcm_0 + - cpu_util + disk.device.read.requests.rate_server_pd_0: + - server_pd_0 + - disk.device.read.requests.rate + disk.device.write.bytes_server_pcm_0: + - server_pcm_0 + - disk.device.write.bytes + disk.allocation_server_pcm_0: + - server_pcm_0 - disk.allocation - disk.device.write.bytes_server_pcm: - - server_pcm + memory.usage_server_pcm_0: + - server_pcm_0 + - memory.usage + instance_server_pd_0: + - server_pd_0 + - instance + disk.allocation_server_pd_0: + - server_pd_0 + - disk.allocation + disk.device.read.bytes_server_pcm_0: + - server_pcm_0 + - disk.device.read.bytes + cpu_util_server_pd_0: + - server_pd_0 + - cpu_util + disk.read.bytes.rate_server_pcm_0: + - server_pcm_0 + - disk.read.bytes.rate + disk.device.iops_server_pcm_0: + - server_pcm_0 + - disk.device.iops + disk.device.write.bytes_server_pd_0: + - server_pd_0 - disk.device.write.bytes - disk.ephemeral.size_server_pcm: - - server_pcm - - disk.ephemeral.size - disk.device.usage_server_pd: - - server_pd - - disk.device.usage - disk.capacity_server_pcm: - - server_pcm + disk.capacity_server_pd_0: + - server_pd_0 - disk.capacity - os_server_pcm: - - server_pcm - - os - endpoint_server_pcm: - - server_pcm - - endpoint - instance_server_pd: - - server_pd - - instance - disk.iops_server_pcm: - - server_pcm - - disk.iops - cpu.delta_server_pd: - - server_pd - - cpu.delta - disk.latency_server_pd: - - server_pd - - disk.latency - disk.device.write.bytes.rate_server_pd: - - server_pd - - disk.device.write.bytes.rate - disk.device.read.bytes.rate_server_pcm: - - server_pcm + disk.device.read.bytes.rate_server_pd_0: + - server_pd_0 - disk.device.read.bytes.rate - disk.write.requests.rate_server_pcm: - - server_pcm - - disk.write.requests.rate - disk.device.write.bytes.rate_server_pcm: - - server_pcm - - disk.device.write.bytes.rate - disk.device.iops_server_pd: - - server_pd - - disk.device.iops - disk.read.requests_server_pd: - - server_pd + cpu.delta_server_pcm_0: + - server_pcm_0 + - cpu.delta + memory.resident_server_pd_0: + - server_pd_0 + - memory.resident + disk.ephemeral.size_server_pcm_0: + - server_pcm_0 + - disk.ephemeral.size + disk.read.requests_server_pcm_0: + - server_pcm_0 - disk.read.requests + disk.device.write.requests.rate_server_pcm_0: + - server_pcm_0 + - disk.device.write.requests.rate + disk.device.write.requests_server_pd_0: + - server_pd_0 + - disk.device.write.requests + binding_server_pd_0: + - server_pd_0 + - binding + scalable_server_pcm_0: + - server_pcm_0 + - scalable + disk.device.allocation_server_pd_0: + - server_pd_0 + - disk.device.allocation + disk.read.bytes_server_pd_0: + - server_pd_0 + - disk.read.bytes + disk.device.read.requests_server_pd_0: + - server_pd_0 + - disk.device.read.requests network.outgoing.bytes.rate_pcm_port_1: - pcm_port_1 - network.outgoing.bytes.rate network.incoming.packets_pcm_port_0: - pcm_port_0 - network.incoming.packets - os_server_pd: - - server_pd - - os - disk.device.latency_server_pd: - - server_pd + disk.device.latency_server_pcm_0: + - server_pcm_0 - disk.device.latency + disk.device.usage_server_pcm_0: + - server_pcm_0 + - disk.device.usage + disk.latency_server_pd_0: + - server_pd_0 + - disk.latency network.outgoing.bytes.rate_pcm_port_0: - pcm_port_0 - network.outgoing.bytes.rate + memory.usage_server_pd_0: + - server_pd_0 + - memory.usage network.incoming.packets_pcm_port_1: - pcm_port_1 - network.incoming.packets - scalable_server_pd: - - server_pd + disk.device.write.requests_server_pcm_0: + - server_pcm_0 + - disk.device.write.requests + disk.device.write.requests.rate_server_pd_0: + - server_pd_0 + - disk.device.write.requests.rate + disk.device.read.requests_server_pcm_0: + - server_pcm_0 + - disk.device.read.requests + scalable_server_pd_0: + - server_pd_0 - scalable - instance_server_pcm: - - server_pcm - - instance - disk.write.bytes_server_pd: - - server_pd - - disk.write.bytes - disk.write.bytes.rate_server_pd: - - server_pd - - disk.write.bytes.rate - feature_server_pd: - - server_pd - - feature + os_server_pcm_0: + - server_pcm_0 + - os network.incoming.bytes.rate_pcm_port_0: - pcm_port_0 - network.incoming.bytes.rate - disk.device.write.requests.rate_server_pd: - - server_pd - - disk.device.write.requests.rate - cpu_server_pd: - - server_pd - - cpu network.incoming.bytes.rate_pcm_port_1: - pcm_port_1 - network.incoming.bytes.rate + os_server_pd_0: + - server_pd_0 + - os requirements: + dependency_server_pcm_0: + - server_pcm_0 + - dependency + local_storage_server_pcm_0: + - server_pcm_0 + - local_storage link_pcm_port_0: - pcm_port_0 - link link_pcm_port_1: - pcm_port_1 - link - local_storage_server_pd: - - server_pd - - local_storage - dependency_server_pd: - - server_pd - - dependency - local_storage_server_pcm: - - server_pcm - - local_storage dependency_pcm_port_0: - pcm_port_0 - dependency - dependency_server_pcm: - - server_pcm + local_storage_server_pd_0: + - server_pd_0 + - local_storage + dependency_server_pd_0: + - server_pd_0 - dependency dependency_pcm_port_1: - pcm_port_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml index 18acb4f442..de3481367e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -18,6 +24,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -33,11 +45,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -68,11 +104,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string @@ -495,6 +555,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -505,6 +571,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -520,11 +592,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -555,11 +651,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string @@ -982,6 +1102,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -992,6 +1118,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -1007,11 +1139,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -1042,11 +1198,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml index 1ab6da631d..1a50030cb0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml index a5e41ea4fa..e75b827856 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.2ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.3ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.3ServiceTemplate.yaml index 9002b35770..4803278efc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.3ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedPointingToThreeDiffNestedFilesSameComputeType/out/nested-pcm_v0.3ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -377,4 +467,4 @@ topology_template: - dependency dependency_pcm_port_1: - pcm_port_1 - - dependency + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/GlobalSubstitutionTypesServiceTemplate.yaml index daaf03d55e..fe6e819385 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -18,6 +24,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -33,11 +45,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -68,11 +104,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string @@ -495,6 +555,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -505,6 +571,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -520,11 +592,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -555,11 +651,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.1ServiceTemplate.yaml index 05a21ce6d1..51429041fe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.2ServiceTemplate.yaml index a788426a41..bae5cf0d08 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/threeNestedSameTypeTwoPointingOnSameNestedFile/out/nested-pcm_v0.2ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml index 14d9ffa1f4..b9bd9b6cf8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,12 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name @@ -18,6 +24,12 @@ node_types: description: CPS network gateway required: true status: SUPPORTED + port_pcm_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -33,11 +45,35 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string pcm_vol: type: string description: CPS Cluman Cinder Volume @@ -68,11 +104,35 @@ node_types: description: CPS network mask required: true status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json oam_net_name: type: string description: OAM network name required: true status: SUPPORTED + port_pcm_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string attributes: server_pcm_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml index 05a21ce6d1..51429041fe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/nestedSingleCompute/twoNestedNodeTemplatesWithSameComputeType/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,6 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false @@ -23,6 +28,11 @@ topology_template: immutable: false type: string description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -41,12 +51,32 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false immutable: false type: string description: flavor name of PCRF CM instance + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string pcm_vol: label: CPS Cluman Cinder Volume hidden: false @@ -83,12 +113,32 @@ topology_template: immutable: false type: string description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json oam_net_name: label: OAM network name hidden: false immutable: false type: string description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -101,15 +151,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -139,15 +209,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml index f3b983e920..c91ab33909 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/MainServiceTemplate.yaml index 7997fe0a81..cb58589bfe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/MainServiceTemplate.yaml @@ -46,6 +46,21 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO_PORT_1 + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -67,21 +82,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO_PORT_1 - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - RAW_SERVER_PD_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/Nested_pd_serverServiceTemplate.yaml index 45fd36f894..ce1fbac923 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePort/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,18 +112,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 2080edef46..e073c59ae5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/MainServiceTemplate.yaml index c87498fa1d..3f3be668d3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/MainServiceTemplate.yaml @@ -60,6 +60,21 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO_PORT_1 + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -81,21 +96,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO_PORT_1 - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - RAW_SERVER_PD_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml index 9923db380e..34003c6f29 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,18 +112,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/GlobalSubstitutionTypesServiceTemplate.yaml index 84dba74e5c..71c1bf5986 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/MainServiceTemplate.yaml index b31071fa0a..a5a1489254 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/MainServiceTemplate.yaml @@ -53,6 +53,23 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - get_attribute: + - network_policy_server + - name + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -74,23 +91,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - get_attribute: - - network_policy_server - - name - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - get_attribute: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/Nested_pd_serverServiceTemplate.yaml index c588df7d89..a4bb6fb890 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOut/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -91,18 +121,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/GlobalSubstitutionTypesServiceTemplate.yaml index 36bd7af7d6..18abf27241 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,30 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json requirements: - dependency_pd_server: capability: tosca.capabilities.Node diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/MainServiceTemplate.yaml index bd65262adb..baffa1f9d1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/MainServiceTemplate.yaml @@ -46,6 +46,18 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -67,18 +79,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_input: pd_flavor_name service_template_filter: substitute_service_template: Nested_pd_serverServiceTemplate.yaml count: 2 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/Nested_pd_serverServiceTemplate.yaml index 1ebbdaa7f0..72af3bb88c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortGetAttrOutComputePort/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json node_templates: pd_server: type: org.openecomp.resource.vfc.nodes.heat.pd_server @@ -72,18 +102,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_attribute: - pd_server - accessIPv4 + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 1acef555cb..d594580a18 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,48 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_pd01_port_security_groups: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_mac_requirements: type: list required: true @@ -30,37 +72,31 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list required: true status: SUPPORTED - port_pd01_port_security_groups: + entry_schema: + type: string + port_pd01_port_vlan_requirements: type: list required: true status: SUPPORTED diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/MainServiceTemplate.yaml index ae7dd92592..8984db0da7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/MainServiceTemplate.yaml @@ -67,6 +67,24 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO_PORT_1 + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name + port_pd01_port_security_groups: + - - jsa_security_group + - - jsa_security_group port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -88,24 +106,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO_PORT_1 - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name - port_pd01_port_security_groups: - - - jsa_security_group - - - jsa_security_group compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - RAW_SERVER_PD_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml index a71e2c4593..9aa0aa9eb3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,41 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_pd01_port_security_groups: + type: list + required: true + entry_schema: + type: json port_pd01_port_mac_requirements: type: list required: true @@ -29,32 +64,27 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list required: true - port_pd01_port_security_groups: + entry_schema: + type: string + port_pd01_port_vlan_requirements: type: list required: true entry_schema: @@ -91,18 +121,42 @@ topology_template: get_input: - port_pd01_port_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml index f3b983e920..c91ab33909 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/MainServiceTemplate.yaml index 4ef370388a..8501ed37c2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/MainServiceTemplate.yaml @@ -75,6 +75,21 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO_PORT_1 + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -96,21 +111,6 @@ topology_template: port_pd01_port_network: - packet_mirror_network - packet_mirror_network - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO_PORT_1 - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - RAW_SERVER_PD_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml index 45fd36f894..ce1fbac923 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,18 +112,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml index 96d645f0e2..27d88f15be 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,13 +8,49 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_pd01_port_mac_requirements: + compute_pd_server_scheduler_hints: type: list required: true status: SUPPORTED entry_schema: type: json - compute_pd_server_scheduler_hints: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_pd01_port_mac_requirements: type: list required: true status: SUPPORTED @@ -36,36 +72,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/MainServiceTemplate.yaml index baf0b4a3b2..d12bf29530 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/MainServiceTemplate.yaml @@ -46,14 +46,29 @@ topology_template: directives: - substitutable properties: + compute_pd_server_scheduler_hints: + - group: BE_Affinity_group + - group: BE_Affinity_group + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO_PORT_1 + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false - mac_count_required: is_required: false - compute_pd_server_scheduler_hints: - - group: BE_Affinity_group - - group: BE_Affinity_group vm_image_name: get_input: pd_image_name port_pd01_port_ip_requirements: @@ -70,21 +85,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO_PORT_1 - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - RAW_SERVER_PD_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/Nested_pd_serverServiceTemplate.yaml index 0d1df3e26b..16c6ed13a1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOneGroup/out/Nested_pd_serverServiceTemplate.yaml @@ -11,12 +11,42 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_pd01_port_mac_requirements: + compute_pd_server_scheduler_hints: type: list required: true entry_schema: type: json - compute_pd_server_scheduler_hints: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_pd01_port_mac_requirements: type: list required: true entry_schema: @@ -34,31 +64,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -91,18 +121,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index cf7b8e5315..8e7dc7ab42 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/MainServiceTemplate.yaml index 38f0073e5d..d1b8f72259 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/MainServiceTemplate.yaml @@ -46,6 +46,21 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO_PORT_1 + - AUTO_PORT_0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -67,21 +82,6 @@ topology_template: port_pd01_port_network: - Network-1 - Network-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO_PORT_1 - - AUTO_PORT_0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW_SERVER_PD_2 - RAW_SERVER_PD_1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml index f49877e3d1..b358a96558 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/oneComputeTypeOnePortOutputParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,18 +112,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml index cf85c2d08a..102842abb6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -411,10 +447,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -435,6 +473,32 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_ps01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_ps01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + vm_image_name: + type: string + required: true + status: SUPPORTED + port_ps01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_ps01_port_replacement_policy: type: list required: true @@ -453,11 +517,19 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_ps01_port_ip_requirements: + type: list required: true status: SUPPORTED - port_ps01_port_ip_requirements: + entry_schema: + type: json + port_ps01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_ps01_port_exCP_naming: type: list required: true status: SUPPORTED diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/MainServiceTemplate.yaml index a1c581355c..661adcc7e4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/MainServiceTemplate.yaml @@ -73,6 +73,21 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO + - AUTO + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -94,21 +109,6 @@ topology_template: port_pd01_port_network: - Network-PD-1 - Network-PD-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO - - AUTO - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - null - RAW @@ -132,14 +132,16 @@ topology_template: - get_input: - ps_server_names - 1 - vm_image_name: - get_input: ps_image_name compute_ps_server_availability_zone: - get_input: availabilityzone_name - get_input: availabilityzone_name compute_ps_server_user_data_format: - null - RAW + vm_flavor_name: + get_input: ps_flavor_name + vm_image_name: + get_input: ps_image_name port_ps01_port_replacement_policy: - AUTO - AUTO @@ -151,8 +153,6 @@ topology_template: port_ps01_port_network: - Network-PS-0 - Network-PS-1 - vm_flavor_name: - get_input: ps_flavor_name port_ps01_port_ip_requirements: - - ip_version: 4 ip_count_required: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_pd_serverServiceTemplate.yaml index 45fd36f894..ce1fbac923 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,18 +112,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_ps_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_ps_serverServiceTemplate.yaml index 3de2a46d80..87e999cf79 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_ps_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePort/out/Nested_ps_serverServiceTemplate.yaml @@ -16,9 +16,11 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -36,6 +38,27 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_ps01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_ps01_port_order: + type: list + required: true + entry_schema: + type: integer + vm_image_name: + type: string + required: true + port_ps01_port_network_role: + type: list + required: true + entry_schema: + type: string port_ps01_port_replacement_policy: type: list required: true @@ -51,14 +74,21 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true port_ps01_port_ip_requirements: type: list required: true entry_schema: type: json + port_ps01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_ps01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json node_templates: ps_server: type: org.openecomp.resource.vfc.nodes.heat.ps_server @@ -82,18 +112,42 @@ topology_template: ps_server_ps01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_ps01_port_exCP_naming + - index_value replacement_policy: get_input: - port_ps01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_ps01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_ps01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_ps01_port_network_role_tag + - index_value mac_requirements: get_input: - port_ps01_port_mac_requirements - index_value + order: + get_input: + - port_ps01_port_order + - index_value + network_role: + get_input: + - port_ps01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_ps01_port_subnetpoolid + - index_value network: get_input: - port_ps01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/GlobalSubstitutionTypesServiceTemplate.yaml index c814e074c2..762c7c10c4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,42 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +66,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -417,10 +453,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -441,6 +479,32 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_ps01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_ps01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + vm_image_name: + type: string + required: true + status: SUPPORTED + port_ps01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_ps01_port_replacement_policy: type: list required: true @@ -459,11 +523,19 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_ps01_port_ip_requirements: + type: list required: true status: SUPPORTED - port_ps01_port_ip_requirements: + entry_schema: + type: json + port_ps01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_ps01_port_exCP_naming: type: list required: true status: SUPPORTED diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/MainServiceTemplate.yaml index 871efb849a..2174bb769f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/MainServiceTemplate.yaml @@ -73,6 +73,21 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + - get_input: + - pd_server_names + - 0 + port_pd01_port_replacement_policy: + - AUTO + - AUTO + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -94,21 +109,6 @@ topology_template: port_pd01_port_network: - Network-PD-1 - Network-PD-0 - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - - get_input: - - pd_server_names - - 0 - port_pd01_port_replacement_policy: - - AUTO - - AUTO - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - null - get_attribute: @@ -134,8 +134,6 @@ topology_template: - get_input: - ps_server_names - 1 - vm_image_name: - get_input: ps_image_name compute_ps_server_availability_zone: - get_input: availabilityzone_name - get_input: availabilityzone_name @@ -144,6 +142,10 @@ topology_template: - abstract_pd_server - pd_server_accessIPv4 - null + vm_flavor_name: + get_input: ps_flavor_name + vm_image_name: + get_input: ps_image_name port_ps01_port_replacement_policy: - AUTO - AUTO @@ -155,8 +157,6 @@ topology_template: port_ps01_port_network: - Network-PS-0 - Network-PS-1 - vm_flavor_name: - get_input: ps_flavor_name port_ps01_port_ip_requirements: - - ip_version: 4 ip_count_required: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_pd_serverServiceTemplate.yaml index dc5f1e5474..a03be48f50 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,36 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +59,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_replacement_policy: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,18 +112,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_ps_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_ps_serverServiceTemplate.yaml index be9be2ceb6..f65ddfa0ca 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_ps_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/scalingInstances/twoComputeTypesOnePortWithGetAttr/out/Nested_ps_serverServiceTemplate.yaml @@ -16,9 +16,11 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -36,6 +38,27 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_ps01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_ps01_port_order: + type: list + required: true + entry_schema: + type: integer + vm_image_name: + type: string + required: true + port_ps01_port_network_role: + type: list + required: true + entry_schema: + type: string port_ps01_port_replacement_policy: type: list required: true @@ -51,14 +74,21 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true port_ps01_port_ip_requirements: type: list required: true entry_schema: type: json + port_ps01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_ps01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json node_templates: ps_server: type: org.openecomp.resource.vfc.nodes.heat.ps_server @@ -82,18 +112,42 @@ topology_template: ps_server_ps01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_ps01_port_exCP_naming + - index_value replacement_policy: get_input: - port_ps01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_ps01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_ps01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_ps01_port_network_role_tag + - index_value mac_requirements: get_input: - port_ps01_port_mac_requirements - index_value + order: + get_input: + - port_ps01_port_order + - index_value + network_role: + get_input: + - port_ps01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_ps01_port_subnetpoolid + - index_value network: get_input: - port_ps01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml index 73f2c6fad8..b003fc2638 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -34,10 +34,28 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_flavor_name: type: string required: true status: SUPPORTED + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -50,6 +68,12 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_image_name: type: string required: true @@ -66,6 +90,36 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -78,6 +132,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd02_port_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/Nested_pd_serverServiceTemplate.yaml index e9da306669..6d0690a78d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortType/out/Nested_pd_serverServiceTemplate.yaml @@ -33,9 +33,24 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json vm_flavor_name: type: string required: true + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -46,6 +61,11 @@ topology_template: required: true entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json vm_image_name: type: string required: true @@ -59,6 +79,31 @@ topology_template: required: true entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -69,6 +114,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd02_port_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd02_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml index 33a9362697..cad5199137 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,29 +8,25 @@ node_types: org.openecomp.resource.abstract.nodes.smp: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_port_ip_requirements: + port_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_port_mac_requirements: + port_port_network: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_port_network: + type: string + compute_smp_name: type: list required: true status: SUPPORTED entry_schema: type: string - compute_smp_name: + port_port_subnetpoolid: type: list required: true status: SUPPORTED @@ -50,28 +46,68 @@ node_types: status: SUPPORTED entry_schema: type: string + port_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_flavor_name: type: string required: true status: SUPPORTED - compute_smp_metadata: + compute_smp_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - compute_smp_user_data_format: + port_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + compute_smp_metadata: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_port_replacement_policy: type: list required: true status: SUPPORTED entry_schema: type: string + port_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer compute_smp_scheduler_hints: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/MainServiceTemplate.yaml index 9a471a91a9..6b57e2663d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/MainServiceTemplate.yaml @@ -55,17 +55,9 @@ topology_template: directives: - substitutable properties: - port_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false port_port_mac_requirements: - mac_count_required: is_required: false - vm_image_name: - get_input: image_smp_name port_port_network: - get_input: port_name compute_smp_name: @@ -74,14 +66,22 @@ topology_template: - get_input: availability_zone_0 vm_flavor_name: get_input: flavor_smp_name + compute_smp_user_data_format: + - RAW + port_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: image_smp_name compute_smp_metadata: - jx_vm_role: smp2 vnf_id: get_input: vnf_id jx_lab_name: get_input: lab_name - compute_smp_user_data_format: - - RAW port_port_replacement_policy: - AUTO compute_smp_scheduler_hints: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/Nested_smpServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/Nested_smpServiceTemplate.yaml index 79e0b10db2..77117043d6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/Nested_smpServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeAndServerGroup/out/Nested_smpServiceTemplate.yaml @@ -11,19 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_port_ip_requirements: - type: list - required: true - entry_schema: - type: json port_port_mac_requirements: type: list required: true entry_schema: type: json - vm_image_name: - type: string - required: true port_port_network: type: list required: true @@ -34,6 +26,11 @@ topology_template: required: true entry_schema: type: string + port_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string index_value: type: integer description: Index value of this substitution service template runtime instance @@ -46,24 +43,57 @@ topology_template: required: true entry_schema: type: string + port_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_port_network_role_tag: + type: list + required: true + entry_schema: + type: string vm_flavor_name: type: string required: true - compute_smp_metadata: + compute_smp_user_data_format: + type: list + required: true + entry_schema: + type: string + port_port_ip_requirements: type: list required: true entry_schema: type: json - compute_smp_user_data_format: + port_port_network_role: type: list required: true entry_schema: type: string + vm_image_name: + type: string + required: true + compute_smp_metadata: + type: list + required: true + entry_schema: + type: json + port_port_exCP_naming: + type: list + required: true + entry_schema: + type: json port_port_replacement_policy: type: list required: true entry_schema: type: string + port_port_order: + type: list + required: true + entry_schema: + type: integer compute_smp_scheduler_hints: type: list required: true @@ -73,18 +103,42 @@ topology_template: smp_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_port_exCP_naming + - index_value replacement_policy: get_input: - port_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_port_vlan_requirements + - index_value ip_requirements: get_input: - port_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_port_network_role_tag + - index_value mac_requirements: get_input: - port_port_mac_requirements - index_value + order: + get_input: + - port_port_order + - index_value + network_role: + get_input: + - port_port_network_role + - index_value + subnetpoolid: + get_input: + - port_port_subnetpoolid + - index_value network: get_input: - port_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index b6c7aa061c..2adc34400a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,14 +8,6 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 compute_pd_server_availability_zone: type: list required: true @@ -34,12 +26,6 @@ node_types: status: SUPPORTED entry_schema: type: string - port_pd02_port_mac_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json vm_flavor_name: type: string required: true @@ -66,19 +52,75 @@ node_types: type: string required: true status: SUPPORTED - port_pd02_port_security_groups: + port_pd02_port_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_pd02_port_replacement_policy: + port_pd02_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_ip_requirements: + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_pd_server_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd02_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd02_port_security_groups: type: list required: true status: SUPPORTED @@ -90,25 +132,43 @@ node_types: status: SUPPORTED entry_schema: type: string - port_pd02_port_ip_requirements: + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json - port_pd01_port_network_role_tag: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd02_port_network: + port_pd02_port_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_user_data_format: + port_pd02_port_network: type: list required: true status: SUPPORTED diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/MainServiceTemplate.yaml index ea3d41d97c..751466605b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/MainServiceTemplate.yaml @@ -104,9 +104,6 @@ topology_template: - 0 port_pd01_port_replacement_policy: - AUTO - port_pd02_port_mac_requirements: - - mac_count_required: - is_required: false vm_flavor_name: get_input: pd_flavor_name port_pd01_port_security_groups: @@ -118,8 +115,6 @@ topology_template: is_required: false vm_image_name: get_input: pd_image_name - port_pd02_port_security_groups: - - - jsa_security_group port_pd02_port_replacement_policy: - AUTO port_pd01_port_ip_requirements: @@ -128,6 +123,13 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + compute_pd_server_user_data_format: + - RAW + port_pd02_port_mac_requirements: + - mac_count_required: + is_required: false + port_pd02_port_security_groups: + - - jsa_security_group port_pd01_port_network: - get_input: oam_net_name port_pd02_port_ip_requirements: @@ -140,8 +142,6 @@ topology_template: - oam port_pd02_port_network: - get_input: oam_net_name - compute_pd_server_user_data_format: - - RAW service_template_filter: substitute_service_template: Nested_pd_serverServiceTemplate.yaml count: 1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml index cefeecf3ff..159644651b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml @@ -11,13 +11,6 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 compute_pd_server_availability_zone: type: list required: true @@ -33,11 +26,6 @@ topology_template: required: true entry_schema: type: string - port_pd02_port_mac_requirements: - type: list - required: true - entry_schema: - type: json vm_flavor_name: type: string required: true @@ -59,17 +47,64 @@ topology_template: vm_image_name: type: string required: true - port_pd02_port_security_groups: + port_pd02_port_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_ip_requirements: type: list required: true entry_schema: type: json - port_pd02_port_replacement_policy: + port_pd02_port_network_role: type: list required: true entry_schema: type: string - port_pd01_port_ip_requirements: + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + compute_pd_server_user_data_format: + type: list + required: true + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd02_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd02_port_security_groups: type: list required: true entry_schema: @@ -79,22 +114,37 @@ topology_template: required: true entry_schema: type: string - port_pd02_port_ip_requirements: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: type: list required: true entry_schema: type: json - port_pd01_port_network_role_tag: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - port_pd02_port_network: + port_pd02_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - compute_pd_server_user_data_format: + port_pd02_port_network: type: list required: true entry_schema: @@ -126,10 +176,18 @@ topology_template: get_input: - port_pd01_port_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -142,6 +200,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -158,10 +228,18 @@ topology_template: get_input: - port_pd02_port_security_groups - index_value + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd02_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements @@ -174,6 +252,18 @@ topology_template: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml index c2a86696e4..d18921cdfa 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,14 +8,6 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 compute_pd_server_availability_zone: type: list required: true @@ -34,16 +26,16 @@ node_types: status: SUPPORTED entry_schema: type: string - port_pd02_port_mac_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json vm_flavor_name: type: string required: true status: SUPPORTED + port_pd02_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_mac_requirements: type: list required: true @@ -66,25 +58,105 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd02_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_pd_server_user_data_format: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd02_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_network: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_pd02_port_network: + port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_user_data_format: + port_pd02_port_network: type: list required: true status: SUPPORTED diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/MainServiceTemplate.yaml index 8bc75d63cf..1e714f26c2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/MainServiceTemplate.yaml @@ -100,9 +100,6 @@ topology_template: - 0 port_pd01_port_replacement_policy: - AUTO - port_pd02_port_mac_requirements: - - mac_count_required: - is_required: false vm_flavor_name: get_input: pd_flavor_name port_pd01_port_mac_requirements: @@ -118,6 +115,11 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + compute_pd_server_user_data_format: + - RAW + port_pd02_port_mac_requirements: + - mac_count_required: + is_required: false port_pd01_port_network: - packet_mirror_network port_pd02_port_ip_requirements: @@ -128,8 +130,6 @@ topology_template: is_required: false port_pd02_port_network: - packet_mirror_network - compute_pd_server_user_data_format: - - RAW service_template_filter: substitute_service_template: Nested_pd_serverServiceTemplate.yaml count: 1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml index 9d86566e4f..64104dc20f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithDiffPortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml @@ -11,13 +11,6 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 compute_pd_server_availability_zone: type: list required: true @@ -33,14 +26,14 @@ topology_template: required: true entry_schema: type: string - port_pd02_port_mac_requirements: - type: list - required: true - entry_schema: - type: json vm_flavor_name: type: string required: true + port_pd02_port_network_role_tag: + type: list + required: true + entry_schema: + type: string port_pd01_port_mac_requirements: type: list required: true @@ -59,22 +52,89 @@ topology_template: required: true entry_schema: type: json + port_pd02_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + compute_pd_server_user_data_format: + type: list + required: true + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd02_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_network: type: list required: true entry_schema: type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true entry_schema: type: json - port_pd02_port_network: + port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string - compute_pd_server_user_data_format: + port_pd02_port_network: type: list required: true entry_schema: @@ -102,18 +162,42 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -126,18 +210,42 @@ topology_template: pd_server_pd02_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value replacement_policy: get_input: - port_pd02_port_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd02_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index cd7b7cd904..b956d579e3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -32,26 +32,12 @@ node_types: status: SUPPORTED entry_schema: type: json - port_pd01_port_0_network_role_tag: + port_pd01_port_0_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_1_ip_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 compute_pd_server_availability_zone: type: list required: true @@ -74,23 +60,35 @@ node_types: type: string required: true status: SUPPORTED - port_pd01_port_1_mac_requirements: + port_pd01_port_1_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string + port_pd01_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED - port_pd01_port_1_replacement_policy: + port_pd01_port_1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_pd01_port_1_network_role_tag: + port_pd01_port_0_subnetpoolid: type: list required: true status: SUPPORTED @@ -108,6 +106,68 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_0_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd01_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_0_security_groups: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/MainServiceTemplate.yaml index 215f5c0b83..7c295f9e48 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/MainServiceTemplate.yaml @@ -109,14 +109,6 @@ topology_template: is_required: false port_pd01_port_1_security_groups: - - jsa_security_group - port_pd01_port_0_network_role_tag: - - oam - port_pd01_port_1_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false compute_pd_server_availability_zone: - get_input: availabilityzone_name compute_pd_server_name: @@ -127,19 +119,27 @@ topology_template: - AUTO vm_flavor_name: get_input: pd_flavor_name - port_pd01_port_1_mac_requirements: - - mac_count_required: - is_required: false vm_image_name: get_input: pd_image_name - port_pd01_port_1_replacement_policy: - - AUTO port_pd01_port_1_network_role_tag: - oam port_pd01_port_1_network: - get_input: oam_net_name compute_pd_server_user_data_format: - RAW + port_pd01_port_0_network_role_tag: + - oam + port_pd01_port_1_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + port_pd01_port_1_mac_requirements: + - mac_count_required: + is_required: false + port_pd01_port_1_replacement_policy: + - AUTO port_pd01_port_0_security_groups: - - jsa_security_group service_template_filter: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml index cc1724133c..75533f5049 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedIn/out/Nested_pd_serverServiceTemplate.yaml @@ -31,23 +31,11 @@ topology_template: required: true entry_schema: type: json - port_pd01_port_0_network_role_tag: + port_pd01_port_0_network_role: type: list required: true entry_schema: type: string - port_pd01_port_1_ip_requirements: - type: list - required: true - entry_schema: - type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 compute_pd_server_availability_zone: type: list required: true @@ -66,20 +54,30 @@ topology_template: vm_flavor_name: type: string required: true - port_pd01_port_1_mac_requirements: + port_pd01_port_1_network_role: type: list required: true entry_schema: - type: json + type: string + port_pd01_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true - port_pd01_port_1_replacement_policy: + port_pd01_port_1_network_role_tag: type: list required: true entry_schema: type: string - port_pd01_port_1_network_role_tag: + port_pd01_port_0_subnetpoolid: type: list required: true entry_schema: @@ -94,6 +92,58 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_0_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_1_ip_requirements: + type: list + required: true + entry_schema: + type: json + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd01_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_0_security_groups: type: list required: true @@ -126,10 +176,18 @@ topology_template: get_input: - port_pd01_port_1_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_1_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_1_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_1_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_1_ip_requirements @@ -142,6 +200,18 @@ topology_template: get_input: - port_pd01_port_1_mac_requirements - index_value + order: + get_input: + - port_pd01_port_1_order + - index_value + network_role: + get_input: + - port_pd01_port_1_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_1_subnetpoolid + - index_value network: get_input: - port_pd01_port_1_network @@ -158,10 +228,18 @@ topology_template: get_input: - port_pd01_port_0_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_0_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_0_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_0_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_0_ip_requirements @@ -174,6 +252,18 @@ topology_template: get_input: - port_pd01_port_0_mac_requirements - index_value + order: + get_input: + - port_pd01_port_0_order + - index_value + network_role: + get_input: + - port_pd01_port_0_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_0_subnetpoolid + - index_value network: get_input: - port_pd01_port_0_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml index 00cd6b4b90..dc1dc15aaa 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -26,20 +26,12 @@ node_types: status: SUPPORTED entry_schema: type: json - port_pd01_port_1_ip_requirements: + port_pd01_port_0_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 + type: string compute_pd_server_availability_zone: type: list required: true @@ -62,17 +54,35 @@ node_types: type: string required: true status: SUPPORTED - port_pd01_port_1_mac_requirements: + port_pd01_port_1_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string + port_pd01_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED - port_pd01_port_1_replacement_policy: + port_pd01_port_1_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_0_subnetpoolid: type: list required: true status: SUPPORTED @@ -90,6 +100,68 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_0_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd01_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_replacement_policy: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json requirements: - dependency_pd_server: capability: tosca.capabilities.Node diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/MainServiceTemplate.yaml index 7a45084d24..17966e0c2f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/MainServiceTemplate.yaml @@ -109,12 +109,6 @@ topology_template: port_pd01_port_0_network: - packet_mirror_network port_pd01_port_0_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - port_pd01_port_1_ip_requirements: - - ip_version: 4 ip_count_required: is_required: false @@ -130,17 +124,23 @@ topology_template: - AUTO vm_flavor_name: get_input: pd_flavor_name - port_pd01_port_1_mac_requirements: - - mac_count_required: - is_required: false vm_image_name: get_input: pd_image_name - port_pd01_port_1_replacement_policy: - - AUTO port_pd01_port_1_network: - packet_internal_network compute_pd_server_user_data_format: - RAW + port_pd01_port_1_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + port_pd01_port_1_mac_requirements: + - mac_count_required: + is_required: false + port_pd01_port_1_replacement_policy: + - AUTO service_template_filter: substitute_service_template: Nested_pd_serverServiceTemplate.yaml count: 1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml index 44d11b66e1..560f18e726 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computeWithSamePortTypeNodeConnectedOut/out/Nested_pd_serverServiceTemplate.yaml @@ -26,18 +26,11 @@ topology_template: required: true entry_schema: type: json - port_pd01_port_1_ip_requirements: + port_pd01_port_0_network_role: type: list required: true entry_schema: - type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 + type: string compute_pd_server_availability_zone: type: list required: true @@ -56,15 +49,30 @@ topology_template: vm_flavor_name: type: string required: true - port_pd01_port_1_mac_requirements: + port_pd01_port_1_network_role: type: list required: true entry_schema: - type: json + type: string + port_pd01_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true - port_pd01_port_1_replacement_policy: + port_pd01_port_1_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_0_subnetpoolid: type: list required: true entry_schema: @@ -79,6 +87,58 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_0_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_1_ip_requirements: + type: list + required: true + entry_schema: + type: json + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd01_port_1_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_replacement_policy: + type: list + required: true + entry_schema: + type: string + port_pd01_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json node_templates: pd_server: type: org.openecomp.resource.vfc.nodes.heat.pd_server @@ -102,18 +162,42 @@ topology_template: pd_server_pd01_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_1_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_1_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_1_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_1_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_1_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_1_mac_requirements - index_value + order: + get_input: + - port_pd01_port_1_order + - index_value + network_role: + get_input: + - port_pd01_port_1_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_1_subnetpoolid + - index_value network: get_input: - port_pd01_port_1_network @@ -126,18 +210,42 @@ topology_template: pd_server_pd01_port_0: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_0_exCP_naming + - index_value replacement_policy: get_input: - port_pd01_port_0_replacement_policy - index_value + vlan_requirements: + get_input: + - port_pd01_port_0_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_0_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_0_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_0_mac_requirements - index_value + order: + get_input: + - port_pd01_port_0_order + - index_value + network_role: + get_input: + - port_pd01_port_0_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_0_subnetpoolid + - index_value network: get_input: - port_pd01_port_0_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/GlobalSubstitutionTypesServiceTemplate.yaml index 058fb9d6bd..857c88bd2e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -34,10 +34,28 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_flavor_name: type: string required: true status: SUPPORTED + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -50,6 +68,12 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_image_name: type: string required: true @@ -66,6 +90,36 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -78,6 +132,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd02_port_network: type: list required: true @@ -507,16 +567,23 @@ node_types: org.openecomp.resource.abstract.nodes.heat.pcm_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pcm_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string availabilityzone_name: type: string description: availabilityzone name required: true status: SUPPORTED - oam_net_gw: - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json pcm_image_name: type: string description: PCRF CM image name @@ -527,6 +594,62 @@ node_types: description: CPS network ip required: true status: SUPPORTED + port_pcm_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + pcm_server_name: + type: string + description: PCRF CM server name + required: true + status: SUPPORTED + cps_net_mask: + type: string + description: CPS network mask + required: true + status: SUPPORTED + port_pcm_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + oam_net_name: + type: string + description: OAM network name + required: true + status: SUPPORTED + port_pcm_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + oam_net_gw: + type: string + description: CPS network gateway + required: true + status: SUPPORTED security_group_name: type: string description: the name of security group @@ -542,6 +665,12 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED + port_pcm_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json pcm_flavor_name: type: string description: flavor name of PCRF CM instance @@ -552,21 +681,11 @@ node_types: description: CPS Cluman Cinder Volume required: true status: SUPPORTED - pcm_server_name: - type: string - description: PCRF CM server name - required: true - status: SUPPORTED cps_net_name: type: string description: CPS network name required: true status: SUPPORTED - cps_net_mask: - type: string - description: CPS network mask - required: true - status: SUPPORTED oam_net_ip: type: string description: OAM network ip @@ -577,11 +696,12 @@ node_types: description: CPS network mask required: true status: SUPPORTED - oam_net_name: - type: string - description: OAM network name + port_pcm_port_1_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer attributes: server_pcm_id: type: string diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/Nested_pd_serverServiceTemplate.yaml index e9da306669..6d0690a78d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/Nested_pd_serverServiceTemplate.yaml @@ -33,9 +33,24 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json vm_flavor_name: type: string required: true + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -46,6 +61,11 @@ topology_template: required: true entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json vm_image_name: type: string required: true @@ -59,6 +79,31 @@ topology_template: required: true entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -69,6 +114,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd02_port_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd02_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/nested-pcm_v0.1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/nested-pcm_v0.1ServiceTemplate.yaml index ba350ce357..8d7c6bd66a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/nested-pcm_v0.1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwodiffporttypesandnested/out/nested-pcm_v0.1ServiceTemplate.yaml @@ -11,18 +11,22 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pcm_port_0_network_role: + type: list + required: true + entry_schema: + type: string availabilityzone_name: label: availabilityzone name hidden: false immutable: false type: string description: availabilityzone name - oam_net_gw: - label: CPS network gateway - hidden: false - immutable: false - type: string - description: CPS network gateway + port_pcm_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_image_name: label: image name hidden: false @@ -35,6 +39,60 @@ topology_template: immutable: false type: string description: CPS network ip + port_pcm_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pcm_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pcm_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + pcm_server_name: + label: PCRF CM server name + hidden: false + immutable: false + type: string + description: PCRF CM server name + cps_net_mask: + label: CPS network mask + hidden: false + immutable: false + type: string + description: CPS network mask + port_pcm_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pcm_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + oam_net_name: + label: OAM network name + hidden: false + immutable: false + type: string + description: OAM network name + port_pcm_port_1_network_role: + type: list + required: true + entry_schema: + type: string + oam_net_gw: + label: CPS network gateway + hidden: false + immutable: false + type: string + description: CPS network gateway security_group_name: label: security group name hidden: false @@ -53,6 +111,11 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume + port_pcm_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json pcm_flavor_name: label: PCRF CM flavor name hidden: false @@ -65,24 +128,12 @@ topology_template: immutable: false type: string description: CPS Cluman Cinder Volume - pcm_server_name: - label: PCRF CM server name - hidden: false - immutable: false - type: string - description: PCRF CM server name cps_net_name: label: CPS network name hidden: false immutable: false type: string description: CPS network name - cps_net_mask: - label: CPS network mask - hidden: false - immutable: false - type: string - description: CPS network mask oam_net_ip: label: OAM network ip hidden: false @@ -95,12 +146,11 @@ topology_template: immutable: false type: string description: CPS network mask - oam_net_name: - label: OAM network name - hidden: false - immutable: false - type: string - description: OAM network name + port_pcm_port_1_order: + type: list + required: true + entry_schema: + type: integer node_templates: pcm_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -113,15 +163,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_1_network_role + - index_value fixed_ips: - ip_address: get_input: oam_net_ip + subnetpoolid: + get_input: + - port_pcm_port_1_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_1_vlan_requirements + - index_value network_role_tag: oam network: get_input: oam_net_name + order: + get_input: + - port_pcm_port_1_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable @@ -151,15 +221,35 @@ topology_template: is_required: false security_groups: - get_input: security_group_name + network_role: + get_input: + - port_pcm_port_0_network_role + - index_value fixed_ips: - ip_address: get_input: cps_net_ip + subnetpoolid: + get_input: + - port_pcm_port_0_subnetpoolid + - index_value mac_requirements: mac_count_required: is_required: false + exCP_naming: + get_input: + - port_pcm_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pcm_port_0_vlan_requirements + - index_value network_role_tag: cps network: get_input: cps_net_name + order: + get_input: + - port_pcm_port_0_order + - index_value requirements: - binding: capability: tosca.capabilities.network.Bindable diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/GlobalSubstitutionTypesServiceTemplate.yaml index af15bfb115..a308e85feb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -32,6 +32,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -58,26 +64,80 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer vm_flavor_name: type: string required: true status: SUPPORTED + port_pd01_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED + port_pd01_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/Nested_pd_serverServiceTemplate.yaml index 236dc97e62..e2edfa3db1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/computewithtwosameporttypes/out/Nested_pd_serverServiceTemplate.yaml @@ -31,6 +31,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_0_network_role: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -53,22 +58,67 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + entry_schema: + type: integer vm_flavor_name: type: string required: true + port_pd01_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true + port_pd01_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_1_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_1_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_1_mac_requirements - index_value + order: + get_input: + - port_pd01_port_1_order + - index_value + network_role: + get_input: + - port_pd01_port_1_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_1_subnetpoolid + - index_value network: get_input: - port_pd01_port_1_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd01_port_0: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_0_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_0_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd01_port_0_mac_requirements - index_value + order: + get_input: + - port_pd01_port_0_order + - index_value + network_role: + get_input: + - port_pd01_port_0_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_0_subnetpoolid + - index_value network: get_input: - port_pd01_port_0_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 8d72374fc5..f6428554bf 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -34,10 +34,28 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_flavor_name: type: string required: true status: SUPPORTED + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -50,6 +68,12 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_image_name: type: string required: true @@ -66,6 +90,36 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -78,6 +132,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd02_port_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml index 073e86d1cb..bd885f9dbe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/diffPortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml @@ -33,9 +33,24 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json vm_flavor_name: type: string required: true + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -46,6 +61,11 @@ topology_template: required: true entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json vm_image_name: type: string required: true @@ -59,6 +79,31 @@ topology_template: required: true entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -69,6 +114,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd02_port_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd02_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/GlobalSubstitutionTypesServiceTemplate.yaml index d1f7bb0857..d53617ed8d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -14,6 +14,112 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB2_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_FSB2_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal2_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_FSB2_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal2_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_FSB2_Internal2_mac_requirements: type: list required: true @@ -40,41 +146,37 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_FSB2_Internal2_network: + port_FSB_OAM_order: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED - compute_FSB2_availability_zone: + type: integer + port_FSB2_Internal2_network: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB_OAM_ip_requirements: + port_FSB2_Internal2_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_FSB2_Internal1_ip_requirements: + port_FSB2_Internal1_order: type: list required: true status: SUPPORTED entry_schema: - type: json - compute_FSB2_name: + type: integer + port_FSB2_Internal2_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB2_Internal1_mac_address: + port_FSB2_Internal1_network_role_tag: type: list required: true status: SUPPORTED @@ -92,24 +194,24 @@ node_types: status: SUPPORTED entry_schema: type: json - port_FSB_OAM_network: + port_FSB2_Internal2_order: type: list required: true status: SUPPORTED entry_schema: - type: string - port_FSB2_Internal1_network: + type: integer + port_FSB2_Internal1_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB2_Internal2_mac_address: + port_FSB_OAM_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json requirements: - dependency_FSB2_FSB_OAM: capability: tosca.capabilities.Node @@ -605,12 +707,12 @@ node_types: org.openecomp.resource.abstract.nodes.VLC2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_VLC_SCTP_A_network: + port_VLC_GTP_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json port_VLC_OAM_network_role_tag: type: list required: true @@ -651,24 +753,24 @@ node_types: status: SUPPORTED entry_schema: type: json - port_VLC_OAM_ip_requirements: + port_VLC2_Internal1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_VLC2_Internal2_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC_OAM_fixed_ips: + port_VLC_GTP_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string vm_image_name: type: string required: true @@ -691,12 +793,6 @@ node_types: status: SUPPORTED entry_schema: type: json - port_VLC_SCTP_A_ip_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json port_VLC_SCTP_B_network: type: list required: true @@ -715,127 +811,343 @@ node_types: status: SUPPORTED entry_schema: type: json - compute_VLC2_name: + port_VLC_GTP_order: type: list required: true status: SUPPORTED entry_schema: - type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + type: integer + port_VLC_OAM_exCP_naming: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - port_VLC_SCTP_B_fixed_ips: + entry_schema: + type: json + port_VLC_SCTP_A_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_GTP_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC_GTP_mac_requirements: + port_VLC_GTP_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC2_Internal1_network: + port_VLC_OAM_network: type: list required: true status: SUPPORTED entry_schema: type: string - compute_VLC2_availability_zone: + port_VLC2_Internal2_network: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC_GTP_fixed_ips: + port_VLC_SCTP_A_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC_OAM_mac_requirements: + port_VLC_SCTP_A_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_SCTP_B_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC_OAM_network: + port_VLC_SCTP_A_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC2_Internal1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_OAM_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC_SCTP_B_mac_requirements: + port_VLC_SCTP_A_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC2_Internal2_network: + port_VLC2_Internal2_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_SCTP_A_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - requirements: - - dependency_VLC2_VLC2_Internal2: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED - - link_VLC2_VLC2_Internal2: - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - occurrences: - - 1 - - 1 - - dependency_VLC2_VLC_OAM: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED - - link_VLC2_VLC_OAM: - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - occurrences: - - 1 - - 1 - - dependency_VLC2_VLC2_Internal1: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED - - link_VLC2_VLC2_Internal1: - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - occurrences: - - 1 - - 1 - - dependency_VLC2_VLC_SCTP_A: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED - - link_VLC2_VLC_SCTP_A: - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - occurrences: - - 1 - - 1 + port_VLC_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_B_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_VLC2_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_OAM_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC2_Internal1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC2_Internal2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_VLC_SCTP_B_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC2_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_B_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_GTP_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC2_Internal2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_GTP_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC2_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_VLC2_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC2_Internal1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC2_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC2_Internal2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_B_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC2_Internal2_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_SCTP_B_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_GTP_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC2_Internal1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_B_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_SCTP_B_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + requirements: + - dependency_VLC2_VLC2_Internal2: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - link_VLC2_VLC2_Internal2: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: + - 1 + - 1 + - dependency_VLC2_VLC_OAM: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - link_VLC2_VLC_OAM: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: + - 1 + - 1 + - dependency_VLC2_VLC2_Internal1: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - link_VLC2_VLC2_Internal1: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: + - 1 + - 1 + - dependency_VLC2_VLC_SCTP_A: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - link_VLC2_VLC_SCTP_A: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: + - 1 + - 1 - dependency_VLC2_VLC_SCTP_B: capability: tosca.capabilities.Node node: tosca.nodes.Root @@ -1512,32 +1824,24 @@ node_types: org.openecomp.resource.abstract.nodes.NCB1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_NCB1_Internal2_mac_address: + port_NCB1_Internal1_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - port_NCB1_Internal1_mac_address: + port_NCB1_Internal2_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_NCB1_Internal1_ip_requirements: + port_NCB1_Internal1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string vm_flavor_name: type: string required: true @@ -1548,68 +1852,148 @@ node_types: status: SUPPORTED entry_schema: type: string - port_NCB1_Internal1_mac_requirements: + port_NCB1_Internal2_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_NCB1_Internal2_mac_requirements: + vm_image_name: + type: string + required: true + status: SUPPORTED + port_NCB1_Internal2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_NCB1_Internal2_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_NCB1_Internal1_network: + port_NCB1_Internal1_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_NCB1_availability_zone: + type: json + port_NCB1_Internal1_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_NCB1_Internal2_vlan_requirements: + type: list required: true status: SUPPORTED - port_NCB1_Internal2_ip_requirements: + entry_schema: + type: json + port_NCB1_Internal2_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - port_NCB1_Internal2_network: + type: string + port_NCB1_Internal2_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - requirements: - - dependency_NCB1: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED - - local_storage_NCB1: - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - occurrences: - - 0 - - UNBOUNDED - - dependency_NCB1_NCB1_Internal1: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_NCB1_Internal1_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_NCB1_Internal1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_NCB1_Internal2_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB1_Internal1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB1_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB1_Internal1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB1_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_NCB1_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_NCB1_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_NCB1_Internal2_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + requirements: + - dependency_NCB1: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - local_storage_NCB1: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: + - 0 + - UNBOUNDED + - dependency_NCB1_NCB1_Internal1: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED - link_NCB1_NCB1_Internal1: capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo @@ -2005,6 +2389,62 @@ node_types: org.openecomp.resource.abstract.nodes.NCB2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + compute_NCB2_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_NCB2_Internal2_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB2_Internal1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_NCB2_Internal1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB2_Internal2_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB2_Internal1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_NCB2_Internal1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_NCB2_Internal2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string index_value: type: integer description: Index value of this substitution service template runtime instance @@ -2019,62 +2459,78 @@ node_types: status: SUPPORTED entry_schema: type: string - compute_NCB2_availability_zone: + port_NCB2_Internal2_ip_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string - port_NCB2_Internal2_ip_requirements: + type: json + port_NCB2_Internal2_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_flavor_name: - type: string + type: string + port_NCB2_Internal2_network: + type: list required: true status: SUPPORTED - port_NCB2_Internal2_mac_requirements: + entry_schema: + type: string + port_NCB2_Internal2_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_NCB2_Internal2_network: + port_NCB2_Internal1_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - port_NCB2_Internal1_mac_requirements: + port_NCB2_Internal2_mac_address: type: list required: true status: SUPPORTED entry_schema: - type: json - port_NCB2_Internal1_mac_address: + type: string + port_NCB2_Internal1_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_NCB2_Internal2_mac_address: + port_NCB2_Internal1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_NCB2_Internal2_order: + type: list required: true status: SUPPORTED + entry_schema: + type: integer compute_NCB2_name: type: list required: true status: SUPPORTED entry_schema: type: string + port_NCB2_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_NCB2_Internal2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_NCB2_Internal1_ip_requirements: type: list required: true @@ -2498,6 +2954,74 @@ node_types: org.openecomp.resource.abstract.nodes.GPB2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_GPB2_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB2_Internal2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_GPB2_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB2_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_GPB2_Internal2_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED + port_GPB2_Internal2_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_GPB2_Internal1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_GPB2_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB2_Internal1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB2_Internal2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_GPB2_Internal2_mac_address: type: list required: true @@ -2516,7 +3040,7 @@ node_types: status: SUPPORTED entry_schema: type: json - port_GPB2_Internal1_network: + port_GPB2_Internal2_network_role: type: list required: true status: SUPPORTED @@ -2536,27 +3060,31 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_GPB2_Internal2_exCP_naming: + type: list required: true status: SUPPORTED - port_GPB2_Internal1_mac_requirements: + entry_schema: + type: json + port_GPB2_Internal1_order: type: list required: true status: SUPPORTED entry_schema: - type: json - port_GPB2_Internal2_ip_requirements: + type: integer + port_GPB2_Internal1_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - vm_image_name: - type: string + port_GPB2_Internal1_exCP_naming: + type: list required: true status: SUPPORTED - compute_GPB2_name: + entry_schema: + type: json + port_GPB2_Internal1_network_role_tag: type: list required: true status: SUPPORTED @@ -2997,36 +3525,42 @@ node_types: status: SUPPORTED entry_schema: type: string - port_VLC1_Internal1_network: + port_VLC_GTP_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_VLC_SCTP_A_network: + type: json + port_VLC_OAM_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC_OAM_network_role_tag: + port_VLC1_Internal1_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC1_Internal1_mac_address: + port_VLC_GTP_ip_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string - port_VLC_GTP_ip_requirements: + type: json + port_VLC1_Internal2_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json + port_VLC1_Internal2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_VLC_SCTP_A_mac_requirements: type: list required: true @@ -3055,6 +3589,160 @@ node_types: status: SUPPORTED entry_schema: type: json + port_VLC1_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_GTP_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_image_name: + type: string + required: true + status: SUPPORTED + port_VLC1_Internal1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_B_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC1_Internal1_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_GTP_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_GTP_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_OAM_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC1_Internal1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC1_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC1_Internal1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_SCTP_A_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_GTP_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_GTP_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_VLC1_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC1_Internal2_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC1_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC1_Internal1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_SCTP_B_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_SCTP_A_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_VLC_OAM_ip_requirements: type: list required: true @@ -3067,40 +3755,72 @@ node_types: status: SUPPORTED entry_schema: type: json - port_VLC_OAM_fixed_ips: + port_VLC_OAM_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC1_Internal2_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC1_Internal2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC1_Internal2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_VLC_SCTP_A_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json - vm_image_name: - type: string - required: true - status: SUPPORTED - port_VLC_SCTP_A_ip_requirements: + type: string + compute_VLC1_availability_zone: type: list required: true status: SUPPORTED entry_schema: - type: json - port_VLC_SCTP_B_network: + type: string + port_VLC_OAM_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC_GTP_network: + port_VLC_SCTP_B_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string - compute_VLC1_availability_zone: + port_VLC_OAM_order: type: list required: true status: SUPPORTED entry_schema: - type: string + type: integer index_value: type: integer description: Index value of this substitution service template runtime instance @@ -3109,66 +3829,84 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_VLC1_Internal1_mac_requirements: + port_VLC1_Internal2_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC1_Internal2_mac_requirements: + port_VLC_SCTP_B_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_VLC_SCTP_B_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json + port_VLC_GTP_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_VLC_SCTP_A_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_VLC_GTP_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC_GTP_fixed_ips: + port_VLC_OAM_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC_OAM_mac_requirements: + port_VLC1_Internal1_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC_OAM_network: + port_VLC_SCTP_B_mac_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_VLC1_name: + type: json + port_VLC_SCTP_B_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_VLC_GTP_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_VLC_SCTP_B_mac_requirements: + port_VLC_SCTP_B_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_VLC1_Internal2_ip_requirements: + port_VLC_SCTP_B_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string requirements: - dependency_VLC1_VLC_SCTP_B: capability: tosca.capabilities.Node @@ -3916,6 +4654,94 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB1_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal2_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal1_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_FSB_OAM_mac_requirements: type: list required: true @@ -3928,6 +4754,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB1_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -3936,28 +4768,24 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_FSB1_Internal1_network: + port_FSB_OAM_order: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED - port_FSB1_Internal2_mac_address: + type: integer + port_FSB1_Internal1_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB_OAM_ip_requirements: + port_FSB1_Internal2_network_role_tag: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_FSB1_Internal2_mac_requirements: type: list required: true @@ -3970,36 +4798,48 @@ node_types: status: SUPPORTED entry_schema: type: json + port_FSB1_Internal2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer port_FSB_OAM_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - compute_FSB1_name: + port_FSB1_Internal1_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - port_FSB1_Internal1_mac_requirements: + type: json + port_FSB_OAM_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json - port_FSB1_Internal1_ip_requirements: + compute_FSB1_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal2_exCP_naming: type: list required: true status: SUPPORTED entry_schema: type: json - port_FSB_OAM_network: + port_FSB1_Internal2_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json requirements: - dependency_FSB1_FSB1_Internal2: capability: tosca.capabilities.Node @@ -4495,21 +5335,13 @@ node_types: org.openecomp.resource.abstract.nodes.GPB1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_GPB1_Internal2_network: + port_GPB1_Internal1_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - port_GPB1_Internal1_network: + port_GPB1_Internal2_network_role: type: list required: true status: SUPPORTED @@ -4525,29 +5357,29 @@ node_types: type: string required: true status: SUPPORTED - port_GPB1_Internal2_mac_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json - port_GPB1_Internal1_mac_address: + port_GPB1_Internal2_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - port_GPB1_Internal2_mac_address: + port_GPB1_Internal1_order: type: list required: true status: SUPPORTED entry_schema: - type: string + type: integer vm_image_name: type: string required: true status: SUPPORTED - port_GPB1_Internal1_ip_requirements: + port_GPB1_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_GPB1_Internal2_exCP_naming: type: list required: true status: SUPPORTED @@ -4565,12 +5397,92 @@ node_types: status: SUPPORTED entry_schema: type: string + port_GPB1_Internal1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_GPB1_Internal2_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_GPB1_Internal2_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_GPB1_Internal1_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB1_Internal2_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_GPB1_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB1_Internal2_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_GPB1_Internal1_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB1_Internal1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB1_Internal2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB1_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_GPB1_Internal1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_GPB1_Internal2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer requirements: - dependency_GPB1: capability: tosca.capabilities.Node diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/MainServiceTemplate.yaml index 8e78b6635d..8ae59dca18 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/MainServiceTemplate.yaml @@ -627,8 +627,6 @@ topology_template: directives: - substitutable properties: - port_VLC_SCTP_A_network: - - epc-sctp-a-net port_VLC_OAM_network_role_tag: - oam port_VLC_GTP_ip_requirements: @@ -657,17 +655,8 @@ topology_template: port_VLC_SCTP_A_fixed_ips: - - ip_address: get_input: vlc2-sctp-a-ip - port_VLC_OAM_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false port_VLC2_Internal2_mac_address: - get_input: vlc2-Internal2-mac - port_VLC_OAM_fixed_ips: - - - ip_address: - get_input: vlc2-oam-ip vm_image_name: get_input: pxe-image port_VLC2_Internal1_mac_address: @@ -678,12 +667,6 @@ topology_template: port_VLC2_Internal1_mac_requirements: - mac_count_required: is_required: true - port_VLC_SCTP_A_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: true - floating_ip_count_required: - is_required: false port_VLC_SCTP_B_network: - epc-sctp-b-net port_VLC_GTP_network: @@ -694,6 +677,30 @@ topology_template: is_required: false floating_ip_count_required: is_required: false + port_VLC_GTP_fixed_ips: + - - ip_address: + get_input: vlc2-gtp-ip + port_VLC_OAM_network: + - get_input: oam_net_id + port_VLC2_Internal2_network: + - Internal2-net + port_VLC_SCTP_A_network: + - epc-sctp-a-net + port_VLC_OAM_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false + port_VLC_OAM_fixed_ips: + - - ip_address: + get_input: vlc2-oam-ip + port_VLC_SCTP_A_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: true + floating_ip_count_required: + is_required: false compute_VLC2_name: - get_input: vlc2-name port_VLC_SCTP_B_fixed_ips: @@ -706,19 +713,12 @@ topology_template: - Internal1-net compute_VLC2_availability_zone: - get_input: vlc_zone - port_VLC_GTP_fixed_ips: - - - ip_address: - get_input: vlc2-gtp-ip port_VLC_OAM_mac_requirements: - mac_count_required: is_required: false - port_VLC_OAM_network: - - get_input: oam_net_id port_VLC_SCTP_B_mac_requirements: - mac_count_required: is_required: false - port_VLC2_Internal2_network: - - Internal2-net service_template_filter: substitute_service_template: Nested_VLC2ServiceTemplate.yaml count: 1 @@ -755,10 +755,6 @@ topology_template: properties: port_VLC1_Internal2_mac_address: - get_input: vlc1-Internal2-mac - port_VLC1_Internal1_network: - - Internal1-net - port_VLC_SCTP_A_network: - - epc-sctp-a-net port_VLC_OAM_network_role_tag: - oam port_VLC1_Internal1_mac_address: @@ -785,6 +781,32 @@ topology_template: port_VLC_SCTP_A_fixed_ips: - - ip_address: get_input: vlc1-sctp-a-ip + vm_image_name: + get_input: pxe-image + port_VLC_SCTP_B_network: + - epc-sctp-b-net + port_VLC_GTP_network: + - epc-gtp-net + port_VLC1_Internal1_mac_requirements: + - mac_count_required: + is_required: true + port_VLC_GTP_fixed_ips: + - - ip_address: + get_input: vlc1-gtp-ip + port_VLC_OAM_network: + - get_input: oam_net_id + compute_VLC1_name: + - get_input: vlc1-name + port_VLC1_Internal2_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + port_VLC1_Internal1_network: + - Internal1-net + port_VLC_SCTP_A_network: + - epc-sctp-a-net port_VLC_OAM_ip_requirements: - - ip_version: 4 ip_count_required: @@ -800,23 +822,14 @@ topology_template: port_VLC_OAM_fixed_ips: - - ip_address: get_input: vlc1-oam-ip - vm_image_name: - get_input: pxe-image port_VLC_SCTP_A_ip_requirements: - - ip_version: 4 ip_count_required: is_required: true floating_ip_count_required: is_required: false - port_VLC_SCTP_B_network: - - epc-sctp-b-net - port_VLC_GTP_network: - - epc-gtp-net compute_VLC1_availability_zone: - get_input: vlc_zone - port_VLC1_Internal1_mac_requirements: - - mac_count_required: - is_required: true port_VLC1_Internal2_mac_requirements: - mac_count_required: is_required: true @@ -826,25 +839,12 @@ topology_template: port_VLC_GTP_mac_requirements: - mac_count_required: is_required: false - port_VLC_GTP_fixed_ips: - - - ip_address: - get_input: vlc1-gtp-ip port_VLC_OAM_mac_requirements: - mac_count_required: is_required: false - port_VLC_OAM_network: - - get_input: oam_net_id - compute_VLC1_name: - - get_input: vlc1-name port_VLC_SCTP_B_mac_requirements: - mac_count_required: is_required: false - port_VLC1_Internal2_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false service_template_filter: substitute_service_template: Nested_VLC1ServiceTemplate.yaml count: 1 @@ -900,35 +900,35 @@ topology_template: directives: - substitutable properties: - port_GPB1_Internal2_network: - - Internal2-net - port_GPB1_Internal1_network: - - Internal1-net compute_GPB1_name: - get_input: gpb1-name vm_flavor_name: get_input: gpb-flavor - port_GPB1_Internal2_mac_requirements: - - mac_count_required: - is_required: true - port_GPB1_Internal1_mac_address: - - get_input: gpb1-Internal1-mac port_GPB1_Internal2_mac_address: - get_input: gpb1-Internal2-mac vm_image_name: get_input: pxe-image - port_GPB1_Internal1_ip_requirements: + port_GPB1_Internal1_mac_requirements: + - mac_count_required: + is_required: true + compute_GPB1_availability_zone: + - get_input: gpb_zone + port_GPB1_Internal2_ip_requirements: - - ip_version: 4 ip_count_required: is_required: false floating_ip_count_required: is_required: false - port_GPB1_Internal1_mac_requirements: + port_GPB1_Internal2_network: + - Internal2-net + port_GPB1_Internal1_network: + - Internal1-net + port_GPB1_Internal2_mac_requirements: - mac_count_required: is_required: true - compute_GPB1_availability_zone: - - get_input: gpb_zone - port_GPB1_Internal2_ip_requirements: + port_GPB1_Internal1_mac_address: + - get_input: gpb1-Internal1-mac + port_GPB1_Internal1_ip_requirements: - - ip_version: 4 ip_count_required: is_required: false @@ -956,6 +956,20 @@ topology_template: directives: - substitutable properties: + port_GPB2_Internal1_network: + - Internal1-net + vm_flavor_name: + get_input: gpb-flavor + port_GPB2_Internal2_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + vm_image_name: + get_input: pxe-image + compute_GPB2_name: + - get_input: gpb2-name port_GPB2_Internal2_mac_address: - get_input: gpb2-Internal2-mac port_GPB2_Internal2_mac_requirements: @@ -967,25 +981,11 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - port_GPB2_Internal1_network: - - Internal1-net compute_GPB2_availability_zone: - get_input: gpb_zone - vm_flavor_name: - get_input: gpb-flavor port_GPB2_Internal1_mac_requirements: - mac_count_required: is_required: true - port_GPB2_Internal2_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - vm_image_name: - get_input: pxe-image - compute_GPB2_name: - - get_input: gpb2-name port_GPB2_Internal1_mac_address: - get_input: gpb2-Internal1-mac port_GPB2_Internal2_network: @@ -1051,6 +1051,21 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_input: ncb-flavor + compute_NCB1_name: + - get_input: ncb1-name + port_NCB1_Internal2_mac_requirements: + - mac_count_required: + is_required: true + vm_image_name: + get_input: pxe-image + port_NCB1_Internal2_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false port_NCB1_Internal2_mac_address: - get_input: ncb1-Internal2-mac port_NCB1_Internal1_mac_address: @@ -1061,28 +1076,13 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - vm_flavor_name: - get_input: ncb-flavor - compute_NCB1_name: - - get_input: ncb1-name port_NCB1_Internal1_mac_requirements: - - mac_count_required: - is_required: true - port_NCB1_Internal2_mac_requirements: - mac_count_required: is_required: true port_NCB1_Internal1_network: - Internal1-net compute_NCB1_availability_zone: - get_input: ncb_zone - vm_image_name: - get_input: pxe-image - port_NCB1_Internal2_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false port_NCB1_Internal2_network: - Internal2-net service_template_filter: @@ -1107,32 +1107,32 @@ topology_template: directives: - substitutable properties: - port_NCB2_Internal1_network: - - Internal1-net compute_NCB2_availability_zone: - get_input: ncb_zone - port_NCB2_Internal2_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false vm_flavor_name: get_input: ncb-flavor port_NCB2_Internal2_mac_requirements: - mac_count_required: is_required: true - port_NCB2_Internal2_network: - - Internal2-net port_NCB2_Internal1_mac_requirements: - mac_count_required: is_required: true + vm_image_name: + get_input: pxe-image + port_NCB2_Internal1_network: + - Internal1-net + port_NCB2_Internal2_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + port_NCB2_Internal2_network: + - Internal2-net port_NCB2_Internal1_mac_address: - get_input: ncb2-Internal1-mac port_NCB2_Internal2_mac_address: - get_input: ncb2-Internal2-mac - vm_image_name: - get_input: pxe-image compute_NCB2_name: - get_input: ncb2-name port_NCB2_Internal1_ip_requirements: @@ -1187,11 +1187,6 @@ topology_template: - oam port_FSB1_Internal2_network: - Internal2-net - port_FSB_OAM_mac_requirements: - - mac_count_required: - is_required: false - compute_FSB1_availability_zone: - - get_input: fsb_zone port_FSB1_Internal1_network: - Internal1-net vm_flavor_name: @@ -1204,31 +1199,36 @@ topology_template: is_required: true floating_ip_count_required: is_required: false - port_FSB1_Internal2_mac_requirements: + port_FSB1_Internal1_mac_requirements: - mac_count_required: is_required: true - port_FSB1_Internal2_ip_requirements: + port_FSB1_Internal1_ip_requirements: - - ip_version: 4 ip_count_required: is_required: false floating_ip_count_required: is_required: false - port_FSB_OAM_fixed_ips: - - - ip_address: - get_input: fsb1-oam-ip - compute_FSB1_name: - - get_input: fsb1-name - port_FSB1_Internal1_mac_requirements: + port_FSB_OAM_network: + - get_input: oam_net_id + port_FSB_OAM_mac_requirements: + - mac_count_required: + is_required: false + compute_FSB1_availability_zone: + - get_input: fsb_zone + port_FSB1_Internal2_mac_requirements: - mac_count_required: is_required: true - port_FSB1_Internal1_ip_requirements: + port_FSB1_Internal2_ip_requirements: - - ip_version: 4 ip_count_required: is_required: false floating_ip_count_required: is_required: false - port_FSB_OAM_network: - - get_input: oam_net_id + port_FSB_OAM_fixed_ips: + - - ip_address: + get_input: fsb1-oam-ip + compute_FSB1_name: + - get_input: fsb1-name service_template_filter: substitute_service_template: Nested_FSB1ServiceTemplate.yaml count: 1 @@ -1253,20 +1253,6 @@ topology_template: properties: port_FSB_OAM_network_role_tag: - oam - port_FSB2_Internal2_mac_requirements: - - mac_count_required: - is_required: true - port_FSB_OAM_mac_requirements: - - mac_count_required: - is_required: false - port_FSB2_Internal2_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - port_FSB2_Internal2_network: - - Internal2-net vm_flavor_name: get_input: fsb2-flavor compute_FSB2_availability_zone: @@ -1287,18 +1273,32 @@ topology_template: - get_input: fsb2-name port_FSB2_Internal1_mac_address: - get_input: fsb2-Internal1-mac - port_FSB_OAM_fixed_ips: - - - ip_address: - get_input: fsb2-oam-ip - port_FSB2_Internal1_mac_requirements: - - mac_count_required: - is_required: true port_FSB_OAM_network: - get_input: oam_net_id port_FSB2_Internal1_network: - Internal1-net port_FSB2_Internal2_mac_address: - get_input: fsb2-Internal2-mac + port_FSB2_Internal2_mac_requirements: + - mac_count_required: + is_required: true + port_FSB_OAM_mac_requirements: + - mac_count_required: + is_required: false + port_FSB2_Internal2_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + port_FSB2_Internal2_network: + - Internal2-net + port_FSB_OAM_fixed_ips: + - - ip_address: + get_input: fsb2-oam-ip + port_FSB2_Internal1_mac_requirements: + - mac_count_required: + is_required: true service_template_filter: substitute_service_template: Nested_FSB2ServiceTemplate.yaml count: 1 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB1ServiceTemplate.yaml index 4331ecaa03..42ba1a647f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB1ServiceTemplate.yaml @@ -26,6 +26,79 @@ topology_template: required: true entry_schema: type: string + port_FSB1_Internal1_network: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_FSB_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal2_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal2_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal1_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal1_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal1_order: + type: list + required: true + entry_schema: + type: integer + port_FSB_OAM_network: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal2_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal1_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_FSB_OAM_mac_requirements: type: list required: true @@ -36,6 +109,11 @@ topology_template: required: true entry_schema: type: string + port_FSB1_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json index_value: type: integer description: Index value of this substitution service template runtime instance @@ -43,24 +121,21 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_FSB1_Internal1_network: + port_FSB_OAM_order: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true - port_FSB1_Internal2_mac_address: + type: integer + port_FSB1_Internal1_network_role: type: list required: true entry_schema: type: string - port_FSB_OAM_ip_requirements: + port_FSB1_Internal2_network_role_tag: type: list required: true entry_schema: - type: json + type: string port_FSB1_Internal2_mac_requirements: type: list required: true @@ -71,43 +146,77 @@ topology_template: required: true entry_schema: type: json + port_FSB1_Internal2_order: + type: list + required: true + entry_schema: + type: integer port_FSB_OAM_fixed_ips: type: list required: true entry_schema: type: json - compute_FSB1_name: + port_FSB1_Internal1_exCP_naming: type: list required: true entry_schema: - type: string - port_FSB1_Internal1_mac_requirements: + type: json + port_FSB_OAM_exCP_naming: type: list required: true entry_schema: type: json - port_FSB1_Internal1_ip_requirements: + compute_FSB1_name: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal2_exCP_naming: type: list required: true entry_schema: type: json - port_FSB_OAM_network: + port_FSB1_Internal2_vlan_requirements: type: list required: true entry_schema: - type: string + type: json node_templates: FSB1_FSB1_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_FSB1_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_FSB1_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_FSB1_Internal2_mac_requirements - index_value + order: + get_input: + - port_FSB1_Internal2_order + - index_value + network_role: + get_input: + - port_FSB1_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal2_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal2_network @@ -124,14 +233,38 @@ topology_template: FSB1_FSB1_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_FSB1_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_FSB1_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_FSB1_Internal1_mac_requirements - index_value + order: + get_input: + - port_FSB1_Internal1_order + - index_value + network_role: + get_input: + - port_FSB1_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal1_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal1_network @@ -148,6 +281,14 @@ topology_template: FSB1_FSB_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB_OAM_vlan_requirements + - index_value ip_requirements: get_input: - port_FSB_OAM_ip_requirements @@ -160,6 +301,18 @@ topology_template: get_input: - port_FSB_OAM_mac_requirements - index_value + order: + get_input: + - port_FSB_OAM_order + - index_value + network_role: + get_input: + - port_FSB_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_FSB_OAM_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB2ServiceTemplate.yaml index a4d2f79275..a71818c237 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_FSB2ServiceTemplate.yaml @@ -16,6 +16,94 @@ topology_template: required: true entry_schema: type: string + port_FSB2_Internal2_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + compute_FSB2_availability_zone: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal2_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal1_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal2_network_role: + type: list + required: true + entry_schema: + type: string + compute_FSB2_name: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_network: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal2_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_FSB2_Internal2_mac_requirements: type: list required: true @@ -38,35 +126,32 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_FSB2_Internal2_network: + port_FSB_OAM_order: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string - required: true - compute_FSB2_availability_zone: + type: integer + port_FSB2_Internal2_network: type: list required: true entry_schema: type: string - port_FSB_OAM_ip_requirements: + port_FSB2_Internal2_vlan_requirements: type: list required: true entry_schema: type: json - port_FSB2_Internal1_ip_requirements: + port_FSB2_Internal1_order: type: list required: true entry_schema: - type: json - compute_FSB2_name: + type: integer + port_FSB2_Internal2_subnetpoolid: type: list required: true entry_schema: type: string - port_FSB2_Internal1_mac_address: + port_FSB2_Internal1_network_role_tag: type: list required: true entry_schema: @@ -81,25 +166,33 @@ topology_template: required: true entry_schema: type: json - port_FSB_OAM_network: + port_FSB2_Internal2_order: type: list required: true entry_schema: - type: string - port_FSB2_Internal1_network: + type: integer + port_FSB2_Internal1_subnetpoolid: type: list required: true entry_schema: type: string - port_FSB2_Internal2_mac_address: + port_FSB_OAM_exCP_naming: type: list required: true entry_schema: - type: string + type: json node_templates: FSB2_FSB_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB_OAM_vlan_requirements + - index_value ip_requirements: get_input: - port_FSB_OAM_ip_requirements @@ -112,6 +205,18 @@ topology_template: get_input: - port_FSB_OAM_mac_requirements - index_value + order: + get_input: + - port_FSB_OAM_order + - index_value + network_role: + get_input: + - port_FSB_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_FSB_OAM_fixed_ips @@ -141,14 +246,38 @@ topology_template: FSB2_FSB2_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_FSB2_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_FSB2_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_FSB2_Internal2_mac_requirements - index_value + order: + get_input: + - port_FSB2_Internal2_order + - index_value + network_role: + get_input: + - port_FSB2_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal2_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal2_network @@ -165,14 +294,38 @@ topology_template: FSB2_FSB2_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_FSB2_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_FSB2_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_FSB2_Internal1_mac_requirements - index_value + order: + get_input: + - port_FSB2_Internal1_order + - index_value + network_role: + get_input: + - port_FSB2_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal1_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal1_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB1ServiceTemplate.yaml index b8e6141f9b..04066334b2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB1ServiceTemplate.yaml @@ -11,19 +11,12 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_GPB1_Internal2_network: + port_GPB1_Internal1_network_role: type: list required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - port_GPB1_Internal1_network: + port_GPB1_Internal2_network_role: type: list required: true entry_schema: @@ -36,25 +29,25 @@ topology_template: vm_flavor_name: type: string required: true - port_GPB1_Internal2_mac_requirements: - type: list - required: true - entry_schema: - type: json - port_GPB1_Internal1_mac_address: + port_GPB1_Internal2_mac_address: type: list required: true entry_schema: type: string - port_GPB1_Internal2_mac_address: + port_GPB1_Internal1_order: type: list required: true entry_schema: - type: string + type: integer vm_image_name: type: string required: true - port_GPB1_Internal1_ip_requirements: + port_GPB1_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_GPB1_Internal2_exCP_naming: type: list required: true entry_schema: @@ -69,11 +62,78 @@ topology_template: required: true entry_schema: type: string + port_GPB1_Internal1_exCP_naming: + type: list + required: true + entry_schema: + type: json port_GPB1_Internal2_ip_requirements: type: list required: true entry_schema: type: json + port_GPB1_Internal2_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_GPB1_Internal1_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_GPB1_Internal2_network: + type: list + required: true + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_GPB1_Internal1_network: + type: list + required: true + entry_schema: + type: string + port_GPB1_Internal2_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_GPB1_Internal1_mac_address: + type: list + required: true + entry_schema: + type: string + port_GPB1_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_GPB1_Internal2_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_GPB1_Internal2_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_GPB1_Internal1_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_GPB1_Internal2_order: + type: list + required: true + entry_schema: + type: integer node_templates: GPB1: type: org.openecomp.resource.vfc.nodes.heat.GPB1 @@ -93,14 +153,38 @@ topology_template: GPB1_GPB1_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_GPB1_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_GPB1_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_GPB1_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_GPB1_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_GPB1_Internal1_mac_requirements - index_value + order: + get_input: + - port_GPB1_Internal1_order + - index_value + network_role: + get_input: + - port_GPB1_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_GPB1_Internal1_subnetpoolid + - index_value network: get_input: - port_GPB1_Internal1_network @@ -117,14 +201,38 @@ topology_template: GPB1_GPB1_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_GPB1_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_GPB1_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_GPB1_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_GPB1_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_GPB1_Internal2_mac_requirements - index_value + order: + get_input: + - port_GPB1_Internal2_order + - index_value + network_role: + get_input: + - port_GPB1_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_GPB1_Internal2_subnetpoolid + - index_value network: get_input: - port_GPB1_Internal2_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB2ServiceTemplate.yaml index 3598778212..64a239a2a5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_GPB2ServiceTemplate.yaml @@ -11,6 +11,62 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_GPB2_Internal2_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_GPB2_Internal2_order: + type: list + required: true + entry_schema: + type: integer + port_GPB2_Internal1_network: + type: list + required: true + entry_schema: + type: string + port_GPB2_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_GPB2_Internal2_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_GPB2_Internal2_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_GPB2_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + compute_GPB2_name: + type: list + required: true + entry_schema: + type: string + port_GPB2_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_GPB2_Internal2_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_GPB2_Internal2_mac_address: type: list required: true @@ -26,7 +82,7 @@ topology_template: required: true entry_schema: type: json - port_GPB2_Internal1_network: + port_GPB2_Internal2_network_role: type: list required: true entry_schema: @@ -43,23 +99,27 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string + port_GPB2_Internal2_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_GPB2_Internal1_order: + type: list required: true + entry_schema: + type: integer port_GPB2_Internal1_mac_requirements: type: list required: true entry_schema: type: json - port_GPB2_Internal2_ip_requirements: + port_GPB2_Internal1_exCP_naming: type: list required: true entry_schema: type: json - vm_image_name: - type: string - required: true - compute_GPB2_name: + port_GPB2_Internal1_network_role_tag: type: list required: true entry_schema: @@ -78,14 +138,38 @@ topology_template: GPB2_GPB2_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_GPB2_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_GPB2_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_GPB2_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_GPB2_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_GPB2_Internal2_mac_requirements - index_value + order: + get_input: + - port_GPB2_Internal2_order + - index_value + network_role: + get_input: + - port_GPB2_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_GPB2_Internal2_subnetpoolid + - index_value network: get_input: - port_GPB2_Internal2_network @@ -102,14 +186,38 @@ topology_template: GPB2_GPB2_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_GPB2_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_GPB2_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_GPB2_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_GPB2_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_GPB2_Internal1_mac_requirements - index_value + order: + get_input: + - port_GPB2_Internal1_order + - index_value + network_role: + get_input: + - port_GPB2_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_GPB2_Internal1_subnetpoolid + - index_value network: get_input: - port_GPB2_Internal1_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB1ServiceTemplate.yaml index f0a3aaf507..c41603b6bd 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB1ServiceTemplate.yaml @@ -11,6 +11,67 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_NCB1_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + port_NCB1_Internal2_network_role: + type: list + required: true + entry_schema: + type: string + port_NCB1_Internal1_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + compute_NCB1_name: + type: list + required: true + entry_schema: + type: string + port_NCB1_Internal2_mac_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_NCB1_Internal2_order: + type: list + required: true + entry_schema: + type: integer + port_NCB1_Internal2_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_NCB1_Internal1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_NCB1_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_NCB1_Internal2_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_NCB1_Internal2_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_NCB1_Internal2_mac_address: type: list required: true @@ -28,25 +89,27 @@ topology_template: required: true entry_schema: type: string - port_NCB1_Internal1_ip_requirements: + port_NCB1_Internal1_order: type: list required: true entry_schema: - type: json - vm_flavor_name: - type: string + type: integer + port_NCB1_Internal2_exCP_naming: + type: list required: true - compute_NCB1_name: + entry_schema: + type: json + port_NCB1_Internal1_ip_requirements: type: list required: true entry_schema: - type: string - port_NCB1_Internal1_mac_requirements: + type: json + port_NCB1_Internal1_vlan_requirements: type: list required: true entry_schema: type: json - port_NCB1_Internal2_mac_requirements: + port_NCB1_Internal1_mac_requirements: type: list required: true entry_schema: @@ -61,14 +124,11 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string - required: true - port_NCB1_Internal2_ip_requirements: + port_NCB1_Internal2_network_role_tag: type: list required: true entry_schema: - type: json + type: string port_NCB1_Internal2_network: type: list required: true @@ -93,14 +153,38 @@ topology_template: NCB1_NCB1_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_NCB1_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_NCB1_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_NCB1_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_NCB1_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_NCB1_Internal1_mac_requirements - index_value + order: + get_input: + - port_NCB1_Internal1_order + - index_value + network_role: + get_input: + - port_NCB1_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_NCB1_Internal1_subnetpoolid + - index_value network: get_input: - port_NCB1_Internal1_network @@ -117,14 +201,38 @@ topology_template: NCB1_NCB1_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_NCB1_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_NCB1_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_NCB1_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_NCB1_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_NCB1_Internal2_mac_requirements - index_value + order: + get_input: + - port_NCB1_Internal2_order + - index_value + network_role: + get_input: + - port_NCB1_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_NCB1_Internal2_subnetpoolid + - index_value network: get_input: - port_NCB1_Internal2_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB2ServiceTemplate.yaml index 7cfca623fa..3ff3a61c8e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_NCB2ServiceTemplate.yaml @@ -11,6 +11,52 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + compute_NCB2_availability_zone: + type: list + required: true + entry_schema: + type: string + vm_flavor_name: + type: string + required: true + port_NCB2_Internal2_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_NCB2_Internal1_mac_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_NCB2_Internal1_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_NCB2_Internal2_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_NCB2_Internal1_order: + type: list + required: true + entry_schema: + type: integer + port_NCB2_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + port_NCB2_Internal2_network_role: + type: list + required: true + entry_schema: + type: string index_value: type: integer description: Index value of this substitution service template runtime instance @@ -23,30 +69,22 @@ topology_template: required: true entry_schema: type: string - compute_NCB2_availability_zone: - type: list - required: true - entry_schema: - type: string port_NCB2_Internal2_ip_requirements: type: list required: true entry_schema: type: json - vm_flavor_name: - type: string - required: true - port_NCB2_Internal2_mac_requirements: + port_NCB2_Internal2_network_role_tag: type: list required: true entry_schema: - type: json + type: string port_NCB2_Internal2_network: type: list required: true entry_schema: type: string - port_NCB2_Internal1_mac_requirements: + port_NCB2_Internal2_vlan_requirements: type: list required: true entry_schema: @@ -61,14 +99,36 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string + port_NCB2_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_NCB2_Internal1_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_NCB2_Internal2_order: + type: list required: true + entry_schema: + type: integer compute_NCB2_name: type: list required: true entry_schema: type: string + port_NCB2_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_NCB2_Internal2_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_NCB2_Internal1_ip_requirements: type: list required: true @@ -93,14 +153,38 @@ topology_template: NCB2_NCB2_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_NCB2_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_NCB2_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_NCB2_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_NCB2_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_NCB2_Internal1_mac_requirements - index_value + order: + get_input: + - port_NCB2_Internal1_order + - index_value + network_role: + get_input: + - port_NCB2_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_NCB2_Internal1_subnetpoolid + - index_value network: get_input: - port_NCB2_Internal1_network @@ -117,14 +201,38 @@ topology_template: NCB2_NCB2_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_NCB2_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_NCB2_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_NCB2_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_NCB2_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_NCB2_Internal2_mac_requirements - index_value + order: + get_input: + - port_NCB2_Internal2_order + - index_value + network_role: + get_input: + - port_NCB2_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_NCB2_Internal2_subnetpoolid + - index_value network: get_input: - port_NCB2_Internal2_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC1ServiceTemplate.yaml index 3fbc173efe..d1f52d6035 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC1ServiceTemplate.yaml @@ -16,16 +16,11 @@ topology_template: required: true entry_schema: type: string - port_VLC1_Internal1_network: - type: list - required: true - entry_schema: - type: string - port_VLC_SCTP_A_network: + port_VLC_GTP_exCP_naming: type: list required: true entry_schema: - type: string + type: json port_VLC_OAM_network_role_tag: type: list required: true @@ -41,6 +36,16 @@ topology_template: required: true entry_schema: type: json + port_VLC1_Internal2_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC1_Internal2_network_role: + type: list + required: true + entry_schema: + type: string port_VLC_SCTP_A_mac_requirements: type: list required: true @@ -64,6 +69,134 @@ topology_template: required: true entry_schema: type: json + port_VLC1_Internal2_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_VLC_GTP_network_role_tag: + type: list + required: true + entry_schema: + type: string + vm_image_name: + type: string + required: true + port_VLC1_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_B_network: + type: list + required: true + entry_schema: + type: string + port_VLC1_Internal1_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_VLC_GTP_network: + type: list + required: true + entry_schema: + type: string + port_VLC_GTP_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_OAM_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC1_Internal1_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC1_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC1_Internal1_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_SCTP_A_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_VLC_GTP_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_GTP_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_VLC_OAM_network: + type: list + required: true + entry_schema: + type: string + compute_VLC1_name: + type: list + required: true + entry_schema: + type: string + port_VLC1_Internal2_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC1_Internal1_network: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_network: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC1_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_SCTP_B_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_A_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_VLC_OAM_ip_requirements: type: list required: true @@ -79,29 +212,56 @@ topology_template: required: true entry_schema: type: json - vm_image_name: - type: string + port_VLC1_Internal2_vlan_requirements: + type: list required: true + entry_schema: + type: json + port_VLC_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC1_Internal2_order: + type: list + required: true + entry_schema: + type: integer + port_VLC1_Internal2_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_VLC_SCTP_A_ip_requirements: type: list required: true entry_schema: type: json - port_VLC_SCTP_B_network: + port_VLC_SCTP_A_subnetpoolid: type: list required: true entry_schema: type: string - port_VLC_GTP_network: + compute_VLC1_availability_zone: type: list required: true entry_schema: type: string - compute_VLC1_availability_zone: + port_VLC_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_B_network_role_tag: type: list required: true entry_schema: type: string + port_VLC_OAM_order: + type: list + required: true + entry_schema: + type: integer index_value: type: integer description: Index value of this substitution service template runtime instance @@ -109,68 +269,107 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_VLC1_Internal1_mac_requirements: + port_VLC1_Internal2_mac_requirements: type: list required: true entry_schema: type: json - port_VLC1_Internal2_mac_requirements: + port_VLC_SCTP_B_subnetpoolid: type: list required: true entry_schema: - type: json + type: string port_VLC_SCTP_B_fixed_ips: type: list required: true entry_schema: type: json + port_VLC_GTP_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_network_role: + type: list + required: true + entry_schema: + type: string port_VLC_GTP_mac_requirements: type: list required: true entry_schema: type: json - port_VLC_GTP_fixed_ips: + port_VLC_OAM_mac_requirements: type: list required: true entry_schema: type: json - port_VLC_OAM_mac_requirements: + port_VLC1_Internal1_exCP_naming: type: list required: true entry_schema: type: json - port_VLC_OAM_network: + port_VLC_SCTP_B_mac_requirements: type: list required: true entry_schema: - type: string - compute_VLC1_name: + type: json + port_VLC_SCTP_B_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_GTP_subnetpoolid: type: list required: true entry_schema: type: string - port_VLC_SCTP_B_mac_requirements: + port_VLC_SCTP_B_vlan_requirements: type: list required: true entry_schema: type: json - port_VLC1_Internal2_ip_requirements: + port_VLC_SCTP_B_network_role: type: list required: true entry_schema: - type: json + type: string node_templates: VLC1_VLC_SCTP_B: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_SCTP_B_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_SCTP_B_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_SCTP_B_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC_SCTP_B_network_role_tag + - index_value mac_requirements: get_input: - port_VLC_SCTP_B_mac_requirements - index_value + order: + get_input: + - port_VLC_SCTP_B_order + - index_value + network_role: + get_input: + - port_VLC_SCTP_B_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_SCTP_B_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_SCTP_B_fixed_ips @@ -187,14 +386,38 @@ topology_template: VLC1_VLC1_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC1_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC1_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC1_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC1_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_VLC1_Internal2_mac_requirements - index_value + order: + get_input: + - port_VLC1_Internal2_order + - index_value + network_role: + get_input: + - port_VLC1_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC1_Internal2_subnetpoolid + - index_value network: get_input: - port_VLC1_Internal2_network @@ -211,14 +434,38 @@ topology_template: VLC1_VLC1_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC1_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC1_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC1_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC1_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_VLC1_Internal1_mac_requirements - index_value + order: + get_input: + - port_VLC1_Internal1_order + - index_value + network_role: + get_input: + - port_VLC1_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC1_Internal1_subnetpoolid + - index_value network: get_input: - port_VLC1_Internal1_network @@ -235,6 +482,14 @@ topology_template: VLC1_VLC_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_OAM_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_OAM_ip_requirements @@ -247,6 +502,18 @@ topology_template: get_input: - port_VLC_OAM_mac_requirements - index_value + order: + get_input: + - port_VLC_OAM_order + - index_value + network_role: + get_input: + - port_VLC_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_OAM_fixed_ips @@ -263,14 +530,38 @@ topology_template: VLC1_VLC_SCTP_A: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_SCTP_A_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_SCTP_A_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_SCTP_A_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC_SCTP_A_network_role_tag + - index_value mac_requirements: get_input: - port_VLC_SCTP_A_mac_requirements - index_value + order: + get_input: + - port_VLC_SCTP_A_order + - index_value + network_role: + get_input: + - port_VLC_SCTP_A_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_SCTP_A_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_SCTP_A_fixed_ips @@ -302,14 +593,38 @@ topology_template: VLC1_VLC_GTP: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_GTP_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_GTP_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_GTP_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC_GTP_network_role_tag + - index_value mac_requirements: get_input: - port_VLC_GTP_mac_requirements - index_value + order: + get_input: + - port_VLC_GTP_order + - index_value + network_role: + get_input: + - port_VLC_GTP_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_GTP_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_GTP_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC2ServiceTemplate.yaml index cb60cfcff3..75b8246a49 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/generalVf/out/Nested_VLC2ServiceTemplate.yaml @@ -11,11 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_VLC_SCTP_A_network: + port_VLC_GTP_exCP_naming: type: list required: true entry_schema: - type: string + type: json port_VLC_OAM_network_role_tag: type: list required: true @@ -49,21 +49,21 @@ topology_template: required: true entry_schema: type: json - port_VLC_OAM_ip_requirements: + port_VLC2_Internal1_network_role_tag: type: list required: true entry_schema: - type: json + type: string port_VLC2_Internal2_mac_address: type: list required: true entry_schema: type: string - port_VLC_OAM_fixed_ips: + port_VLC_GTP_network_role_tag: type: list required: true entry_schema: - type: json + type: string vm_image_name: type: string required: true @@ -82,31 +82,151 @@ topology_template: required: true entry_schema: type: json - port_VLC_SCTP_A_ip_requirements: + port_VLC_SCTP_B_network: + type: list + required: true + entry_schema: + type: string + port_VLC_GTP_network: + type: list + required: true + entry_schema: + type: string + port_VLC2_Internal1_ip_requirements: type: list required: true entry_schema: type: json - port_VLC_SCTP_B_network: + port_VLC_GTP_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_OAM_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_A_network_role_tag: type: list required: true entry_schema: type: string - port_VLC_GTP_network: + port_VLC_GTP_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_GTP_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_VLC_OAM_network: type: list required: true entry_schema: type: string - port_VLC2_Internal1_ip_requirements: + port_VLC2_Internal2_network: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_network: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_A_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_SCTP_B_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_A_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_OAM_fixed_ips: type: list required: true entry_schema: type: json + port_VLC2_Internal1_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC2_Internal2_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_A_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_B_network_role_tag: + type: list + required: true + entry_schema: + type: string compute_VLC2_name: type: list required: true entry_schema: type: string + port_VLC_OAM_order: + type: list + required: true + entry_schema: + type: integer + port_VLC2_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC2_Internal2_network_role: + type: list + required: true + entry_schema: + type: string index_value: type: integer description: Index value of this substitution service template runtime instance @@ -114,11 +234,36 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_VLC_SCTP_B_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC2_Internal2_network_role_tag: + type: list + required: true + entry_schema: + type: string port_VLC_SCTP_B_fixed_ips: type: list required: true entry_schema: type: json + port_VLC_GTP_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_A_network_role: + type: list + required: true + entry_schema: + type: string + port_VLC2_Internal2_order: + type: list + required: true + entry_schema: + type: integer port_VLC_GTP_mac_requirements: type: list required: true @@ -134,7 +279,7 @@ topology_template: required: true entry_schema: type: string - port_VLC_GTP_fixed_ips: + port_VLC2_Internal1_exCP_naming: type: list required: true entry_schema: @@ -144,7 +289,12 @@ topology_template: required: true entry_schema: type: json - port_VLC_OAM_network: + port_VLC2_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC2_Internal2_subnetpoolid: type: list required: true entry_schema: @@ -154,7 +304,32 @@ topology_template: required: true entry_schema: type: json - port_VLC2_Internal2_network: + port_VLC2_Internal2_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_B_order: + type: list + required: true + entry_schema: + type: integer + port_VLC_GTP_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC2_Internal1_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_VLC_SCTP_B_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_VLC_SCTP_B_network_role: type: list required: true entry_schema: @@ -163,14 +338,38 @@ topology_template: VLC2_VLC2_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC2_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC2_Internal2_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC2_Internal2_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC2_Internal2_network_role_tag + - index_value mac_requirements: get_input: - port_VLC2_Internal2_mac_requirements - index_value + order: + get_input: + - port_VLC2_Internal2_order + - index_value + network_role: + get_input: + - port_VLC2_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC2_Internal2_subnetpoolid + - index_value network: get_input: - port_VLC2_Internal2_network @@ -187,6 +386,14 @@ topology_template: VLC2_VLC_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_OAM_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_OAM_ip_requirements @@ -199,6 +406,18 @@ topology_template: get_input: - port_VLC_OAM_mac_requirements - index_value + order: + get_input: + - port_VLC_OAM_order + - index_value + network_role: + get_input: + - port_VLC_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_OAM_fixed_ips @@ -215,14 +434,38 @@ topology_template: VLC2_VLC2_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC2_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC2_Internal1_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC2_Internal1_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC2_Internal1_network_role_tag + - index_value mac_requirements: get_input: - port_VLC2_Internal1_mac_requirements - index_value + order: + get_input: + - port_VLC2_Internal1_order + - index_value + network_role: + get_input: + - port_VLC2_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC2_Internal1_subnetpoolid + - index_value network: get_input: - port_VLC2_Internal1_network @@ -239,14 +482,38 @@ topology_template: VLC2_VLC_SCTP_A: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_SCTP_A_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_SCTP_A_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_SCTP_A_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC_SCTP_A_network_role_tag + - index_value mac_requirements: get_input: - port_VLC_SCTP_A_mac_requirements - index_value + order: + get_input: + - port_VLC_SCTP_A_order + - index_value + network_role: + get_input: + - port_VLC_SCTP_A_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_SCTP_A_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_SCTP_A_fixed_ips @@ -263,14 +530,38 @@ topology_template: VLC2_VLC_SCTP_B: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_SCTP_B_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_SCTP_B_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_SCTP_B_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC_SCTP_B_network_role_tag + - index_value mac_requirements: get_input: - port_VLC_SCTP_B_mac_requirements - index_value + order: + get_input: + - port_VLC_SCTP_B_order + - index_value + network_role: + get_input: + - port_VLC_SCTP_B_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_SCTP_B_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_SCTP_B_fixed_ips @@ -287,14 +578,38 @@ topology_template: VLC2_VLC_GTP: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_VLC_GTP_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_VLC_GTP_vlan_requirements + - index_value ip_requirements: get_input: - port_VLC_GTP_ip_requirements - index_value + network_role_tag: + get_input: + - port_VLC_GTP_network_role_tag + - index_value mac_requirements: get_input: - port_VLC_GTP_mac_requirements - index_value + order: + get_input: + - port_VLC_GTP_order + - index_value + network_role: + get_input: + - port_VLC_GTP_network_role + - index_value + subnetpoolid: + get_input: + - port_VLC_GTP_subnetpoolid + - index_value fixed_ips: get_input: - port_VLC_GTP_fixed_ips diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 07792bad3d..b9579e65a7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -34,10 +34,28 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_flavor_name: type: string required: true status: SUPPORTED + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -50,6 +68,12 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_image_name: type: string required: true @@ -66,6 +90,36 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -78,6 +132,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd02_port_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/Nested_pd_serverServiceTemplate.yaml index 2dc08c62ba..3dce505771 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttIn/out/Nested_pd_serverServiceTemplate.yaml @@ -33,9 +33,24 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json vm_flavor_name: type: string required: true + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -46,6 +61,11 @@ topology_template: required: true entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json vm_image_name: type: string required: true @@ -59,6 +79,31 @@ topology_template: required: true entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true @@ -69,6 +114,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd02_port_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd02_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml index 57acfc92a7..b003fc2638 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -34,10 +34,28 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_flavor_name: type: string required: true status: SUPPORTED + port_pd02_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -50,6 +68,12 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json vm_image_name: type: string required: true @@ -66,12 +90,54 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd02_port_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml index e9f880a804..6d0690a78d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeDiffPortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml @@ -33,9 +33,24 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json vm_flavor_name: type: string required: true + port_pd02_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd02_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd02_port_network_role_tag: type: list required: true @@ -46,6 +61,11 @@ topology_template: required: true entry_schema: type: json + port_pd02_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json vm_image_name: type: string required: true @@ -59,11 +79,46 @@ topology_template: required: true entry_schema: type: string + port_pd02_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd02_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd02_port_ip_requirements: type: list required: true entry_schema: type: json + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd02_port_network: type: list required: true @@ -97,14 +152,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network @@ -117,6 +196,14 @@ topology_template: pd_server_pd02_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd02_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd02_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd02_port_ip_requirements @@ -129,6 +216,18 @@ topology_template: get_input: - port_pd02_port_mac_requirements - index_value + order: + get_input: + - port_pd02_port_order + - index_value + network_role: + get_input: + - port_pd02_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd02_port_subnetpoolid + - index_value network: get_input: - port_pd02_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml index 49604b2074..a308e85feb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -26,6 +26,18 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_0_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -52,26 +64,80 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer vm_flavor_name: type: string required: true status: SUPPORTED + port_pd01_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED + port_pd01_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml index 96061d140c..e2edfa3db1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortTypesAndGetAttOut/out/Nested_pd_serverServiceTemplate.yaml @@ -26,6 +26,16 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_0_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_0_network_role: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -48,22 +58,67 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + entry_schema: + type: integer vm_flavor_name: type: string required: true + port_pd01_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true + port_pd01_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_network: type: list required: true @@ -97,6 +152,14 @@ topology_template: pd_server_pd01_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_1_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_1_ip_requirements @@ -109,6 +172,18 @@ topology_template: get_input: - port_pd01_port_1_mac_requirements - index_value + order: + get_input: + - port_pd01_port_1_order + - index_value + network_role: + get_input: + - port_pd01_port_1_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_1_subnetpoolid + - index_value network: get_input: - port_pd01_port_1_network @@ -121,14 +196,38 @@ topology_template: pd_server_pd01_port_0: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_0_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_0_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_0_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_0_mac_requirements - index_value + order: + get_input: + - port_pd01_port_0_order + - index_value + network_role: + get_input: + - port_pd01_port_0_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_0_subnetpoolid + - index_value network: get_input: - port_pd01_port_0_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index f6ae733527..c9e53c828b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -32,6 +32,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -58,26 +64,80 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer vm_flavor_name: type: string required: true status: SUPPORTED + port_pd01_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED + port_pd01_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml index 88138e2374..9103bf7fa2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/oneComputeSamePortsAndGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml @@ -31,6 +31,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_0_network_role: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -53,22 +58,67 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + entry_schema: + type: integer vm_flavor_name: type: string required: true + port_pd01_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true + port_pd01_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_1_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_1_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_1_mac_requirements - index_value + order: + get_input: + - port_pd01_port_1_order + - index_value + network_role: + get_input: + - port_pd01_port_1_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_1_subnetpoolid + - index_value network: get_input: - port_pd01_port_1_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd01_port_0: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_0_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_0_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd01_port_0_mac_requirements - index_value + order: + get_input: + - port_pd01_port_0_order + - index_value + network_role: + get_input: + - port_pd01_port_0_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_0_subnetpoolid + - index_value network: get_input: - port_pd01_port_0_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml index 380f7bb1dc..2ad9165c79 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -32,6 +32,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_0_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -58,26 +64,80 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer vm_flavor_name: type: string required: true status: SUPPORTED + port_pd01_port_0_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED + port_pd01_port_1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_1_network: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml index d9d82c2f68..0554f63c37 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/samePortTypeAndOutParamGetAttrIn/out/Nested_pd_serverServiceTemplate.yaml @@ -31,6 +31,11 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_0_network_role: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_ip_requirements: type: list required: true @@ -53,22 +58,67 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_1_order: + type: list + required: true + entry_schema: + type: integer vm_flavor_name: type: string required: true + port_pd01_port_0_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_pd01_port_1_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_0_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_1_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_mac_requirements: type: list required: true entry_schema: type: json + port_pd01_port_1_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true + port_pd01_port_1_exCP_naming: + type: list + required: true + entry_schema: + type: json port_pd01_port_1_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_0_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_0_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd01_port_1_network: type: list required: true @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port_1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_1_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_1_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_1_mac_requirements - index_value + order: + get_input: + - port_pd01_port_1_order + - index_value + network_role: + get_input: + - port_pd01_port_1_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_1_subnetpoolid + - index_value network: get_input: - port_pd01_port_1_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd01_port_0: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_0_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_0_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_0_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd01_port_0_mac_requirements - index_value + order: + get_input: + - port_pd01_port_0_order + - index_value + network_role: + get_input: + - port_pd01_port_0_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_0_subnetpoolid + - index_value network: get_input: - port_pd01_port_0_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml index 7c9866a5f0..7d05b9ccc7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,13 +8,49 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_pd01_port_mac_requirements: + compute_pd_server_scheduler_hints: type: list required: true status: SUPPORTED entry_schema: type: json - compute_pd_server_scheduler_hints: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_pd01_port_security_groups: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_mac_requirements: type: list required: true status: SUPPORTED @@ -36,42 +72,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string - required: true - status: SUPPORTED - port_pd01_port_security_groups: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -428,6 +458,30 @@ node_types: org.openecomp.resource.abstract.nodes.oam_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_pd01_port_security_groups: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_mac_requirements: type: list required: true @@ -456,18 +510,18 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_oam_server_user_data_format: type: list required: true @@ -480,18 +534,24 @@ node_types: status: SUPPORTED entry_schema: type: string - port_pd01_port_security_groups: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: - type: json + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_oam_server_scheduler_hints: type: list required: true @@ -843,22 +903,12 @@ node_types: org.openecomp.resource.abstract.nodes.ps_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_pd01_port_mac_requirements: - type: list - required: true - status: SUPPORTED - entry_schema: - type: json compute_ps_server_name: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string - required: true - status: SUPPORTED compute_ps_server_availability_zone: type: list required: true @@ -877,6 +927,40 @@ node_types: status: SUPPORTED entry_schema: type: json + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_pd01_port_security_groups: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_pd01_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED port_pd01_port_ip_requirements: type: list required: true @@ -889,19 +973,31 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list required: true status: SUPPORTED - port_pd01_port_security_groups: + entry_schema: + type: string + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: type: list required: true status: SUPPORTED diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/MainServiceTemplate.yaml index 104d72f82a..21a0a374de 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/MainServiceTemplate.yaml @@ -202,21 +202,8 @@ topology_template: directives: - substitutable properties: - port_pd01_port_mac_requirements: - - mac_count_required: - is_required: false compute_pd_server_scheduler_hints: - group: BE_Affinity_group - vm_image_name: - get_input: pd_image_name - port_pd01_port_ip_requirements: - - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - port_pd01_port_network: - - get_input: oam_net_name compute_pd_server_availability_zone: - get_input: availabilityzone_name compute_pd_server_name: @@ -229,6 +216,19 @@ topology_template: - name port_pd01_port_security_groups: - - jsa_security_group + port_pd01_port_mac_requirements: + - mac_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name + port_pd01_port_ip_requirements: + - - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + port_pd01_port_network: + - get_input: oam_net_name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -251,21 +251,27 @@ topology_template: directives: - substitutable properties: - port_pd01_port_mac_requirements: - - mac_count_required: - is_required: false compute_ps_server_name: - get_input: - ps_server_names - 0 - vm_image_name: - get_input: pd_image_name compute_ps_server_availability_zone: - get_input: availabilityzone_name compute_ps_server_user_data_format: - RAW compute_ps_server_scheduler_hints: - group: BE_Affinity_group + vm_flavor_name: + get_attribute: + - network_policy_server + - name + port_pd01_port_security_groups: + - - jsa_security_group + port_pd01_port_mac_requirements: + - mac_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name port_pd01_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -276,12 +282,6 @@ topology_template: - get_attribute: - network_policy_server - name - vm_flavor_name: - get_attribute: - - network_policy_server - - name - port_pd01_port_security_groups: - - - jsa_security_group service_template_filter: substitute_service_template: Nested_ps_serverServiceTemplate.yaml count: 1 @@ -300,6 +300,12 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_attribute: + - network_policy_server + - name + port_pd01_port_security_groups: + - - jsa_security_group port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -315,18 +321,12 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - vm_flavor_name: - get_attribute: - - network_policy_server - - name compute_oam_server_user_data_format: - RAW compute_oam_server_name: - get_input: - oam_server_names - 0 - port_pd01_port_security_groups: - - - jsa_security_group port_pd01_port_network_role_tag: - oam compute_oam_server_scheduler_hints: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_oam_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_oam_serverServiceTemplate.yaml index e9f9aee10e..4e1b24e7f0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_oam_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_oam_serverServiceTemplate.yaml @@ -11,6 +11,26 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_pd01_port_security_groups: + type: list + required: true + entry_schema: + type: json port_pd01_port_mac_requirements: type: list required: true @@ -34,16 +54,16 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + port_pd01_port_order: + type: list required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_oam_server_user_data_format: type: list required: true @@ -54,16 +74,21 @@ topology_template: required: true entry_schema: type: string - port_pd01_port_security_groups: + port_pd01_port_network_role: type: list required: true entry_schema: - type: json + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_oam_server_scheduler_hints: type: list required: true @@ -77,6 +102,14 @@ topology_template: get_input: - port_pd01_port_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -89,6 +122,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_pd_serverServiceTemplate.yaml index c79dd4cc64..1356fb8878 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_pd_serverServiceTemplate.yaml @@ -11,12 +11,42 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_pd01_port_mac_requirements: + compute_pd_server_scheduler_hints: type: list required: true entry_schema: type: json - compute_pd_server_scheduler_hints: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_pd01_port_security_groups: + type: list + required: true + entry_schema: + type: json + port_pd01_port_mac_requirements: type: list required: true entry_schema: @@ -34,36 +64,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true - port_pd01_port_security_groups: + port_pd01_port_network_role: type: list required: true entry_schema: - type: json + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -100,6 +125,14 @@ topology_template: get_input: - port_pd01_port_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -112,6 +145,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_ps_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_ps_serverServiceTemplate.yaml index b2c48a9534..f408bad2cc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_ps_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithAllConnectivities/out/Nested_ps_serverServiceTemplate.yaml @@ -11,19 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_pd01_port_mac_requirements: - type: list - required: true - entry_schema: - type: json compute_ps_server_name: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true compute_ps_server_availability_zone: type: list required: true @@ -39,16 +31,6 @@ topology_template: required: true entry_schema: type: json - port_pd01_port_ip_requirements: - type: list - required: true - entry_schema: - type: json - port_pd01_port_network: - type: list - required: true - entry_schema: - type: string index_value: type: integer description: Index value of this substitution service template runtime instance @@ -56,6 +38,11 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json vm_flavor_name: type: string required: true @@ -64,6 +51,49 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true + port_pd01_port_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_pd01_port_network: + type: list + required: true + entry_schema: + type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json node_templates: ps_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port @@ -72,14 +102,38 @@ topology_template: get_input: - port_pd01_port_security_groups - index_value + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml index d4a4f2e671..85ccd9d77a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -405,6 +435,24 @@ node_types: org.openecomp.resource.abstract.nodes.oam_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -433,18 +481,18 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_oam_server_user_data_format: type: list required: true @@ -457,12 +505,24 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json requirements: - dependency_oam_server_pd01_port: capability: tosca.capabilities.Node @@ -802,34 +862,52 @@ node_types: org.openecomp.resource.abstract.nodes.ps_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_pd01_port_mac_requirements: + compute_ps_server_name: type: list required: true status: SUPPORTED entry_schema: - type: json - compute_ps_server_name: + type: string + compute_ps_server_availability_zone: type: list required: true status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + compute_ps_server_user_data_format: + type: list required: true status: SUPPORTED - compute_ps_server_availability_zone: + entry_schema: + type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_ps_server_user_data_format: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_pd01_port_mac_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string + type: json + vm_image_name: + type: string + required: true + status: SUPPORTED port_pd01_port_ip_requirements: type: list required: true @@ -842,18 +920,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json requirements: - dependency_ps_server_pd01_port: capability: tosca.capabilities.Node diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/MainServiceTemplate.yaml index 1e96f5cadd..4a0ccad45d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/MainServiceTemplate.yaml @@ -175,6 +175,16 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -188,16 +198,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_attribute: - - network_policy_server - - name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -215,19 +215,23 @@ topology_template: directives: - substitutable properties: - port_pd01_port_mac_requirements: - - mac_count_required: - is_required: false compute_ps_server_name: - get_input: - ps_server_names - 0 - vm_image_name: - get_input: pd_image_name compute_ps_server_availability_zone: - get_input: availabilityzone_name compute_ps_server_user_data_format: - RAW + vm_flavor_name: + get_attribute: + - network_policy_server + - name + port_pd01_port_mac_requirements: + - mac_count_required: + is_required: false + vm_image_name: + get_input: pd_image_name port_pd01_port_ip_requirements: - - ip_version: 4 ip_count_required: @@ -238,10 +242,6 @@ topology_template: - get_attribute: - network_policy_server - name - vm_flavor_name: - get_attribute: - - network_policy_server - - name service_template_filter: substitute_service_template: Nested_ps_serverServiceTemplate.yaml count: 1 @@ -255,6 +255,10 @@ topology_template: directives: - substitutable properties: + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -270,10 +274,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - vm_flavor_name: - get_attribute: - - network_policy_server - - name compute_oam_server_user_data_format: - RAW compute_oam_server_name: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_oam_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_oam_serverServiceTemplate.yaml index 999882d584..9a034c3803 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_oam_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_oam_serverServiceTemplate.yaml @@ -11,6 +11,21 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -34,16 +49,16 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + port_pd01_port_order: + type: list required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_oam_server_user_data_format: type: list required: true @@ -54,15 +69,33 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json node_templates: oam_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -75,6 +108,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_pd_serverServiceTemplate.yaml index 74044a11c2..dd358a5dd2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_ps_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_ps_serverServiceTemplate.yaml index 9b747c547e..8ccfbad0a7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_ps_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeDiffComputesWithPorts/out/Nested_ps_serverServiceTemplate.yaml @@ -11,19 +11,11 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_pd01_port_mac_requirements: - type: list - required: true - entry_schema: - type: json compute_ps_server_name: type: list required: true entry_schema: type: string - vm_image_name: - type: string - required: true compute_ps_server_availability_zone: type: list required: true @@ -34,6 +26,29 @@ topology_template: required: true entry_schema: type: string + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_pd01_port_mac_requirements: + type: list + required: true + entry_schema: + type: json + vm_image_name: + type: string + required: true port_pd01_port_ip_requirements: type: list required: true @@ -44,28 +59,67 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - vm_flavor_name: - type: string + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_pd01_port_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json node_templates: ps_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/GlobalSubstitutionTypesServiceTemplate.yaml index 1bf05aa17e..13e08cc899 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -24,30 +54,36 @@ node_types: status: SUPPORTED entry_schema: type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list required: true status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -393,6 +429,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -409,30 +475,36 @@ node_types: status: SUPPORTED entry_schema: type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list required: true status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -778,6 +850,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -800,36 +902,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/MainServiceTemplate.yaml index 3fab6b6130..6eec7d894d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/MainServiceTemplate.yaml @@ -190,6 +190,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 2 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -203,14 +211,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 2 - vm_flavor_name: - get_input: pd_flavor_name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -233,6 +233,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -244,14 +252,6 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: @@ -267,6 +267,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -278,14 +286,6 @@ topology_template: is_required: false floating_ip_count_required: is_required: false - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_input: pd_flavor_name compute_pd_server_user_data_format: - RAW service_template_filter: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_0ServiceTemplate.yaml index a0614d3393..2ca7b3c25f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_0ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -24,26 +49,31 @@ topology_template: required: true entry_schema: type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -72,14 +102,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_attribute: - pd_server diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_1ServiceTemplate.yaml index c32b489666..445fc6df88 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_1ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -24,26 +49,31 @@ topology_template: required: true entry_schema: type: json - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -72,14 +102,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_attribute: - pd_server diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_2ServiceTemplate.yaml index 1b487934d1..08e5895c0e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeNovaSameTypeWithGetAttrFromPort/out/Nested_pd_server_2ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml index 4f96bcd484..c5923cc46b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_0: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -405,6 +435,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -427,30 +487,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 + port_pd01_port_order: + type: list + required: true status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -796,6 +862,24 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server_2: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + port_pd01_port_2_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_pd01_port_3_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_3_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer index_value: type: integer description: Index value of this substitution service template runtime instance @@ -804,6 +888,12 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_pd01_port_2_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_availability_zone: type: list required: true @@ -844,22 +934,52 @@ node_types: status: SUPPORTED entry_schema: type: string + port_pd01_port_2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_2_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string vm_image_name: type: string required: true status: SUPPORTED + port_pd01_port_3_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_pd01_port_2_network: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_3_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_2_mac_requirements: type: list required: true status: SUPPORTED entry_schema: type: json + port_pd01_port_2_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_pd01_port_3_network_role_tag: type: list required: true @@ -878,6 +998,12 @@ node_types: status: SUPPORTED entry_schema: type: json + port_pd01_port_3_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json requirements: - dependency_pd_server: capability: tosca.capabilities.Node diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/MainServiceTemplate.yaml index 393fbdc37a..873c04ebec 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/MainServiceTemplate.yaml @@ -233,6 +233,16 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 1 + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -246,16 +256,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 1 - vm_flavor_name: - get_attribute: - - network_policy_server - - name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -273,6 +273,16 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_attribute: + - network_policy_server + - name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -288,16 +298,6 @@ topology_template: - get_attribute: - network_policy_server - name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_attribute: - - network_policy_server - - name compute_pd_server_user_data_format: - RAW service_template_filter: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_0ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_0ServiceTemplate.yaml index b6c4036c6d..6a96d70747 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_0ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_0ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_1ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_1ServiceTemplate.yaml index a0da89fcd1..1efd8dcca0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_1ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_1ServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,26 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - compute_pd_server_name: + port_pd01_port_network_role: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_pd01_port_vlan_requirements: + type: list required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -77,14 +107,38 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements - index_value + network_role_tag: + get_input: + - port_pd01_port_network_role_tag + - index_value mac_requirements: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_2ServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_2ServiceTemplate.yaml index f9becc9b4a..fd95fdc3fe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_2ServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/threeSameComputesNoConsolidation/out/Nested_pd_server_2ServiceTemplate.yaml @@ -11,6 +11,21 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + port_pd01_port_2_order: + type: list + required: true + entry_schema: + type: integer + port_pd01_port_3_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_3_order: + type: list + required: true + entry_schema: + type: integer index_value: type: integer description: Index value of this substitution service template runtime instance @@ -18,6 +33,11 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_pd01_port_2_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_availability_zone: type: list required: true @@ -51,19 +71,44 @@ topology_template: required: true entry_schema: type: string + port_pd01_port_2_network_role: + type: list + required: true + entry_schema: + type: string + port_pd01_port_2_subnetpoolid: + type: list + required: true + entry_schema: + type: string vm_image_name: type: string required: true + port_pd01_port_3_subnetpoolid: + type: list + required: true + entry_schema: + type: string port_pd01_port_2_network: type: list required: true entry_schema: type: string + port_pd01_port_3_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_pd01_port_2_mac_requirements: type: list required: true entry_schema: type: json + port_pd01_port_2_exCP_naming: + type: list + required: true + entry_schema: + type: json port_pd01_port_3_network_role_tag: type: list required: true @@ -79,6 +124,11 @@ topology_template: required: true entry_schema: type: json + port_pd01_port_3_exCP_naming: + type: list + required: true + entry_schema: + type: json node_templates: pd_server: type: org.openecomp.resource.vfc.nodes.heat.pd_server @@ -102,6 +152,14 @@ topology_template: pd_server_pd01_port_2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_2_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_2_ip_requirements @@ -114,6 +172,18 @@ topology_template: get_input: - port_pd01_port_2_mac_requirements - index_value + order: + get_input: + - port_pd01_port_2_order + - index_value + network_role: + get_input: + - port_pd01_port_2_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_2_subnetpoolid + - index_value network: get_input: - port_pd01_port_2_network @@ -126,6 +196,14 @@ topology_template: pd_server_pd01_port_3: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_3_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_3_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_3_ip_requirements @@ -138,6 +216,18 @@ topology_template: get_input: - port_pd01_port_3_mac_requirements - index_value + order: + get_input: + - port_pd01_port_3_order + - index_value + network_role: + get_input: + - port_pd01_port_3_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_3_subnetpoolid + - index_value network: get_input: - port_pd01_port_3_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml index 63f9c558e7..fb56d43c41 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -417,10 +447,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -441,22 +473,44 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_ps01_port_mac_requirements: + port_ps01_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_ps01_port_network: + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_ps01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: + type: integer + vm_image_name: type: string required: true status: SUPPORTED + port_ps01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_ps01_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_ps01_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_ps01_port_ip_requirements: type: list required: true @@ -469,6 +523,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_ps01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json attributes: ps_server_accessIPv4: type: list diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/MainServiceTemplate.yaml index 2848946b96..f8c0769307 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/MainServiceTemplate.yaml @@ -355,6 +355,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -370,14 +378,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_input: pd_flavor_name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -399,21 +399,21 @@ topology_template: - get_input: - ps_server_names - 0 - vm_image_name: - get_attribute: - - abstract_pd_server - - pd_server_accessIPv4 compute_ps_server_availability_zone: - get_input: availabilityzone_name compute_ps_server_user_data_format: - RAW + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_attribute: + - abstract_pd_server + - pd_server_accessIPv4 port_ps01_port_mac_requirements: - mac_count_required: is_required: false port_ps01_port_network: - get_input: oam_net_name - vm_flavor_name: - get_input: pd_flavor_name port_ps01_port_ip_requirements: - - ip_version: 4 ip_count_required: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_pd_serverServiceTemplate.yaml index 245fee1136..ad0a81d4dc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_ps_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_ps_serverServiceTemplate.yaml index f889b1a55b..d92309c5c3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_ps_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoComputesWithGetAttrBetweenThem/out/Nested_ps_serverServiceTemplate.yaml @@ -16,9 +16,11 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -36,6 +38,27 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_ps01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_ps01_port_order: + type: list + required: true + entry_schema: + type: integer + vm_image_name: + type: string + required: true + port_ps01_port_network_role: + type: list + required: true + entry_schema: + type: string port_ps01_port_mac_requirements: type: list required: true @@ -46,9 +69,6 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true port_ps01_port_ip_requirements: type: list required: true @@ -59,6 +79,11 @@ topology_template: required: true entry_schema: type: string + port_ps01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json node_templates: ps_server: type: org.openecomp.resource.vfc.nodes.heat.ps_server @@ -82,6 +107,14 @@ topology_template: ps_server_ps01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_ps01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_ps01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_ps01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_ps01_port_mac_requirements - index_value + order: + get_input: + - port_ps01_port_order + - index_value + network_role: + get_input: + - port_ps01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_ps01_port_subnetpoolid + - index_value network: get_input: - port_ps01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/GlobalSubstitutionTypesServiceTemplate.yaml index a674d6bf46..2ef83fec70 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,6 +8,36 @@ node_types: org.openecomp.resource.abstract.nodes.pd_server: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + status: SUPPORTED + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED port_pd01_port_mac_requirements: type: list required: true @@ -30,36 +60,36 @@ node_types: status: SUPPORTED entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - status: SUPPORTED - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true status: SUPPORTED + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true status: SUPPORTED entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -411,10 +441,12 @@ node_types: status: SUPPORTED entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true status: SUPPORTED + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -435,22 +467,44 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_ps01_port_mac_requirements: + port_ps01_port_vlan_requirements: type: list required: true status: SUPPORTED entry_schema: type: json - port_ps01_port_network: + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_ps01_port_order: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: + type: integer + vm_image_name: type: string required: true status: SUPPORTED + port_ps01_port_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_ps01_port_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_ps01_port_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string port_ps01_port_ip_requirements: type: list required: true @@ -463,6 +517,12 @@ node_types: status: SUPPORTED entry_schema: type: string + port_ps01_port_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json requirements: - dependency_ps_server: capability: tosca.capabilities.Node diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/MainServiceTemplate.yaml index bbbd7dadd3..645929f408 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/MainServiceTemplate.yaml @@ -355,6 +355,14 @@ topology_template: directives: - substitutable properties: + compute_pd_server_availability_zone: + - get_input: availabilityzone_name + compute_pd_server_name: + - get_input: + - pd_server_names + - 0 + vm_flavor_name: + get_input: pd_flavor_name port_pd01_port_mac_requirements: - mac_count_required: is_required: false @@ -368,14 +376,6 @@ topology_template: is_required: false port_pd01_port_network: - get_input: oam_net_name - compute_pd_server_availability_zone: - - get_input: availabilityzone_name - compute_pd_server_name: - - get_input: - - pd_server_names - - 0 - vm_flavor_name: - get_input: pd_flavor_name port_pd01_port_network_role_tag: - oam compute_pd_server_user_data_format: @@ -397,19 +397,19 @@ topology_template: - get_input: - ps_server_names - 0 - vm_image_name: - get_input: pd_image_name compute_ps_server_availability_zone: - get_input: availabilityzone_name compute_ps_server_user_data_format: - RAW + vm_flavor_name: + get_input: pd_flavor_name + vm_image_name: + get_input: pd_image_name port_ps01_port_mac_requirements: - mac_count_required: is_required: false port_ps01_port_network: - get_input: oam_net_name - vm_flavor_name: - get_input: pd_flavor_name port_ps01_port_ip_requirements: - - ip_version: 4 ip_count_required: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_pd_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_pd_serverServiceTemplate.yaml index 74044a11c2..dd358a5dd2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_pd_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_pd_serverServiceTemplate.yaml @@ -11,6 +11,31 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: + index_value: + type: integer + description: Index value of this substitution service template runtime instance + required: false + default: 0 + constraints: + - greater_or_equal: 0 + compute_pd_server_availability_zone: + type: list + required: true + entry_schema: + type: string + compute_pd_server_name: + type: list + required: true + entry_schema: + type: string + port_pd01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true port_pd01_port_mac_requirements: type: list required: true @@ -29,31 +54,31 @@ topology_template: required: true entry_schema: type: string - index_value: - type: integer - description: Index value of this substitution service template runtime instance - required: false - default: 0 - constraints: - - greater_or_equal: 0 - compute_pd_server_availability_zone: + port_pd01_port_order: type: list required: true entry_schema: - type: string - compute_pd_server_name: + type: integer + port_pd01_port_subnetpoolid: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_pd01_port_network_role: + type: list required: true + entry_schema: + type: string port_pd01_port_network_role_tag: type: list required: true entry_schema: type: string + port_pd01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json compute_pd_server_user_data_format: type: list required: true @@ -82,6 +107,14 @@ topology_template: pd_server_pd01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_pd01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_pd01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_pd01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_pd01_port_mac_requirements - index_value + order: + get_input: + - port_pd01_port_order + - index_value + network_role: + get_input: + - port_pd01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_pd01_port_subnetpoolid + - index_value network: get_input: - port_pd01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_ps_serverServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_ps_serverServiceTemplate.yaml index 5baa4a45ff..c16b51c98d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_ps_serverServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/fulltest/singleSubstitution/twoSetsOfSingle/out/Nested_ps_serverServiceTemplate.yaml @@ -16,9 +16,11 @@ topology_template: required: true entry_schema: type: string - vm_image_name: - type: string + port_ps01_port_subnetpoolid: + type: list required: true + entry_schema: + type: string compute_ps_server_availability_zone: type: list required: true @@ -36,6 +38,27 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_ps01_port_vlan_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_ps01_port_order: + type: list + required: true + entry_schema: + type: integer + vm_image_name: + type: string + required: true + port_ps01_port_network_role: + type: list + required: true + entry_schema: + type: string port_ps01_port_mac_requirements: type: list required: true @@ -46,9 +69,6 @@ topology_template: required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true port_ps01_port_ip_requirements: type: list required: true @@ -59,6 +79,11 @@ topology_template: required: true entry_schema: type: string + port_ps01_port_exCP_naming: + type: list + required: true + entry_schema: + type: json node_templates: ps_server: type: org.openecomp.resource.vfc.nodes.heat.ps_server @@ -82,6 +107,14 @@ topology_template: ps_server_ps01_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_ps01_port_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_ps01_port_vlan_requirements + - index_value ip_requirements: get_input: - port_ps01_port_ip_requirements @@ -94,6 +127,18 @@ topology_template: get_input: - port_ps01_port_mac_requirements - index_value + order: + get_input: + - port_ps01_port_order + - index_value + network_role: + get_input: + - port_ps01_port_network_role + - index_value + subnetpoolid: + get_input: + - port_ps01_port_subnetpoolid + - index_value network: get_input: - port_ps01_port_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/getAttr/getAttrOnlyResourceName/expectedoutputfiles/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/getAttr/getAttrOnlyResourceName/expectedoutputfiles/MainServiceTemplate.yaml index 5d5f46e5fe..ec7134b1e0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/getAttr/getAttrOnlyResourceName/expectedoutputfiles/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/getAttr/getAttrOnlyResourceName/expectedoutputfiles/MainServiceTemplate.yaml @@ -326,7 +326,6 @@ topology_template: - sub_interface_vlan_tag - mac - port_tuple_refs - - virtual_machine_intefrace_mac_addresses - ip_prefix - address_mode - mac_address @@ -337,6 +336,7 @@ topology_template: - virtual_network_refs - virtual_machine_interface_properties - virtual_machine_interface_allowed_address_pairs + - virtual_machine_interface_mac_addresses groups: ep-jsa_net_group: type: org.openecomp.groups.heat.HeatStack diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEAdd_On_Module_QRouterTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEAdd_On_Module_QRouterTemplate.yaml index aae1455919..758276fe18 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEAdd_On_Module_QRouterTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEAdd_On_Module_QRouterTemplate.yaml @@ -62,7 +62,7 @@ parameters: vnf_id: type: string resources: - QRouter: + QRouter1: properties: availability_zone: get_param: availability_zone_0 @@ -178,7 +178,7 @@ resources: qrouter_volume_0_att: properties: instance_uuid: - get_resource: QRouter + get_resource: QRouter1 volume_id: get_resource: qrouter_volume_0 type: OS::Cinder::VolumeAttachment @@ -194,7 +194,7 @@ resources: qrouter_volume_1_att: properties: instance_uuid: - get_resource: QRouter + get_resource: QRouter1 volume_id: get_resource: qrouter_volume_1 type: OS::Cinder::VolumeAttachment @@ -210,7 +210,7 @@ resources: qrouter_volume_2_att: properties: instance_uuid: - get_resource: QRouter + get_resource: QRouter1 volume_id: get_resource: qrouter_volume_2 type: OS::Cinder::VolumeAttachment \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEBase_Module.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEBase_Module.yaml index 5d0a5457ca..331737e599 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEBase_Module.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/inputfiles/FEBase_Module.yaml @@ -269,7 +269,7 @@ parameters: description: Windows servers' domain type: string resources: - QRouter: + QRouter0: depends_on: - security_group - packet_mirror_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/FEAdd_On_Module_QRouterTemplateServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/FEAdd_On_Module_QRouterTemplateServiceTemplate.yaml index ce5bddcbb4..ca861cbfc0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/FEAdd_On_Module_QRouterTemplateServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/FEAdd_On_Module_QRouterTemplateServiceTemplate.yaml @@ -134,7 +134,52 @@ topology_template: immutable: false type: string node_templates: - QRouter: + qrouter_volume_1: + type: org.openecomp.resource.vfc.nodes.heat.cinder.Volume + properties: + volume_type: + get_input: qrouter_volume_type_1 + size: '(get_input : qrouter_volume_size_1) * 1024' + description: + get_input: qrouter_volume_name_1 + qrouter_volume_0: + type: org.openecomp.resource.vfc.nodes.heat.cinder.Volume + properties: + volume_type: + get_input: qrouter_volume_type_0 + size: '(get_input : qrouter_volume_size_0) * 1024' + description: + get_input: qrouter_volume_name_0 + cdr_network_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + properties: + ip_requirements: + - ip_version: 4 + ip_count_required: + is_required: false + floating_ip_count_required: + is_required: false + security_groups: + - get_input: security_group + mac_requirements: + mac_count_required: + is_required: false + network: + get_input: cdr_network + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: QRouter1 + relationship: tosca.relationships.network.BindsTo + qrouter_volume_2: + type: org.openecomp.resource.vfc.nodes.heat.cinder.Volume + properties: + volume_type: + get_input: qrouter_volume_type_2 + size: '(get_input : qrouter_volume_size_2) * 1024' + description: + get_input: qrouter_volume_name_2 + QRouter1: type: org.openecomp.resource.vfc.nodes.heat.qrouter properties: flavor: @@ -230,51 +275,6 @@ topology_template: register_status: type: tosca.artifacts.Deployment file: ../Artifacts/register_status.py - qrouter_volume_1: - type: org.openecomp.resource.vfc.nodes.heat.cinder.Volume - properties: - volume_type: - get_input: qrouter_volume_type_1 - size: '(get_input : qrouter_volume_size_1) * 1024' - description: - get_input: qrouter_volume_name_1 - qrouter_volume_0: - type: org.openecomp.resource.vfc.nodes.heat.cinder.Volume - properties: - volume_type: - get_input: qrouter_volume_type_0 - size: '(get_input : qrouter_volume_size_0) * 1024' - description: - get_input: qrouter_volume_name_0 - cdr_network_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - properties: - ip_requirements: - - ip_version: 4 - ip_count_required: - is_required: false - floating_ip_count_required: - is_required: false - security_groups: - - get_input: security_group - mac_requirements: - mac_count_required: - is_required: false - network: - get_input: cdr_network - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: QRouter - relationship: tosca.relationships.network.BindsTo - qrouter_volume_2: - type: org.openecomp.resource.vfc.nodes.heat.cinder.Volume - properties: - volume_type: - get_input: qrouter_volume_type_2 - size: '(get_input : qrouter_volume_size_2) * 1024' - description: - get_input: qrouter_volume_name_2 oam_private_net_network_port: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: @@ -295,78 +295,66 @@ topology_template: requirements: - binding: capability: tosca.capabilities.network.Bindable - node: QRouter + node: QRouter1 relationship: tosca.relationships.network.BindsTo relationship_templates: qrouter_volume_0_att: type: org.openecomp.relationships.VolumeAttachesTo properties: volume_id: qrouter_volume_0 - instance_uuid: QRouter + instance_uuid: QRouter1 qrouter_volume_2_att: type: org.openecomp.relationships.VolumeAttachesTo properties: volume_id: qrouter_volume_2 - instance_uuid: QRouter + instance_uuid: QRouter1 qrouter_volume_1_att: type: org.openecomp.relationships.VolumeAttachesTo properties: volume_id: qrouter_volume_1 - instance_uuid: QRouter + instance_uuid: QRouter1 groups: FEAdd_On_Module_QRouterTemplate_group: type: org.openecomp.groups.heat.HeatStack properties: heat_file: ../Artifacts/FEAdd_On_Module_QRouterTemplate.yaml members: - - QRouter - qrouter_volume_1 - qrouter_volume_0 - cdr_network_port - qrouter_volume_2 + - QRouter1 - oam_private_net_network_port substitution_mappings: node_type: org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_QRouterTemplate capabilities: - disk.usage_QRouter: - - QRouter - - disk.usage network.outgoing.bytes_cdr_network_port: - cdr_network_port - network.outgoing.bytes - disk.write.bytes_QRouter: - - QRouter - - disk.write.bytes + binding_QRouter1: + - QRouter1 + - binding attachment_oam_private_net_network_port: - oam_private_net_network_port - attachment feature_qrouter_volume_1: - qrouter_volume_1 - feature - disk.device.write.bytes_QRouter: - - QRouter - - disk.device.write.bytes feature_qrouter_volume_2: - qrouter_volume_2 - feature - endpoint_QRouter: - - QRouter - - endpoint feature_qrouter_volume_0: - qrouter_volume_0 - feature attachment_qrouter_volume_2: - qrouter_volume_2 - attachment - disk.capacity_QRouter: - - QRouter - - disk.capacity + cpu_util_QRouter1: + - QRouter1 + - cpu_util attachment_qrouter_volume_0: - qrouter_volume_0 - attachment - disk.read.bytes.rate_QRouter: - - QRouter - - disk.read.bytes.rate attachment_qrouter_volume_1: - qrouter_volume_1 - attachment @@ -376,172 +364,181 @@ topology_template: network.incoming.packets_cdr_network_port: - cdr_network_port - network.incoming.packets + disk.device.read.bytes.rate_QRouter1: + - QRouter1 + - disk.device.read.bytes.rate network.outgoing.bytes.rate_oam_private_net_network_port: - oam_private_net_network_port - network.outgoing.bytes.rate - instance_QRouter: - - QRouter - - instance - disk.device.latency_QRouter: - - QRouter - - disk.device.latency - disk.device.usage_QRouter: - - QRouter - - disk.device.usage - disk.ephemeral.size_QRouter: - - QRouter - - disk.ephemeral.size - disk.device.iops_QRouter: - - QRouter - - disk.device.iops + disk.device.read.bytes_QRouter1: + - QRouter1 + - disk.device.read.bytes network.outpoing.packets_oam_private_net_network_port: - oam_private_net_network_port - network.outpoing.packets network.outpoing.packets_cdr_network_port: - cdr_network_port - network.outpoing.packets - disk.device.read.bytes_QRouter: - - QRouter - - disk.device.read.bytes - disk.iops_QRouter: - - QRouter - - disk.iops + memory.resident_QRouter1: + - QRouter1 + - memory.resident + disk.device.latency_QRouter1: + - QRouter1 + - disk.device.latency + host_QRouter1: + - QRouter1 + - host feature_cdr_network_port: - cdr_network_port - feature - disk.device.read.requests.rate_QRouter: - - QRouter - - disk.device.read.requests.rate - disk.read.bytes_QRouter: - - QRouter - - disk.read.bytes - memory.resident_QRouter: - - QRouter - - memory.resident - host_QRouter: - - QRouter - - host + disk.device.write.bytes.rate_QRouter1: + - QRouter1 + - disk.device.write.bytes.rate + disk.device.usage_QRouter1: + - QRouter1 + - disk.device.usage network.incoming.bytes_cdr_network_port: - cdr_network_port - network.incoming.bytes - memory_QRouter: - - QRouter - - memory - disk.device.read.requests_QRouter: - - QRouter - - disk.device.read.requests - scalable_QRouter: - - QRouter - - scalable - os_QRouter: - - QRouter - - os + instance_QRouter1: + - QRouter1 + - instance + disk.root.size_QRouter1: + - QRouter1 + - disk.root.size + vcpus_QRouter1: + - QRouter1 + - vcpus network.incoming.bytes_oam_private_net_network_port: - oam_private_net_network_port - network.incoming.bytes - disk.write.bytes.rate_QRouter: - - QRouter - - disk.write.bytes.rate feature_oam_private_net_network_port: - oam_private_net_network_port - feature - cpu_util_QRouter: - - QRouter - - cpu_util + cpu.delta_QRouter1: + - QRouter1 + - cpu.delta + disk.capacity_QRouter1: + - QRouter1 + - disk.capacity + memory.usage_QRouter1: + - QRouter1 + - memory.usage + disk.write.requests.rate_QRouter1: + - QRouter1 + - disk.write.requests.rate + disk.read.requests_QRouter1: + - QRouter1 + - disk.read.requests + feature_QRouter1: + - QRouter1 + - feature network.incoming.bytes.rate_oam_private_net_network_port: - oam_private_net_network_port - network.incoming.bytes.rate - disk.device.write.requests_QRouter: - - QRouter - - disk.device.write.requests - disk.device.read.bytes.rate_QRouter: - - QRouter - - disk.device.read.bytes.rate + disk.ephemeral.size_QRouter1: + - QRouter1 + - disk.ephemeral.size + disk.latency_QRouter1: + - QRouter1 + - disk.latency + disk.device.capacity_QRouter1: + - QRouter1 + - disk.device.capacity network.incoming.bytes.rate_cdr_network_port: - cdr_network_port - network.incoming.bytes.rate - disk.device.allocation_QRouter: - - QRouter - - disk.device.allocation network.outgoing.bytes_oam_private_net_network_port: - oam_private_net_network_port - network.outgoing.bytes - disk.device.capacity_QRouter: - - QRouter - - disk.device.capacity - feature_QRouter: - - QRouter - - feature - disk.read.requests_QRouter: - - QRouter - - disk.read.requests - disk.device.write.bytes.rate_QRouter: - - QRouter - - disk.device.write.bytes.rate - disk.write.requests_QRouter: - - QRouter - - disk.write.requests - disk.root.size_QRouter: - - QRouter - - disk.root.size - memory.usage_QRouter: - - QRouter - - memory.usage + disk.iops_QRouter1: + - QRouter1 + - disk.iops + disk.device.write.requests_QRouter1: + - QRouter1 + - disk.device.write.requests + disk.device.write.requests.rate_QRouter1: + - QRouter1 + - disk.device.write.requests.rate + disk.device.allocation_QRouter1: + - QRouter1 + - disk.device.allocation + memory_QRouter1: + - QRouter1 + - memory + disk.usage_QRouter1: + - QRouter1 + - disk.usage + scalable_QRouter1: + - QRouter1 + - scalable network.outgoing.bytes.rate_cdr_network_port: - cdr_network_port - network.outgoing.bytes.rate binding_oam_private_net_network_port: - oam_private_net_network_port - binding - cpu_QRouter: - - QRouter - - cpu - vcpus_QRouter: - - QRouter - - vcpus - disk.allocation_QRouter: - - QRouter - - disk.allocation network.incoming.packets.rate_cdr_network_port: - cdr_network_port - network.incoming.packets.rate + disk.write.bytes_QRouter1: + - QRouter1 + - disk.write.bytes + disk.write.requests_QRouter1: + - QRouter1 + - disk.write.requests network.incoming.packets_oam_private_net_network_port: - oam_private_net_network_port - network.incoming.packets + cpu_QRouter1: + - QRouter1 + - cpu + os_QRouter1: + - QRouter1 + - os + disk.device.read.requests.rate_QRouter1: + - QRouter1 + - disk.device.read.requests.rate network.incoming.packets.rate_oam_private_net_network_port: - oam_private_net_network_port - network.incoming.packets.rate - disk.device.write.requests.rate_QRouter: - - QRouter - - disk.device.write.requests.rate - cpu.delta_QRouter: - - QRouter - - cpu.delta - binding_QRouter: - - QRouter - - binding + disk.read.bytes_QRouter1: + - QRouter1 + - disk.read.bytes binding_cdr_network_port: - cdr_network_port - binding + disk.write.bytes.rate_QRouter1: + - QRouter1 + - disk.write.bytes.rate + disk.device.write.bytes_QRouter1: + - QRouter1 + - disk.device.write.bytes network.outgoing.packets.rate_cdr_network_port: - cdr_network_port - network.outgoing.packets.rate - disk.latency_QRouter: - - QRouter - - disk.latency - disk.write.requests.rate_QRouter: - - QRouter - - disk.write.requests.rate + disk.device.iops_QRouter1: + - QRouter1 + - disk.device.iops + disk.read.bytes.rate_QRouter1: + - QRouter1 + - disk.read.bytes.rate + endpoint_QRouter1: + - QRouter1 + - endpoint + disk.allocation_QRouter1: + - QRouter1 + - disk.allocation + disk.device.read.requests_QRouter1: + - QRouter1 + - disk.device.read.requests network.outgoing.packets.rate_oam_private_net_network_port: - oam_private_net_network_port - network.outgoing.packets.rate requirements: - local_storage_QRouter: - - QRouter + local_storage_QRouter1: + - QRouter1 - local_storage - dependency_QRouter: - - QRouter - - dependency dependency_qrouter_volume_1: - qrouter_volume_1 - dependency @@ -562,4 +559,7 @@ topology_template: - dependency link_cdr_network_port: - cdr_network_port - - link \ No newline at end of file + - link + dependency_QRouter1: + - QRouter1 + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/GlobalSubstitutionTypesServiceTemplate.yaml index 4d7aa4f012..86de04a96c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -131,20 +131,6 @@ node_types: required: true status: SUPPORTED requirements: - - dependency_QRouter: - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - occurrences: - - 0 - - UNBOUNDED - - local_storage_QRouter: - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - occurrences: - - 0 - - UNBOUNDED - dependency_qrouter_volume_1: capability: tosca.capabilities.Node node: tosca.nodes.Root @@ -179,6 +165,20 @@ node_types: occurrences: - 0 - UNBOUNDED + - dependency_QRouter1: + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: + - 0 + - UNBOUNDED + - local_storage_QRouter1: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: + - 0 + - UNBOUNDED - dependency_oam_private_net_network_port: capability: tosca.capabilities.Node node: tosca.nodes.Root @@ -193,21 +193,14 @@ node_types: - 1 - 1 capabilities: - disk.usage_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED network.outgoing.bytes_cdr_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + binding_QRouter1: + type: tosca.capabilities.network.Bindable occurrences: - 1 - UNBOUNDED @@ -221,22 +214,11 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.device.write.bytes_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED feature_qrouter_volume_2: type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - endpoint_QRouter: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED feature_qrouter_volume_0: type: tosca.capabilities.Node occurrences: @@ -247,7 +229,7 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.capacity_QRouter: + cpu_util_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -258,12 +240,6 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.read.bytes.rate_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. - occurrences: - - 1 - - UNBOUNDED attachment_qrouter_volume_1: type: tosca.capabilities.Attachment occurrences: @@ -280,160 +256,161 @@ node_types: occurrences: - 1 - UNBOUNDED - network.outgoing.bytes.rate_oam_private_net_network_port: + disk.device.read.bytes.rate_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - instance_QRouter: + network.outgoing.bytes.rate_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.latency_QRouter: + disk.device.read.bytes_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.usage_QRouter: + network.outpoing.packets_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.ephemeral.size_QRouter: + network.outpoing.packets_cdr_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.iops_QRouter: + memory.resident_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outpoing.packets_oam_private_net_network_port: + disk.device.latency_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outpoing.packets_cdr_network_port: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + host_QRouter1: + type: tosca.capabilities.Container + valid_source_types: + - tosca.nodes.SoftwareComponent occurrences: - 1 - UNBOUNDED - disk.device.read.bytes_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + feature_cdr_network_port: + type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - disk.iops_QRouter: + disk.device.write.bytes.rate_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - feature_cdr_network_port: - type: tosca.capabilities.Node + disk.device.usage_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.requests.rate_QRouter: + network.incoming.bytes_cdr_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.read.bytes_QRouter: + instance_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory.resident_QRouter: + disk.root.size_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - host_QRouter: - type: tosca.capabilities.Container - valid_source_types: - - tosca.nodes.SoftwareComponent + vcpus_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes_cdr_network_port: + network.incoming.bytes_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + feature_oam_private_net_network_port: + type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - disk.device.read.requests_QRouter: + cpu.delta_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - scalable_QRouter: - type: tosca.capabilities.Scalable + disk.capacity_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - os_QRouter: - type: tosca.capabilities.OperatingSystem + memory.usage_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes_oam_private_net_network_port: + disk.write.requests.rate_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes.rate_QRouter: + disk.read.requests_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - feature_oam_private_net_network_port: + feature_QRouter1: type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - cpu_util_QRouter: + network.incoming.bytes.rate_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes.rate_oam_private_net_network_port: + disk.ephemeral.size_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.requests_QRouter: + disk.latency_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.bytes.rate_QRouter: + disk.device.capacity_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -445,56 +422,50 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.device.allocation_QRouter: + network.outgoing.bytes_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outgoing.bytes_oam_private_net_network_port: + disk.iops_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.capacity_QRouter: + disk.device.write.requests_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - feature_QRouter: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - disk.read.requests_QRouter: + disk.device.write.requests.rate_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.bytes.rate_QRouter: + disk.device.allocation_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests_QRouter: + memory_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.root.size_QRouter: + disk.usage_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory.usage_QRouter: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + scalable_QRouter1: + type: tosca.capabilities.Scalable occurrences: - 1 - UNBOUNDED @@ -511,56 +482,56 @@ node_types: occurrences: - 0 - UNBOUNDED - cpu_QRouter: + network.incoming.packets.rate_cdr_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - vcpus_QRouter: + disk.write.bytes_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.allocation_QRouter: + disk.write.requests_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.packets.rate_cdr_network_port: + network.incoming.packets_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.packets_oam_private_net_network_port: + cpu_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.packets.rate_oam_private_net_network_port: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + os_QRouter1: + type: tosca.capabilities.OperatingSystem occurrences: - 1 - UNBOUNDED - disk.device.write.requests.rate_QRouter: + disk.device.read.requests.rate_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu.delta_QRouter: + network.incoming.packets.rate_oam_private_net_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - binding_QRouter: - type: tosca.capabilities.network.Bindable + disk.read.bytes_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED @@ -571,19 +542,48 @@ node_types: occurrences: - 0 - UNBOUNDED + disk.write.bytes.rate_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.device.write.bytes_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED network.outgoing.packets.rate_cdr_network_port: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.latency_QRouter: + disk.device.iops_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes.rate_QRouter1: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + occurrences: + - 1 + - UNBOUNDED + endpoint_QRouter1: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + disk.allocation_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests.rate_QRouter: + disk.device.read.requests_QRouter1: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/MainServiceTemplate.yaml index b6e1ec9cd6..7d2364e084 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/securityrulestoportconnection/securityRulesToPortGetResource/out/MainServiceTemplate.yaml @@ -733,91 +733,6 @@ topology_template: capability: tosca.capabilities.Node node: packet_internal_network relationship: tosca.relationships.DependsOn - QRouter: - type: org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_QRouterTemplate - directives: - - substitutable - properties: - vf_module_id: - get_input: vf_module_id - qrouter_cluster_name: - get_input: qrouter_cluster_name - oam_private_net_name: - get_input: oam_private_net_name - qrouter_flavor_name: - get_input: qrouter_flavor_name - version_number: - get_input: version_number - vf_module_name: - get_input: vf_module_name - service_template_filter: - substitute_service_template: FEAdd_On_Module_QRouterTemplateServiceTemplate.yaml - domain_name: - get_input: domain_name - ntp_timezone: - get_input: ntp_timezone - vnf_id: - get_input: vnf_id - availability_zone_0: - get_input: availability_zone_0 - region_name: - get_input: region_name - manager_name_0: - get_input: manager_name_0 - qrouter_names: - get_input: qrouter_names - tenant_name: - get_input: tenant_name - security_group: security_group - cdr_network: - get_input: cdr_network - qrouter_image_name: - get_input: base_image_name - qrouter_volume_type_1: - get_input: qrouter_volume_type_1 - qrouter_volume_type_2: - get_input: qrouter_volume_type_2 - qrouter_node_count: - get_input: qrouter_node_count - qrouter_volume_name_2: - get_input: qrouter_volume_name_2 - qrouter_volume_name_1: - get_input: qrouter_volume_name_1 - qrouter_volume_name_0: - get_input: qrouter_volume_name_0 - qrouter_volume_type_0: - get_input: qrouter_volume_type_0 - qrouter_volume_size_0: - get_input: qrouter_volume_size_0 - qrouter_volume_size_1: - get_input: qrouter_volume_size_1 - manager_oam_direct_ip_0: - get_input: manager_oam_direct_ip_0 - qrouter_volume_size_2: - get_input: qrouter_volume_size_2 - rpmrepository_ip_0: - get_input: rpmrepository_ip_0 - requirements: - - dependency: - capability: tosca.capabilities.Node - node: security_group - relationship: tosca.relationships.DependsOn - - dependency: - capability: tosca.capabilities.Node - node: packet_mirror_network - relationship: tosca.relationships.DependsOn - - dependency: - capability: tosca.capabilities.Node - node: packet_mirror_network - relationship: tosca.relationships.DependsOn - - dependency: - capability: tosca.capabilities.Node - node: packet_internal_network - relationship: tosca.relationships.DependsOn - - dependency: - capability: tosca.capabilities.Node - node: packet_internal_network - relationship: tosca.relationships.DependsOn packet_mirror_network: type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net properties: @@ -915,11 +830,11 @@ topology_template: requirements: - port: capability: attachment_oam_private_net_network_port - node: QRouter + node: QRouter0 relationship: org.openecomp.relationships.AttachesTo - port: capability: attachment_cdr_network_port - node: QRouter + node: QRouter0 relationship: org.openecomp.relationships.AttachesTo - port: capability: attachment_oam_private_net_network_port @@ -957,6 +872,91 @@ topology_template: capability: attachment_packet_internal_network_port node: vProbe relationship: org.openecomp.relationships.AttachesTo + QRouter0: + type: org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_QRouterTemplate + directives: + - substitutable + properties: + vf_module_id: + get_input: vf_module_id + qrouter_cluster_name: + get_input: qrouter_cluster_name + oam_private_net_name: + get_input: oam_private_net_name + qrouter_flavor_name: + get_input: qrouter_flavor_name + version_number: + get_input: version_number + vf_module_name: + get_input: vf_module_name + service_template_filter: + substitute_service_template: FEAdd_On_Module_QRouterTemplateServiceTemplate.yaml + domain_name: + get_input: domain_name + ntp_timezone: + get_input: ntp_timezone + vnf_id: + get_input: vnf_id + availability_zone_0: + get_input: availability_zone_0 + region_name: + get_input: region_name + manager_name_0: + get_input: manager_name_0 + qrouter_names: + get_input: qrouter_names + tenant_name: + get_input: tenant_name + security_group: security_group + cdr_network: + get_input: cdr_network + qrouter_image_name: + get_input: base_image_name + qrouter_volume_type_1: + get_input: qrouter_volume_type_1 + qrouter_volume_type_2: + get_input: qrouter_volume_type_2 + qrouter_node_count: + get_input: qrouter_node_count + qrouter_volume_name_2: + get_input: qrouter_volume_name_2 + qrouter_volume_name_1: + get_input: qrouter_volume_name_1 + qrouter_volume_name_0: + get_input: qrouter_volume_name_0 + qrouter_volume_type_0: + get_input: qrouter_volume_type_0 + qrouter_volume_size_0: + get_input: qrouter_volume_size_0 + qrouter_volume_size_1: + get_input: qrouter_volume_size_1 + manager_oam_direct_ip_0: + get_input: manager_oam_direct_ip_0 + qrouter_volume_size_2: + get_input: qrouter_volume_size_2 + rpmrepository_ip_0: + get_input: rpmrepository_ip_0 + requirements: + - dependency: + capability: tosca.capabilities.Node + node: security_group + relationship: tosca.relationships.DependsOn + - dependency: + capability: tosca.capabilities.Node + node: packet_mirror_network + relationship: tosca.relationships.DependsOn + - dependency: + capability: tosca.capabilities.Node + node: packet_mirror_network + relationship: tosca.relationships.DependsOn + - dependency: + capability: tosca.capabilities.Node + node: packet_internal_network + relationship: tosca.relationships.DependsOn + - dependency: + capability: tosca.capabilities.Node + node: packet_internal_network + relationship: tosca.relationships.DependsOn vLB: type: org.openecomp.resource.abstract.nodes.heat.FEAdd_On_Module_vLBTemplate directives: @@ -1062,8 +1062,8 @@ topology_template: members: - vLBAgent - vProbe - - QRouter - packet_mirror_network - packet_internal_network - security_group + - QRouter0 - vLB \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/GlobalSubstitutionTypesServiceTemplate.yaml index 9159c8b742..13cccd38b7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -14,12 +14,166 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB_OAM_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_FSB1_metadata: type: list required: true status: SUPPORTED entry_schema: type: json + port_FSB2_Internal2_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal2_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal2_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal1_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal2_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal2_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal2_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_FSB1_availability_zone: type: list required: true @@ -40,47 +194,85 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_FSB_OAM_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer port_FSB2_Internal2_network: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_FSB2_Internal2_vlan_requirements: + type: list required: true status: SUPPORTED - port_FSB2_Internal1_mac_address: + entry_schema: + type: json + port_FSB2_Internal1_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal2_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string + port_FSB1_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal1_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal1_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_FSB_OAM_fixed_ips: type: list required: true status: SUPPORTED entry_schema: type: json - compute_FSB1_name: + port_FSB2_Internal2_order: type: list required: true status: SUPPORTED entry_schema: - type: string - port_FSB_OAM_network: + type: integer + port_FSB2_Internal1_subnetpoolid: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB2_Internal1_network: + port_FSB1_Internal_mac_requirements: type: list required: true status: SUPPORTED entry_schema: - type: string - port_FSB2_Internal2_mac_address: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_FSB1_name: type: list required: true status: SUPPORTED @@ -655,4 +847,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/SubstitutionServiceTemplate.yaml index 3fd981df0e..ac5e7b1360 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoOutParamDuplicatePortType/out/SubstitutionServiceTemplate.yaml @@ -16,11 +16,139 @@ topology_template: required: true entry_schema: type: string + port_FSB_OAM_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_FSB1_metadata: type: list required: true entry_schema: type: json + port_FSB2_Internal2_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_exCP_naming: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal2_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal2_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal1_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_network: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal2_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal2_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal2_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_mac_requirements: + type: list + required: true + entry_schema: + type: json compute_FSB1_availability_zone: type: list required: true @@ -38,40 +166,72 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_FSB_OAM_order: + type: list + required: true + entry_schema: + type: integer port_FSB2_Internal2_network: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_FSB2_Internal2_vlan_requirements: + type: list required: true - port_FSB2_Internal1_mac_address: + entry_schema: + type: json + port_FSB2_Internal1_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal2_subnetpoolid: type: list required: true entry_schema: type: string + port_FSB1_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal1_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal1_mac_requirements: + type: list + required: true + entry_schema: + type: json port_FSB_OAM_fixed_ips: type: list required: true entry_schema: type: json - compute_FSB1_name: + port_FSB2_Internal2_order: type: list required: true entry_schema: - type: string - port_FSB_OAM_network: + type: integer + port_FSB2_Internal1_subnetpoolid: type: list required: true entry_schema: type: string - port_FSB2_Internal1_network: + port_FSB1_Internal_mac_requirements: type: list required: true entry_schema: - type: string - port_FSB2_Internal2_mac_address: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + entry_schema: + type: json + compute_FSB1_name: type: list required: true entry_schema: @@ -80,6 +240,38 @@ topology_template: FSB1_FSB1_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB1_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB1_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB1_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB1_Internal_order + - index_value + network_role: + get_input: + - port_FSB1_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal_network @@ -96,6 +288,38 @@ topology_template: FSB1_FSB_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB_OAM_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB_OAM_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB_OAM_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB_OAM_mac_requirements + - index_value + order: + get_input: + - port_FSB_OAM_order + - index_value + network_role: + get_input: + - port_FSB_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_FSB_OAM_fixed_ips @@ -112,6 +336,38 @@ topology_template: FSB1_FSB2_Internal2: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal2_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal2_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal2_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal2_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal2_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal2_order + - index_value + network_role: + get_input: + - port_FSB2_Internal2_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal2_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal2_network @@ -152,6 +408,38 @@ topology_template: FSB1_FSB2_Internal1: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal1_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal1_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal1_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal1_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal1_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal1_order + - index_value + network_role: + get_input: + - port_FSB2_Internal1_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal1_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal1_network diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml index 916359eb88..78f448ce6f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -295,4 +295,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/SubstitutionServiceTemplate.yaml index 7c322d53fd..96a3a66c4e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/NoPorts/out/SubstitutionServiceTemplate.yaml @@ -193,4 +193,4 @@ topology_template: - dependency local_storage_FSB1: - FSB1 - - local_storage + - local_storage \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/GlobalSubstitutionTypesServiceTemplate.yaml index d570a37afb..dda1f4295d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -14,13 +14,119 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB_OAM_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_FSB1_metadata: type: list required: true status: SUPPORTED entry_schema: type: json - port_FSB_OAM_fixed_ips: + port_FSB2_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_mac_requirements: type: list required: true status: SUPPORTED @@ -46,29 +152,67 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB_OAM_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - compute_FSB1_name: + port_FSB2_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB_OAM_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_mac_requirements: + type: list required: true status: SUPPORTED - port_FSB2_Internal_mac_address: + entry_schema: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_FSB1_name: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB_OAM_network: + port_FSB2_Internal_network_role_tag: type: list required: true status: SUPPORTED @@ -565,4 +709,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/SubstitutionServiceTemplate.yaml index 58ea943973..76dbaad388 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithIndex/out/SubstitutionServiceTemplate.yaml @@ -16,12 +16,100 @@ topology_template: required: true entry_schema: type: string + port_FSB_OAM_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_FSB1_metadata: type: list required: true entry_schema: type: json - port_FSB_OAM_fixed_ips: + port_FSB2_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_mac_requirements: type: list required: true entry_schema: @@ -43,25 +131,57 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB_OAM_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_mac_address: type: list required: true entry_schema: type: string - compute_FSB1_name: + port_FSB2_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB_OAM_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_mac_requirements: + type: list required: true - port_FSB2_Internal_mac_address: + entry_schema: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + entry_schema: + type: json + compute_FSB1_name: type: list required: true entry_schema: type: string - port_FSB_OAM_network: + port_FSB2_Internal_network_role_tag: type: list required: true entry_schema: @@ -70,6 +190,38 @@ topology_template: FSB1_FSB1_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB1_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB1_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB1_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB1_Internal_order + - index_value + network_role: + get_input: + - port_FSB1_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal_network @@ -86,6 +238,38 @@ topology_template: FSB1_FSB2_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal_order + - index_value + network_role: + get_input: + - port_FSB2_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal_network @@ -102,6 +286,38 @@ topology_template: FSB1_FSB_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB_OAM_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB_OAM_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB_OAM_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB_OAM_mac_requirements + - index_value + order: + get_input: + - port_FSB_OAM_order + - index_value + network_role: + get_input: + - port_FSB_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_FSB_OAM_fixed_ips @@ -388,4 +604,4 @@ topology_template: - link dependency_FSB1_FSB2_Internal: - FSB1_FSB2_Internal - - dependency + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml index 6183e8703e..e2581559d2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -14,12 +14,82 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_FSB1_metadata: type: list required: true status: SUPPORTED entry_schema: type: json + port_FSB2_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB2_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_FSB1_availability_zone: type: list required: true @@ -40,23 +110,49 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB2_Internal_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - compute_FSB1_name: + port_FSB2_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_network: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_mac_requirements: + type: list required: true status: SUPPORTED - port_FSB2_Internal_mac_address: + entry_schema: + type: json + compute_FSB1_name: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal_network_role_tag: type: list required: true status: SUPPORTED @@ -516,4 +612,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/SubstitutionServiceTemplate.yaml index 07c6c2528b..adc80eaf7a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/consolidation/out/SubstitutionServiceTemplate.yaml @@ -16,11 +16,69 @@ topology_template: required: true entry_schema: type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_FSB1_metadata: type: list required: true entry_schema: type: json + port_FSB2_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB2_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_network_role: + type: list + required: true + entry_schema: + type: string compute_FSB1_availability_zone: type: list required: true @@ -38,20 +96,42 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_FSB2_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + entry_schema: + type: integer port_FSB2_Internal_network: type: list required: true entry_schema: type: string + port_FSB1_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json compute_FSB1_name: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string - required: true - port_FSB2_Internal_mac_address: + port_FSB2_Internal_network_role_tag: type: list required: true entry_schema: @@ -60,6 +140,38 @@ topology_template: FSB1_FSB1_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB1_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB1_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB1_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB1_Internal_order + - index_value + network_role: + get_input: + - port_FSB1_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal_network @@ -76,6 +188,38 @@ topology_template: FSB1_FSB2_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal_order + - index_value + network_role: + get_input: + - port_FSB2_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal_network @@ -388,4 +532,4 @@ topology_template: - local_storage dependency_FSB1_FSB2_Internal: - FSB1_FSB2_Internal - - dependency + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml index bf0af32231..40048e44db 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -14,13 +14,119 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB_OAM_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_FSB1_metadata: type: list required: true status: SUPPORTED entry_schema: type: json - port_FSB_OAM_fixed_ips: + port_FSB2_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_mac_requirements: type: list required: true status: SUPPORTED @@ -46,29 +152,67 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB_OAM_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - compute_FSB1_name: + port_FSB2_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB_OAM_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_mac_requirements: + type: list required: true status: SUPPORTED - port_FSB2_Internal_mac_address: + entry_schema: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + compute_FSB1_name: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB_OAM_network: + port_FSB2_Internal_network_role_tag: type: list required: true status: SUPPORTED @@ -601,4 +745,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/SubstitutionServiceTemplate.yaml index b20af41093..4faca73a16 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/WithOutputParameters/noConsolidation/out/SubstitutionServiceTemplate.yaml @@ -16,12 +16,100 @@ topology_template: required: true entry_schema: type: string + port_FSB_OAM_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_FSB1_metadata: type: list required: true entry_schema: type: json - port_FSB_OAM_fixed_ips: + port_FSB2_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_mac_requirements: type: list required: true entry_schema: @@ -43,25 +131,57 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB_OAM_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_mac_address: type: list required: true entry_schema: type: string - compute_FSB1_name: + port_FSB2_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB_OAM_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_mac_requirements: + type: list required: true - port_FSB2_Internal_mac_address: + entry_schema: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + entry_schema: + type: json + compute_FSB1_name: type: list required: true entry_schema: type: string - port_FSB_OAM_network: + port_FSB2_Internal_network_role_tag: type: list required: true entry_schema: @@ -70,6 +190,38 @@ topology_template: FSB1_FSB1_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB1_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB1_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB1_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB1_Internal_order + - index_value + network_role: + get_input: + - port_FSB1_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal_network @@ -86,6 +238,38 @@ topology_template: FSB1_FSB2_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal_order + - index_value + network_role: + get_input: + - port_FSB2_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal_network @@ -102,6 +286,38 @@ topology_template: FSB1_FSB_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB_OAM_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB_OAM_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB_OAM_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB_OAM_mac_requirements + - index_value + order: + get_input: + - port_FSB_OAM_order + - index_value + network_role: + get_input: + - port_FSB_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_FSB_OAM_fixed_ips @@ -445,4 +661,4 @@ topology_template: - link dependency_FSB1_FSB2_Internal: - FSB1_FSB2_Internal - - dependency + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml index 6772f8c594..84bab83d19 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -14,12 +14,36 @@ node_types: status: SUPPORTED entry_schema: type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string compute_FSB1_metadata: type: list required: true status: SUPPORTED entry_schema: type: json + port_FSB2_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer compute_FSB1_availability_zone: type: list required: true @@ -34,23 +58,95 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 + port_FSB2_Internal_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB2_Internal_mac_address: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB1_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json port_FSB2_Internal_network: type: list required: true status: SUPPORTED entry_schema: type: string + port_FSB2_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json compute_FSB1_name: type: list required: true status: SUPPORTED entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_exCP_naming: + type: list required: true status: SUPPORTED - port_FSB2_Internal_mac_address: + entry_schema: + type: json + port_FSB1_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal_network_role_tag: type: list required: true status: SUPPORTED @@ -510,4 +606,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/SubstitutionServiceTemplate.yaml index 4c5d4ae924..cb7a4127a1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/consolidation/out/SubstitutionServiceTemplate.yaml @@ -16,11 +16,31 @@ topology_template: required: true entry_schema: type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string compute_FSB1_metadata: type: list required: true entry_schema: type: json + port_FSB2_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + entry_schema: + type: integer compute_FSB1_availability_zone: type: list required: true @@ -33,20 +53,80 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 + port_FSB2_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB2_Internal_mac_address: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB1_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json port_FSB2_Internal_network: type: list required: true entry_schema: type: string + port_FSB2_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json compute_FSB1_name: type: list required: true entry_schema: type: string - vm_flavor_name: - type: string + port_FSB1_Internal_exCP_naming: + type: list required: true - port_FSB2_Internal_mac_address: + entry_schema: + type: json + port_FSB1_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal_network_role_tag: type: list required: true entry_schema: @@ -55,6 +135,38 @@ topology_template: FSB1_FSB1_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB1_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB1_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB1_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB1_Internal_order + - index_value + network_role: + get_input: + - port_FSB1_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal_subnetpoolid + - index_value network: get_attribute: - FSB1_FSB2_Internal @@ -71,6 +183,38 @@ topology_template: FSB1_FSB2_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal_order + - index_value + network_role: + get_input: + - port_FSB2_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal_subnetpoolid + - index_value device_id: get_attribute: - FSB1 @@ -387,4 +531,4 @@ topology_template: - local_storage dependency_FSB1_FSB2_Internal: - FSB1_FSB2_Internal - - dependency + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml index f1d1182772..b9a448541a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -8,7 +8,113 @@ node_types: org.openecomp.resource.abstract.nodes.FSB1: derived_from: org.openecomp.resource.abstract.nodes.VFC properties: - port_FSB_OAM_fixed_ips: + port_FSB_OAM_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB2_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + status: SUPPORTED + port_FSB_OAM_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB_OAM_mac_requirements: type: list required: true status: SUPPORTED @@ -28,23 +134,61 @@ node_types: status: SUPPORTED constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB_OAM_order: type: list required: true status: SUPPORTED entry_schema: - type: string - vm_flavor_name: - type: string + type: integer + port_FSB2_Internal_mac_requirements: + type: list required: true status: SUPPORTED + entry_schema: + type: json port_FSB2_Internal_mac_address: type: list required: true status: SUPPORTED entry_schema: type: string - port_FSB_OAM_network: + port_FSB2_Internal_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + status: SUPPORTED + entry_schema: + type: integer + port_FSB_OAM_fixed_ips: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network: + type: list + required: true + status: SUPPORTED + entry_schema: + type: string + port_FSB1_Internal_mac_requirements: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + status: SUPPORTED + entry_schema: + type: json + port_FSB2_Internal_network_role_tag: type: list required: true status: SUPPORTED @@ -577,4 +721,4 @@ node_types: description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - - UNBOUNDED + - UNBOUNDED \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/SubstitutionServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/SubstitutionServiceTemplate.yaml index 3ef8780d7e..6cd3625e82 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/SubstitutionServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/creSubstitutionServiceTemplate/updNodesGetAttrInFromInnerNodes/noConsolidation/out/SubstitutionServiceTemplate.yaml @@ -11,7 +11,95 @@ node_types: derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server topology_template: inputs: - port_FSB_OAM_fixed_ips: + port_FSB_OAM_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB2_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB2_Internal_ip_requirements: + type: list + required: true + entry_schema: + type: json + vm_flavor_name: + type: string + required: true + port_FSB_OAM_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_ip_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_network_role_tag: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_vlan_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_network: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_network_role: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_subnetpoolid: + type: list + required: true + entry_schema: + type: string + port_FSB_OAM_mac_requirements: type: list required: true entry_schema: @@ -28,20 +116,52 @@ topology_template: default: 0 constraints: - greater_or_equal: 0 - port_FSB2_Internal_network: + port_FSB_OAM_order: type: list required: true entry_schema: - type: string - vm_flavor_name: - type: string + type: integer + port_FSB2_Internal_mac_requirements: + type: list required: true + entry_schema: + type: json port_FSB2_Internal_mac_address: type: list required: true entry_schema: type: string - port_FSB_OAM_network: + port_FSB2_Internal_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB1_Internal_order: + type: list + required: true + entry_schema: + type: integer + port_FSB_OAM_fixed_ips: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network: + type: list + required: true + entry_schema: + type: string + port_FSB1_Internal_mac_requirements: + type: list + required: true + entry_schema: + type: json + port_FSB_OAM_exCP_naming: + type: list + required: true + entry_schema: + type: json + port_FSB2_Internal_network_role_tag: type: list required: true entry_schema: @@ -50,6 +170,38 @@ topology_template: FSB1_FSB1_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB1_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB1_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB1_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB1_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB1_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB1_Internal_order + - index_value + network_role: + get_input: + - port_FSB1_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB1_Internal_subnetpoolid + - index_value network: get_input: - port_FSB1_Internal_network @@ -66,6 +218,38 @@ topology_template: FSB1_FSB2_Internal: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB2_Internal_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB2_Internal_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB2_Internal_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB2_Internal_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB2_Internal_mac_requirements + - index_value + order: + get_input: + - port_FSB2_Internal_order + - index_value + network_role: + get_input: + - port_FSB2_Internal_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB2_Internal_subnetpoolid + - index_value network: get_input: - port_FSB2_Internal_network @@ -82,6 +266,38 @@ topology_template: FSB1_FSB_OAM: type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port properties: + exCP_naming: + get_input: + - port_FSB_OAM_exCP_naming + - index_value + vlan_requirements: + get_input: + - port_FSB_OAM_vlan_requirements + - index_value + ip_requirements: + get_input: + - port_FSB_OAM_ip_requirements + - index_value + network_role_tag: + get_input: + - port_FSB_OAM_network_role_tag + - index_value + mac_requirements: + get_input: + - port_FSB_OAM_mac_requirements + - index_value + order: + get_input: + - port_FSB_OAM_order + - index_value + network_role: + get_input: + - port_FSB_OAM_network_role + - index_value + subnetpoolid: + get_input: + - port_FSB_OAM_subnetpoolid + - index_value fixed_ips: get_input: - port_FSB_OAM_fixed_ips @@ -420,4 +636,4 @@ topology_template: - link dependency_FSB1_FSB2_Internal: - FSB1_FSB2_Internal - - dependency + - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsDiffType/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsDiffType/out/MainServiceTemplate.yaml index b441d659c0..ac134c31c5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsDiffType/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsDiffType/out/MainServiceTemplate.yaml @@ -181,16 +181,18 @@ topology_template: properties: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - port_FSB1_Internal_network: - - Internal1-net vm_flavor_name: get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb1-Internal2-mac vm_image_name: get_input: fsb-image compute_FSB_admin_pass: - STATIC-DATA-FSB1 + port_FSB_OAM_network: + - jsa_net1 + port_FSB1_Internal_network: + - Internal1-net + port_FSB2_Internal_mac_address: + - get_input: fsb1-Internal2-mac port_FSB_OAM_fixed_ips: - - ip_address: get_input: fsb1-oam-ip @@ -202,8 +204,6 @@ topology_template: - path: /path2/etc/sysconfig/network-scripts/ifcfg-eth1 compute_FSB_availability_zone: - get_input: fsb1_zone - port_FSB_OAM_network: - - jsa_net1 compute_FSB_name: - get_input: fsb1-name service_template_filter: @@ -225,4 +225,4 @@ topology_template: - FSB2_Internal2 - FSB1_Internal1 - FSB1_OAM - - FSB1_template + - FSB1_template \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsSameType/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsSameType/out/MainServiceTemplate.yaml index e2adb3038b..8bb81bc2fa 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsSameType/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/oneComputeMultiplePortsSameType/out/MainServiceTemplate.yaml @@ -162,22 +162,22 @@ topology_template: - get_input: fsb1-Internal1-mac port_FSB1_Internal2_network: - Internal2-net + port_FSB1_Internal1_network: + - Internal1-net + vm_flavor_name: + get_input: fsb-flavor + port_FSB1_Internal2_mac_address: + - get_input: fsb1-Internal2-mac vm_image_name: get_input: fsb-image compute_FSB_admin_pass: - STATIC-DATA-FSB1 - port_FSB1_Internal1_network: - - Internal1-net compute_FSB_metadata: - write_files: - path: /path1/etc/sysconfig/network-scripts/ifcfg-eth0 - path: /path2/etc/sysconfig/network-scripts/ifcfg-eth1 compute_FSB_availability_zone: - get_input: fsb1_zone - vm_flavor_name: - get_input: fsb-flavor - port_FSB1_Internal2_mac_address: - - get_input: fsb1-Internal2-mac compute_FSB_name: - get_input: fsb1-name service_template_filter: @@ -198,4 +198,4 @@ topology_template: members: - FSB1_Internal2 - FSB1_Internal1 - - FSB1_template + - FSB1_template \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/twoComputesMultiplePorts/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/twoComputesMultiplePorts/out/MainServiceTemplate.yaml index ce35a8ed2a..92fc5bdb6e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/twoComputesMultiplePorts/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/createAbstractSubstitute/twoComputesMultiplePorts/out/MainServiceTemplate.yaml @@ -243,6 +243,11 @@ topology_template: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - get_input: fsb1-Internal2-mac + compute_FSB_user_data: + - OPTIONAL-DATA-FSB1 + - null + vm_flavor_name: + get_input: fsb-flavor vm_image_name: get_input: fsb-image compute_FSB_admin_pass: @@ -251,6 +256,9 @@ topology_template: port_FSB1_Internal_network: - Internal1-net-fsb1-Internal1 - Internal1-net-fsb1-Internal2 + port_FSB2_Internal_mac_address: + - get_input: fsb2-Internal1-mac + - get_input: fsb2-Internal2-mac port_FSB2_Internal_network: - Internal2-net-fsb2-Internal1 - Internal2-net-fsb2-Internal2 @@ -261,17 +269,9 @@ topology_template: - write_files: - path: /path3/etc/sysconfig/network-scripts/ifcfg-eth0 - path: /path4/etc/sysconfig/network-scripts/ifcfg-eth1 - compute_FSB_user_data: - - OPTIONAL-DATA-FSB1 - - null compute_FSB_availability_zone: - get_input: fsb1_zone - get_input: fsb2_zone - vm_flavor_name: - get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb2-Internal1-mac - - get_input: fsb2-Internal2-mac compute_FSB_name: - get_input: fsb1-name - get_input: fsb2-name @@ -296,4 +296,4 @@ topology_template: - FSB2_Internal1 - FSB2_Internal2 - FSB1_template - - FSB2_template + - FSB2_template \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/pattern1b/noConsolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/pattern1b/noConsolidation/out/MainServiceTemplate.yaml index 773801f9fa..209d729be8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/pattern1b/noConsolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/pattern1b/noConsolidation/out/MainServiceTemplate.yaml @@ -148,12 +148,12 @@ topology_template: - get_input: fsb_zone port_FSB1_Internal_network: - Internal1-net - port_FSB2_Internal_network: - - Internal2-net vm_flavor_name: get_input: fsb1-flavor port_FSB2_Internal_mac_address: - get_input: fsb1-Internal2-mac + port_FSB2_Internal_network: + - Internal2-net service_template_filter: substitute_service_template: Nested_FSB1_0ServiceTemplate.yaml count: 1 @@ -291,4 +291,4 @@ topology_template: - abstract_FSB1_0 - FSB1_FSB1_Internal_accessIPv6 - 0 - - OS-EXT-IPS-MAC:mac_addr + - OS-EXT-IPS-MAC:mac_addr \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/consolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/consolidation/out/MainServiceTemplate.yaml index f8872c5a9d..492e64573c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/consolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/consolidation/out/MainServiceTemplate.yaml @@ -240,6 +240,11 @@ topology_template: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - get_input: fsb1-Internal2-mac + compute_FSB_user_data: + - STATIC-DATA-FSB1 + - STATIC-DATA-FSB2 + vm_flavor_name: + get_input: fsb-flavor vm_image_name: get_input: fsb-image compute_FSB_admin_pass: @@ -248,6 +253,9 @@ topology_template: port_FSB1_Internal_network: - Internal1-net-fsb1-Internal1 - Internal1-net-fsb1-Internal2 + port_FSB2_Internal_mac_address: + - get_input: fsb2-Internal1-mac + - get_input: fsb2-Internal2-mac port_FSB2_Internal_network: - Internal2-net-fsb2-Internal1 - Internal2-net-fsb2-Internal2 @@ -258,17 +266,9 @@ topology_template: - write_files: - path: /path3/etc/sysconfig/network-scripts/ifcfg-eth0 - path: /path4/etc/sysconfig/network-scripts/ifcfg-eth1 - compute_FSB_user_data: - - STATIC-DATA-FSB1 - - STATIC-DATA-FSB2 compute_FSB_availability_zone: - get_input: fsb1_zone - get_input: fsb2_zone - vm_flavor_name: - get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb2-Internal1-mac - - get_input: fsb2-Internal2-mac compute_FSB_name: - get_input: fsb1-name - get_input: fsb2-name @@ -317,4 +317,4 @@ topology_template: - FSB2_template - jsa_net - jsa_net1 - - packet_mirror_network_name + - packet_mirror_network_name \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/noConsolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/noConsolidation/out/MainServiceTemplate.yaml index af3ef63b0f..ce8bde09d3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/noConsolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updGroupsConnectivity/noConsolidation/out/MainServiceTemplate.yaml @@ -98,30 +98,30 @@ topology_template: directives: - substitutable properties: - port_port2_network: - - get_input: port_name + compute_smp_availability_zone: + - get_input: availability_zone_0 + vm_flavor_name: + get_input: flavor_smp_name + compute_smp_user_data_format: + - RAW vm_image_name: get_input: image_smp_name port_port2_replacement_policy: - AUTO compute_smp_name: - get_input: smp_name_1 - compute_smp_availability_zone: - - get_input: availability_zone_0 port_port1_replacement_policy: - AUTO port_port1_network: - get_input: port_name - vm_flavor_name: - get_input: flavor_smp_name + port_port2_network: + - get_input: port_name compute_smp_metadata: - jx_vm_role: smp2 vnf_id: get_input: vnf_id jx_lab_name: get_input: lab_name - compute_smp_user_data_format: - - RAW compute_smp_scheduler_hints: - group: BE_Affinity_group service_template_filter: @@ -164,4 +164,4 @@ topology_template: name: abc affinity: host targets: - - FE_SMP_Affinity_group + - FE_SMP_Affinity_group \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/consolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/consolidation/out/MainServiceTemplate.yaml index b98c6e07bb..b7bb7cbb43 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/consolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/consolidation/out/MainServiceTemplate.yaml @@ -253,6 +253,11 @@ topology_template: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - get_input: fsb1-Internal2-mac + compute_FSB_user_data: + - OPTIONAL-DATA-FSB1 + - null + vm_flavor_name: + get_input: fsb-flavor vm_image_name: get_input: fsb-image compute_FSB_admin_pass: @@ -261,6 +266,9 @@ topology_template: port_FSB1_Internal_network: - Internal1-net-fsb1-Internal1 - Internal1-net-fsb1-Internal2 + port_FSB2_Internal_mac_address: + - get_input: fsb2-Internal1-mac + - get_input: fsb2-Internal2-mac port_FSB2_Internal_network: - Internal2-net-fsb2-Internal1 - Internal2-net-fsb2-Internal2 @@ -271,17 +279,9 @@ topology_template: - write_files: - path: /path3/etc/sysconfig/network-scripts/ifcfg-eth0 - path: /path4/etc/sysconfig/network-scripts/ifcfg-eth1 - compute_FSB_user_data: - - OPTIONAL-DATA-FSB1 - - null compute_FSB_availability_zone: - get_input: fsb1_zone - get_input: fsb2_zone - vm_flavor_name: - get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb2-Internal1-mac - - get_input: fsb2-Internal2-mac compute_FSB_name: - get_input: fsb1-name - get_input: fsb2-name @@ -319,4 +319,4 @@ topology_template: - jsa_net - jsa_net1 - packet_mirror_network - - jsa_security_group + - jsa_security_group \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/noConsolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/noConsolidation/out/MainServiceTemplate.yaml index 6ebaa53c6a..44452b959f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/noConsolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedIn/noConsolidation/out/MainServiceTemplate.yaml @@ -99,14 +99,14 @@ topology_template: properties: compute_QRouter_availability_zone: - Availability-test - port_oam_private_net_network_port_network: - - get_input: oam_private_net_name - vm_image_name: Image-test compute_QRouter_config_drive: - true port_cdr_network_port_network: - get_input: cdr_network vm_flavor_name: FLAVOR-test + port_oam_private_net_network_port_network: + - get_input: oam_private_net_name + vm_image_name: Image-test compute_QRouter_name: - QRouter-name service_template_filter: @@ -127,4 +127,4 @@ topology_template: - packet_mirror_network - packet_internal_network - cdr_network_port - - oam_private_net_network_port + - oam_private_net_network_port \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/consolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/consolidation/out/MainServiceTemplate.yaml index f554f0a844..5cd7faa646 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/consolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/consolidation/out/MainServiceTemplate.yaml @@ -240,6 +240,11 @@ topology_template: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - get_input: fsb1-Internal2-mac + compute_FSB_user_data: + - OPTIONAL-DATA-FSB1 + - null + vm_flavor_name: + get_input: fsb-flavor vm_image_name: get_input: fsb-image compute_FSB_admin_pass: @@ -248,6 +253,9 @@ topology_template: port_FSB1_Internal_network: - Internal1-net-fsb1-Internal1 - Internal1-net-fsb1-Internal2 + port_FSB2_Internal_mac_address: + - get_input: fsb2-Internal1-mac + - get_input: fsb2-Internal2-mac port_FSB2_Internal_network: - Internal2-net-fsb2-Internal1 - Internal2-net-fsb2-Internal2 @@ -258,17 +266,9 @@ topology_template: - write_files: - path: /path3/etc/sysconfig/network-scripts/ifcfg-eth0 - path: /path4/etc/sysconfig/network-scripts/ifcfg-eth1 - compute_FSB_user_data: - - OPTIONAL-DATA-FSB1 - - null compute_FSB_availability_zone: - get_input: fsb1_zone - get_input: fsb2_zone - vm_flavor_name: - get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb2-Internal1-mac - - get_input: fsb2-Internal2-mac compute_FSB_name: - get_input: fsb1-name - get_input: fsb2-name @@ -309,4 +309,4 @@ topology_template: - FSB2_template - jsa_net - jsa_net1 - - packet_mirror_network_name + - packet_mirror_network_name \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/noConsolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/noConsolidation/out/MainServiceTemplate.yaml index 45b3f46412..1779261886 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/noConsolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updNodesConnectedOut/noConsolidation/out/MainServiceTemplate.yaml @@ -175,16 +175,18 @@ topology_template: properties: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - port_FSB1_Internal_network: - - Internal1-net vm_flavor_name: get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb1-Internal2-mac vm_image_name: get_input: fsb-image compute_FSB_admin_pass: - STATIC-DATA-FSB1 + port_FSB_OAM_network: + - jsa_net1 + port_FSB1_Internal_network: + - Internal1-net + port_FSB2_Internal_mac_address: + - get_input: fsb1-Internal2-mac port_FSB_OAM_fixed_ips: - - ip_address: get_input: fsb1-oam-ip @@ -196,8 +198,6 @@ topology_template: - path: /path2/etc/sysconfig/network-scripts/ifcfg-eth1 compute_FSB_availability_zone: - get_input: fsb1_zone - port_FSB_OAM_network: - - jsa_net1 compute_FSB_name: - get_input: fsb1-name service_template_filter: @@ -233,4 +233,4 @@ topology_template: - FSB1_Internal1 - FSB1_OAM - FSB1_template - - packet_mirror_network_name + - packet_mirror_network_name \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/consolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/consolidation/out/MainServiceTemplate.yaml index 5e53a1d849..e5513bd30a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/consolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/consolidation/out/MainServiceTemplate.yaml @@ -280,6 +280,11 @@ topology_template: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - get_input: fsb1-Internal2-mac + compute_FSB_user_data: + - OPTIONAL-DATA-FSB1 + - null + vm_flavor_name: + get_input: fsb-flavor vm_image_name: get_input: fsb-image compute_FSB_admin_pass: @@ -288,6 +293,9 @@ topology_template: port_FSB1_Internal_network: - Internal1-net-fsb1-Internal1 - Internal1-net-fsb1-Internal2 + port_FSB2_Internal_mac_address: + - get_input: fsb2-Internal1-mac + - get_input: fsb2-Internal2-mac port_FSB2_Internal_network: - Internal2-net-fsb2-Internal1 - Internal2-net-fsb2-Internal2 @@ -298,17 +306,9 @@ topology_template: - write_files: - path: /path3/etc/sysconfig/network-scripts/ifcfg-eth0 - path: /path4/etc/sysconfig/network-scripts/ifcfg-eth1 - compute_FSB_user_data: - - OPTIONAL-DATA-FSB1 - - null compute_FSB_availability_zone: - get_input: fsb1_zone - get_input: fsb2_zone - vm_flavor_name: - get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb2-Internal1-mac - - get_input: fsb2-Internal2-mac compute_FSB_name: - get_input: fsb1-name - get_input: fsb2-name @@ -357,4 +357,4 @@ topology_template: - FSB2_template - jsa_net - jsa_net1 - - packet_mirror_network_name + - packet_mirror_network_name \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/noConsolidation/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/noConsolidation/out/MainServiceTemplate.yaml index 06b43188e5..54d4cfe9ee 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/noConsolidation/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/unifiedComposition/updVolumes/noConsolidation/out/MainServiceTemplate.yaml @@ -195,16 +195,18 @@ topology_template: properties: port_FSB1_Internal_mac_address: - get_input: fsb1-Internal1-mac - port_FSB1_Internal_network: - - Internal1-net vm_flavor_name: get_input: fsb-flavor - port_FSB2_Internal_mac_address: - - get_input: fsb1-Internal2-mac vm_image_name: get_input: fsb-image compute_FSB_admin_pass: - STATIC-DATA-FSB1 + port_FSB_OAM_network: + - jsa_net1 + port_FSB1_Internal_network: + - Internal1-net + port_FSB2_Internal_mac_address: + - get_input: fsb1-Internal2-mac port_FSB_OAM_fixed_ips: - - ip_address: get_input: fsb1-oam-ip @@ -216,8 +218,6 @@ topology_template: - path: /path2/etc/sysconfig/network-scripts/ifcfg-eth1 compute_FSB_availability_zone: - get_input: fsb1_zone - port_FSB_OAM_network: - - jsa_net1 compute_FSB_name: - get_input: fsb1-name service_template_filter: @@ -261,4 +261,4 @@ topology_template: - FSB1_Internal1 - FSB1_OAM - FSB1_template - - packet_mirror_network_name + - packet_mirror_network_name \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/main.yml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/main.yml index b97dd4b535..0894686026 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/main.yml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/main.yml @@ -62,7 +62,7 @@ parameters: resources: - server_cmaui: + server_cmaui_1: type: nested.yml properties: cmaui_names: { get_param: [cmaui_names, 0]} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/nested.yml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/nested.yml index cdaf251b85..d205cee2be 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/nested.yml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/inputfiles/nested.yml @@ -82,9 +82,9 @@ resources: type: OS::Cinder::VolumeAttachment properties: volume_id: {get_param: out_cmaui_volume} - instance_uuid: {get_resource: server_cmaui} + instance_uuid: {get_resource: server_cmaui_2} - server_cmaui: + server_cmaui_2: type: OS::Nova::Server properties: name: { get_param: [cmaui_names, 0]} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/GlobalSubstitutionTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/GlobalSubstitutionTypesServiceTemplate.yaml index c215d730a6..9ef461e1de 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/GlobalSubstitutionTypesServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/GlobalSubstitutionTypesServiceTemplate.yaml @@ -103,14 +103,14 @@ node_types: type: string status: SUPPORTED requirements: - - dependency_server_cmaui: + - dependency_server_cmaui_2: capability: tosca.capabilities.Node node: tosca.nodes.Root relationship: tosca.relationships.DependsOn occurrences: - 0 - UNBOUNDED - - local_storage_server_cmaui: + - local_storage_server_cmaui_2: capability: tosca.capabilities.Attachment node: tosca.nodes.BlockStorage relationship: tosca.relationships.AttachesTo @@ -138,19 +138,19 @@ node_types: - 1 - 1 capabilities: - cpu.delta_server_cmaui: + disk.write.bytes.rate_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.requests.rate_server_cmaui: + disk.device.write.bytes_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.allocation_server_cmaui: + disk.device.usage_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -162,84 +162,69 @@ node_types: occurrences: - 1 - UNBOUNDED - scalable_server_cmaui: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - disk.read.bytes.rate_server_cmaui: + disk.write.bytes_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - cpu_server_cmaui: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + feature_server_cmaui_2: + type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - disk.write.bytes.rate_server_cmaui: + disk.device.latency_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.bytes.rate_server_cmaui: + disk.allocation_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - host_server_cmaui: - type: tosca.capabilities.Container - valid_source_types: - - tosca.nodes.SoftwareComponent - occurrences: - - 1 - - UNBOUNDED - cpu_util_server_cmaui: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + feature_cmaui_port_0: + type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - feature_cmaui_port_0: - type: tosca.capabilities.Node + binding_server_cmaui_2: + type: tosca.capabilities.network.Bindable occurrences: - 1 - UNBOUNDED - disk.device.latency_server_cmaui: + disk.root.size_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.requests_server_cmaui: + disk.device.write.requests.rate_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.read.requests_server_cmaui: + vcpus_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outgoing.packets.rate_cmaui_port_0: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + scalable_server_cmaui_2: + type: tosca.capabilities.Scalable occurrences: - 1 - UNBOUNDED - disk.device.capacity_server_cmaui: + network.outgoing.packets.rate_cmaui_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.usage_server_cmaui: + disk.read.requests_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -250,101 +235,114 @@ node_types: occurrences: - 1 - UNBOUNDED - disk.device.usage_server_cmaui: + network.outgoing.bytes_cmaui_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outgoing.bytes_cmaui_port_0: + disk.write.requests_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.capacity_server_cmaui: + disk.device.iops_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests.rate_server_cmaui: + disk.usage_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.requests_server_cmaui: + disk.device.capacity_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - instance_server_cmaui: + disk.device.read.bytes.rate_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.bytes_server_cmaui: + endpoint_server_cmaui_2: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + disk.read.bytes_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory_server_cmaui: + os_server_cmaui_2: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + disk.device.read.bytes_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.root.size_server_cmaui: + disk.write.requests.rate_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - binding_server_cmaui: - type: tosca.capabilities.network.Bindable + memory_server_cmaui_2: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.read.requests.rate_server_cmaui: + cpu_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.bytes_server_cmaui: + disk.device.allocation_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - os_server_cmaui: - type: tosca.capabilities.OperatingSystem + host_server_cmaui_2: + type: tosca.capabilities.Container + valid_source_types: + - tosca.nodes.SoftwareComponent occurrences: - 1 - UNBOUNDED - disk.device.write.bytes.rate_server_cmaui: + network.incoming.packets_cmaui_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.packets_cmaui_port_0: + disk.ephemeral.size_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory.resident_server_cmaui: + disk.capacity_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.latency_server_cmaui: + instance_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -357,59 +355,60 @@ node_types: occurrences: - 0 - UNBOUNDED - feature_server_cmaui: + feature_cmaui_volume: type: tosca.capabilities.Node occurrences: - 1 - UNBOUNDED - feature_cmaui_volume: - type: tosca.capabilities.Node + network.incoming.bytes.rate_cmaui_port_0: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - vcpus_server_cmaui: + disk.iops_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes.rate_cmaui_port_0: + disk.device.write.requests_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.write.bytes_server_cmaui: + disk.device.read.requests_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.allocation_server_cmaui: + network.outpoing.packets_cmaui_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.write.requests_server_cmaui: + disk.read.bytes.rate_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - memory.usage_server_cmaui: + cpu.delta_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.outpoing.packets_cmaui_port_0: + disk.device.read.requests.rate_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.ephemeral.size_server_cmaui: + memory.resident_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: @@ -421,35 +420,36 @@ node_types: occurrences: - 1 - UNBOUNDED - endpoint_server_cmaui: - type: tosca.capabilities.Endpoint.Admin + disk.latency_server_cmaui_2: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.iops_server_cmaui: + cpu_util_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - disk.device.iops_server_cmaui: - type: org.openecomp.capabilities.metric.Ceilometer - description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. + attachment_cmaui_volume: + type: tosca.capabilities.Attachment occurrences: - 1 - UNBOUNDED - disk.read.bytes_server_cmaui: + network.incoming.bytes_cmaui_port_0: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - attachment_cmaui_volume: - type: tosca.capabilities.Attachment + disk.device.write.bytes.rate_server_cmaui_2: + type: org.openecomp.capabilities.metric.Ceilometer + description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: - 1 - UNBOUNDED - network.incoming.bytes_cmaui_port_0: + memory.usage_server_cmaui_2: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. occurrences: diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/MainServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/MainServiceTemplate.yaml index d59250444f..b0c76462ac 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/MainServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/MainServiceTemplate.yaml @@ -99,7 +99,7 @@ topology_template: type: string description: the name of the target volume backend node_templates: - server_cmaui: + server_cmaui_1: type: org.openecomp.resource.abstract.nodes.heat.nested directives: - substitutable @@ -123,4 +123,4 @@ topology_template: heat_file: ../Artifacts/main.yml description: cmaui server template for vMMSC members: - - server_cmaui \ No newline at end of file + - server_cmaui_1 \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/nestedServiceTemplate.yaml b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/nestedServiceTemplate.yaml index 7dd65fdfa5..9da203c466 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/nestedServiceTemplate.yaml +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/resources/mock/services/heattotosca/vol_attach/nested_with_inner_vol/out/nestedServiceTemplate.yaml @@ -114,7 +114,7 @@ topology_template: type: string description: the name of the target volume backend node_templates: - server_cmaui: + server_cmaui_2: type: org.openecomp.resource.vfc.nodes.heat.cmaui properties: flavor: @@ -168,14 +168,14 @@ topology_template: requirements: - binding: capability: tosca.capabilities.network.Bindable - node: server_cmaui + node: server_cmaui_2 relationship: tosca.relationships.network.BindsTo relationship_templates: cmaui_volume_attachment: type: org.openecomp.relationships.VolumeAttachesTo properties: volume_id: cmaui_volume - instance_uuid: server_cmaui + instance_uuid: server_cmaui_2 groups: a_vol_group: type: org.openecomp.groups.heat.HeatStack @@ -190,7 +190,7 @@ topology_template: heat_file: ../Artifacts/nested.yml description: cmaui server template for vMMSC members: - - server_cmaui + - server_cmaui_2 - cmaui_port_0 outputs: out_cmaui_volume: @@ -198,181 +198,181 @@ topology_template: substitution_mappings: node_type: org.openecomp.resource.abstract.nodes.heat.nested capabilities: - cpu.delta_server_cmaui: - - server_cmaui - - cpu.delta - disk.device.write.requests.rate_server_cmaui: - - server_cmaui - - disk.device.write.requests.rate - disk.device.allocation_server_cmaui: - - server_cmaui - - disk.device.allocation + disk.write.bytes.rate_server_cmaui_2: + - server_cmaui_2 + - disk.write.bytes.rate + disk.device.write.bytes_server_cmaui_2: + - server_cmaui_2 + - disk.device.write.bytes + disk.device.usage_server_cmaui_2: + - server_cmaui_2 + - disk.device.usage network.incoming.packets.rate_cmaui_port_0: - cmaui_port_0 - network.incoming.packets.rate - scalable_server_cmaui: - - server_cmaui - - scalable - disk.read.bytes.rate_server_cmaui: - - server_cmaui - - disk.read.bytes.rate - cpu_server_cmaui: - - server_cmaui - - cpu - disk.write.bytes.rate_server_cmaui: - - server_cmaui - - disk.write.bytes.rate - disk.device.read.bytes.rate_server_cmaui: - - server_cmaui - - disk.device.read.bytes.rate - host_server_cmaui: - - server_cmaui - - host - cpu_util_server_cmaui: - - server_cmaui - - cpu_util + disk.write.bytes_server_cmaui_2: + - server_cmaui_2 + - disk.write.bytes + feature_server_cmaui_2: + - server_cmaui_2 + - feature + disk.device.latency_server_cmaui_2: + - server_cmaui_2 + - disk.device.latency + disk.allocation_server_cmaui_2: + - server_cmaui_2 + - disk.allocation feature_cmaui_port_0: - cmaui_port_0 - feature - disk.device.latency_server_cmaui: - - server_cmaui - - disk.device.latency - disk.device.write.requests_server_cmaui: - - server_cmaui - - disk.device.write.requests - disk.read.requests_server_cmaui: - - server_cmaui - - disk.read.requests + binding_server_cmaui_2: + - server_cmaui_2 + - binding + disk.root.size_server_cmaui_2: + - server_cmaui_2 + - disk.root.size + disk.device.write.requests.rate_server_cmaui_2: + - server_cmaui_2 + - disk.device.write.requests.rate + vcpus_server_cmaui_2: + - server_cmaui_2 + - vcpus + scalable_server_cmaui_2: + - server_cmaui_2 + - scalable network.outgoing.packets.rate_cmaui_port_0: - cmaui_port_0 - network.outgoing.packets.rate - disk.device.capacity_server_cmaui: - - server_cmaui - - disk.device.capacity - disk.usage_server_cmaui: - - server_cmaui - - disk.usage + disk.read.requests_server_cmaui_2: + - server_cmaui_2 + - disk.read.requests attachment_cmaui_port_0: - cmaui_port_0 - attachment - disk.device.usage_server_cmaui: - - server_cmaui - - disk.device.usage network.outgoing.bytes_cmaui_port_0: - cmaui_port_0 - network.outgoing.bytes - disk.capacity_server_cmaui: - - server_cmaui - - disk.capacity - disk.write.requests.rate_server_cmaui: - - server_cmaui - - disk.write.requests.rate - disk.device.read.requests_server_cmaui: - - server_cmaui - - disk.device.read.requests - instance_server_cmaui: - - server_cmaui - - instance - disk.device.read.bytes_server_cmaui: - - server_cmaui + disk.write.requests_server_cmaui_2: + - server_cmaui_2 + - disk.write.requests + disk.device.iops_server_cmaui_2: + - server_cmaui_2 + - disk.device.iops + disk.usage_server_cmaui_2: + - server_cmaui_2 + - disk.usage + disk.device.capacity_server_cmaui_2: + - server_cmaui_2 + - disk.device.capacity + disk.device.read.bytes.rate_server_cmaui_2: + - server_cmaui_2 + - disk.device.read.bytes.rate + endpoint_server_cmaui_2: + - server_cmaui_2 + - endpoint + disk.read.bytes_server_cmaui_2: + - server_cmaui_2 + - disk.read.bytes + os_server_cmaui_2: + - server_cmaui_2 + - os + disk.device.read.bytes_server_cmaui_2: + - server_cmaui_2 - disk.device.read.bytes - memory_server_cmaui: - - server_cmaui + disk.write.requests.rate_server_cmaui_2: + - server_cmaui_2 + - disk.write.requests.rate + memory_server_cmaui_2: + - server_cmaui_2 - memory - disk.root.size_server_cmaui: - - server_cmaui - - disk.root.size - binding_server_cmaui: - - server_cmaui - - binding - disk.device.read.requests.rate_server_cmaui: - - server_cmaui - - disk.device.read.requests.rate - disk.write.bytes_server_cmaui: - - server_cmaui - - disk.write.bytes - os_server_cmaui: - - server_cmaui - - os - disk.device.write.bytes.rate_server_cmaui: - - server_cmaui - - disk.device.write.bytes.rate + cpu_server_cmaui_2: + - server_cmaui_2 + - cpu + disk.device.allocation_server_cmaui_2: + - server_cmaui_2 + - disk.device.allocation + host_server_cmaui_2: + - server_cmaui_2 + - host network.incoming.packets_cmaui_port_0: - cmaui_port_0 - network.incoming.packets - memory.resident_server_cmaui: - - server_cmaui - - memory.resident - disk.latency_server_cmaui: - - server_cmaui - - disk.latency + disk.ephemeral.size_server_cmaui_2: + - server_cmaui_2 + - disk.ephemeral.size + disk.capacity_server_cmaui_2: + - server_cmaui_2 + - disk.capacity + instance_server_cmaui_2: + - server_cmaui_2 + - instance binding_cmaui_port_0: - cmaui_port_0 - binding - feature_server_cmaui: - - server_cmaui - - feature feature_cmaui_volume: - cmaui_volume - feature - vcpus_server_cmaui: - - server_cmaui - - vcpus network.incoming.bytes.rate_cmaui_port_0: - cmaui_port_0 - network.incoming.bytes.rate - disk.device.write.bytes_server_cmaui: - - server_cmaui - - disk.device.write.bytes - disk.allocation_server_cmaui: - - server_cmaui - - disk.allocation - disk.write.requests_server_cmaui: - - server_cmaui - - disk.write.requests - memory.usage_server_cmaui: - - server_cmaui - - memory.usage + disk.iops_server_cmaui_2: + - server_cmaui_2 + - disk.iops + disk.device.write.requests_server_cmaui_2: + - server_cmaui_2 + - disk.device.write.requests + disk.device.read.requests_server_cmaui_2: + - server_cmaui_2 + - disk.device.read.requests network.outpoing.packets_cmaui_port_0: - cmaui_port_0 - network.outpoing.packets - disk.ephemeral.size_server_cmaui: - - server_cmaui - - disk.ephemeral.size + disk.read.bytes.rate_server_cmaui_2: + - server_cmaui_2 + - disk.read.bytes.rate + cpu.delta_server_cmaui_2: + - server_cmaui_2 + - cpu.delta + disk.device.read.requests.rate_server_cmaui_2: + - server_cmaui_2 + - disk.device.read.requests.rate + memory.resident_server_cmaui_2: + - server_cmaui_2 + - memory.resident network.outgoing.bytes.rate_cmaui_port_0: - cmaui_port_0 - network.outgoing.bytes.rate - endpoint_server_cmaui: - - server_cmaui - - endpoint - disk.iops_server_cmaui: - - server_cmaui - - disk.iops - disk.device.iops_server_cmaui: - - server_cmaui - - disk.device.iops - disk.read.bytes_server_cmaui: - - server_cmaui - - disk.read.bytes + disk.latency_server_cmaui_2: + - server_cmaui_2 + - disk.latency + cpu_util_server_cmaui_2: + - server_cmaui_2 + - cpu_util attachment_cmaui_volume: - cmaui_volume - attachment network.incoming.bytes_cmaui_port_0: - cmaui_port_0 - network.incoming.bytes + disk.device.write.bytes.rate_server_cmaui_2: + - server_cmaui_2 + - disk.device.write.bytes.rate + memory.usage_server_cmaui_2: + - server_cmaui_2 + - memory.usage requirements: - dependency_server_cmaui: - - server_cmaui - - dependency - local_storage_server_cmaui: - - server_cmaui - - local_storage dependency_cmaui_port_0: - cmaui_port_0 - dependency link_cmaui_port_0: - cmaui_port_0 - link + local_storage_server_cmaui_2: + - server_cmaui_2 + - local_storage + dependency_server_cmaui_2: + - server_cmaui_2 + - dependency dependency_cmaui_volume: - cmaui_volume - dependency \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java index ee6ffbfca2..624ffeb05e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java @@ -176,8 +176,12 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { mapElementInfoToFeatureGroup(featureGroup.getId(), featureGroup.getVersion(), elementInfo.get()); - currentFeatureGroup.getEntitlementPoolIds().removeAll(removedEntitlementPools); - currentFeatureGroup.getEntitlementPoolIds().addAll(addedEntitlementPools); + if (!(removedEntitlementPools == null)) { + currentFeatureGroup.getEntitlementPoolIds().removeAll(removedEntitlementPools); + } + if (!(addedEntitlementPools == null)) { + currentFeatureGroup.getEntitlementPoolIds().addAll(addedEntitlementPools); + } if (featureGroupElement.getRelations() == null) { featureGroupElement.setRelations(new ArrayList<>()); } @@ -187,7 +191,12 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { .createRelation(RelationType.FeatureGroupToEntitlmentPool, relation)) .collect(Collectors.toList())); - currentFeatureGroup.getLicenseKeyGroupIds().removeAll(removedLicenseKeyGroups); + if (!(removedLicenseKeyGroups == null)) { + currentFeatureGroup.getLicenseKeyGroupIds().removeAll(removedLicenseKeyGroups); + } + if (!(addedLicenseKeyGroups == null)) { + currentFeatureGroup.getLicenseKeyGroupIds().addAll(addedLicenseKeyGroups); + } currentFeatureGroup.getLicenseKeyGroupIds().addAll(addedLicenseKeyGroups); featureGroupElement.getRelations() .addAll(currentFeatureGroup.getLicenseKeyGroupIds().stream() diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java index 55bbae9b33..45c831fbd7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java @@ -187,8 +187,13 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { mapElementInfoToLicenseAgreement(licenseAgreement.getId(), licenseAgreement.getVersion(), elementInfo.get()); - currentLicenseAgreement.getFeatureGroupIds().removeAll(removedFeatureGroupIds); - currentLicenseAgreement.getFeatureGroupIds().addAll(addedFeatureGroupIds); + if (! (removedFeatureGroupIds == null) ) { + currentLicenseAgreement.getFeatureGroupIds().removeAll(removedFeatureGroupIds); + } + + if (! (addedFeatureGroupIds == null)) { + currentLicenseAgreement.getFeatureGroupIds().addAll(addedFeatureGroupIds); + } licenseAgreementElement.setRelations(currentLicenseAgreement.getFeatureGroupIds().stream() .map(relation -> VlmZusammenUtil .createRelation(RelationType.LicenseAgreementToFeatureGroup, relation)) diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MibDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MibDao.java index cf980a52ff..1efd21ccbf 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MibDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MibDao.java @@ -38,4 +38,6 @@ public interface MibDao extends VersionableDao { Collection list(MibEntity entity); void deleteAll(MibEntity entity); + + Collection listArtifacts(MibEntity entity); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/MibDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/MibDaoZusammenImpl.java index 10cdfbd9da..d56db41cee 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/MibDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/MibDaoZusammenImpl.java @@ -135,6 +135,38 @@ public class MibDaoZusammenImpl implements MibDao { VspZusammenUtil.aggregateElements(componentElement, mibsElement), "Delete mibs"); } + @Override + public Collection listArtifacts(MibEntity mib) { + SessionContext context = ZusammenUtil.createSessionContext(); + Id itemId = new Id(mib.getVspId()); + ElementContext elementContext = new ElementContext(itemId, + VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), + VspZusammenUtil.getVersionTag(mib.getVersion())); + + final Optional elementByName = + zusammenAdaptor.getElementByName(context, elementContext, new Id(mib.getComponentId() + ), StructureElement.Mibs.name()); + + if(!elementByName.isPresent()) + return null; + else { + final Id elementId = elementByName.get().getElementId(); + return zusammenAdaptor.listElementData(context, elementContext, elementId).stream() + .map(element -> + buildMibEntity(element,mib) + ).collect(Collectors.toList()); + } + } + + private MibEntity buildMibEntity (Element element, MibEntity mib) { + MibEntity createdMib = new MibEntity(mib.getVspId(), mib.getVersion(), mib.getComponentId(), + null); + createdMib.setArtifactName((String) element.getInfo().getProperties().get(ARTIFACT_NAME)); + createdMib.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); + createdMib.setType( ArtifactType.valueOf(element.getInfo().getName())); + return createdMib; + } + private ZusammenElement buildComponentElement(MibEntity mibEntity) { ZusammenElement componentElement = new ZusammenElement(); componentElement.setElementId(new Id(mibEntity.getComponentId())); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java index 83a78bc705..2b6d52a38a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java @@ -5,6 +5,7 @@ import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.utils.fileutils.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; @@ -13,7 +14,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; @@ -89,11 +89,11 @@ public class OrchestrationTemplateDaoZusammenImpl implements OrchestrationTempla VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplate, null); ZusammenElement orchestrationTemplateValidationDataElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateValidationData, null); + .buildStructuralElement(StructureElement.OrchestrationTemplateValidationData, Action.UPDATE); orchestrationTemplateValidationDataElement.setData(new ByteArrayInputStream(uploadData .getValidationData().getBytes())); ZusammenElement orchestrationTemplateContent = - VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplateContent, null); + VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplateContent, Action.UPDATE); orchestrationTemplateContent .setData(new ByteArrayInputStream(uploadData.getContentData().array())); orchestrationTemplateElement.addSubElement(orchestrationTemplateValidationDataElement); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java index ffc9cb2901..b0cff4371e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java @@ -197,6 +197,9 @@ public class ProcessDaoZusammenImpl implements ProcessDao { processEntity .setArtifactName((String) elementInfo.getInfo().getProperties().get(ARTIFACT_NAME)); processEntity.setDescription((String) elementInfo.getInfo().getProperties().get(DESCRIPTION)); + processEntity.setType( elementInfo.getInfo().getProperties().get(PROCESS_TYPE) != null ? + ProcessType.valueOf((String) elementInfo.getInfo().getProperties().get(PROCESS_TYPE)) : + null); return processEntity; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java index d15014286f..7efb70494d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java @@ -214,7 +214,7 @@ public class TxtInformationArtifactGeneratorImpl implements InformationArtifactG .getNetworkDescription(), TAB + TAB + TAB + TAB)); networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_NETWORK, network.toString(), TAB + TAB + TAB + TAB)); - addEntryWithIndent(VNICS_PROTOCOLS, nicQuestionnaire.getProtocols().toString(), + addEntryWithIndent(VNICS_PROTOCOLS, nicQuestionnaire.getProtocols() == null ? "" : nicQuestionnaire.getProtocols().toString(), TAB + TAB + TAB + TAB); Optional ipconfigOpt = Optional.of(nicQuestionnaire).map diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java index 7d408ab82e..ac7cab6c51 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java @@ -24,6 +24,7 @@ import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; @@ -76,4 +77,7 @@ public interface ToscaAnalyzerService { boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId, RequirementAssignment requirementAssignment); + + public Map manageSubstitutionNodeTypeProperties( + ServiceTemplate substitutionServiceTemplate); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java index e7aacb96cf..eaf3fb492f 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java @@ -94,7 +94,7 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { .filter(nodeTypes -> Objects.nonNull(nodeTypes) && nodeTypes.containsKey(nodeTypeKey)) .findFirst(); if (nodeTypeMap.isPresent()) { - return Optional.ofNullable(nodeTypeMap.get().values().iterator().next()); + return Optional.ofNullable(nodeTypeMap.get().get(nodeTypeKey)); } return Optional.empty(); } @@ -601,7 +601,7 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return substitutionNodeType; } - private Map manageSubstitutionNodeTypeProperties( + public Map manageSubstitutionNodeTypeProperties( ServiceTemplate substitutionServiceTemplate) { Map substitutionNodeTypeProperties = new HashMap<>(); Map properties = diff --git a/openecomp-be/sonar-project.properties b/openecomp-be/sonar-project.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/openecomp-be/tools/install/database/schemaTemplates/questionnaire/component.ftl b/openecomp-be/tools/install/database/schemaTemplates/questionnaire/component.ftl index 6e588eb22a..d525c62474 100644 --- a/openecomp-be/tools/install/database/schemaTemplates/questionnaire/component.ftl +++ b/openecomp-be/tools/install/database/schemaTemplates/questionnaire/component.ftl @@ -136,7 +136,6 @@ "minimum": { "type": "number", "minimum": 0, - "exclusiveMinimum": true, "maximum": 100 }, "maximum": { diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml b/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml index 7bc93bddab..1f281c950b 100644 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml +++ b/openecomp-be/tools/migration/1702_to_1707_zusammen/pom.xml @@ -47,7 +47,7 @@ com.amdocs.zusammen.plugin zusammen-state-store-cassandra-plugin - 0.0.1-SNAPSHOT + 0.0.1 org.hibernate diff --git a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java index 283c9cf25d..c43cf32001 100644 --- a/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java +++ b/openecomp-be/tools/migration/1702_to_1707_zusammen/src/main/java/org/openecomp/core/migration/MigrationMain.java @@ -78,7 +78,7 @@ public class MigrationMain { printMessage(logger, "Checking whether a migration has already been run."); if (MigrationMarker.isMigrated()) { printMessage(logger, "The DB has already been migrated, this script will now exit."); - return; + System.exit(status); } ItemCassandraDao itemCassandraDao = new ItemCassandraDao(); VersionCassandraDao versionCassandraDao = new VersionCassandraDao(); @@ -243,7 +243,8 @@ public class MigrationMain { new OrchestrationTemplateCandidateCassandraLoader(); orchestrationTemplateCandidateCassandraLoader.list().stream() - .filter(entity -> needMigration(entity.getId(), entity.getVersion())) + .filter(entity -> needMigration(entity.getId(), entity.getVersion()) && + entity.getContentData()!=null && entity.getFilesDataStructure()!=null) .forEach(entity -> ElementHandler .save(context, cassandraElementRepository, entity.getId(), entity.getVersion(), OrchestrationTemplateCandidateConvertor diff --git a/openecomp-ui/resources/scss/components/_sequenceDiagram.scss b/openecomp-ui/resources/scss/components/_sequenceDiagram.scss index 5fad92a668..d89c342d47 100644 --- a/openecomp-ui/resources/scss/components/_sequenceDiagram.scss +++ b/openecomp-ui/resources/scss/components/_sequenceDiagram.scss @@ -1,11 +1,18 @@ .sequence-diagram { - @extend .flex-column; .sequence-diagram-sequencer { - flex: 0 1 auto; - margin-bottom: 30px; + .asdcs-diagram { + overflow: auto; + max-height: 60vh; + } + .asdcs-editor { + height: 60vh; + } } .sequence-diagram-action-buttons { - flex: 0.1; - text-align: center; + margin-left: 20px; + margin-top: 20px; + button:first-of-type { + margin-right: 20px; + } } } diff --git a/openecomp-ui/resources/scss/modules/_workflows.scss b/openecomp-ui/resources/scss/modules/_workflows.scss index c1555df28c..894b6e7973 100644 --- a/openecomp-ui/resources/scss/modules/_workflows.scss +++ b/openecomp-ui/resources/scss/modules/_workflows.scss @@ -25,19 +25,3 @@ padding: 15px; } } - -.sequence-diagram { - position: absolute; - bottom: 0; - right: 0; - left: 0; - top: 0; - - padding-bottom: 20px; - .sequence-diagram-action-buttons { - display: flex; - button { - margin: 20px; - } - } -} diff --git a/openecomp-ui/src/nfvo-components/input/validation/Form.jsx b/openecomp-ui/src/nfvo-components/input/validation/Form.jsx index 47922f86a0..98810d1c0d 100644 --- a/openecomp-ui/src/nfvo-components/input/validation/Form.jsx +++ b/openecomp-ui/src/nfvo-components/input/validation/Form.jsx @@ -110,5 +110,19 @@ class Form extends React.Component { } +export class TabsForm extends Form { + render() { + // eslint-disable-next-line no-unused-vars + let {isValid, formReady, onValidateForm, isReadOnlyMode, hasButtons, onSubmit, labledButtons, onValidChange, onValidityChanged, onDataChanged, children, ...formProps} = this.props; + return ( +
this.form = form} onSubmit={event => this.handleFormValidation(event)}> +
+ {children} +
+ {hasButtons && this.buttons = buttons} isReadOnlyMode={isReadOnlyMode}/>} + + ); + } +} export default Form; diff --git a/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js index 4945d33b23..74bde4058b 100644 --- a/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/OnboardingActionHelper.js @@ -155,10 +155,12 @@ export default { licenseModelId = response[0].vendorId; } + const newVersion = response[0].version ? response[0].version : version; + SoftwareProductActionHelper.loadSoftwareProductDetailsData(dispatch, {licenseModelId, licensingVersion}); - SoftwareProductComponentsActionHelper.fetchSoftwareProductComponents(dispatch, {softwareProductId, version}); - SoftwareProductActionHelper.loadSoftwareProductHeatCandidate(dispatch, {softwareProductId, version}); - setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, {softwareProductId, licenseModelId, version}); + SoftwareProductComponentsActionHelper.fetchSoftwareProductComponents(dispatch, {softwareProductId, version: newVersion}); + SoftwareProductActionHelper.loadSoftwareProductHeatCandidate(dispatch, {softwareProductId, version: newVersion}); + setCurrentScreen(dispatch, enums.SCREEN.SOFTWARE_PRODUCT_LANDING_PAGE, {softwareProductId, licenseModelId, version: newVersion}); }); }, diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx index 5ae22cba95..d69548442c 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupEditorView.jsx @@ -18,7 +18,7 @@ import Tabs from 'nfvo-components/input/validation/Tabs.jsx'; import Tab from 'react-bootstrap/lib/Tab.js'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; import GridItem from 'nfvo-components/grid/GridItem.jsx'; -import Form from 'nfvo-components/input/validation/Form.jsx'; +import {TabsForm as Form} from 'nfvo-components/input/validation/Form.jsx'; import DualListboxView from 'nfvo-components/input/dualListbox/DualListboxView.jsx'; import Input from 'nfvo-components/input/validation/Input.jsx'; import i18n from 'nfvo-utils/i18n/i18n.js'; @@ -169,17 +169,23 @@ class FeatureGroupEditorView extends React.Component { className='feature-group-form'> - this.validateName(value)}/> +
+ this.validateName(value)}/> +
- +
+ +
- +
+ +
diff --git a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx index 67a3333a3a..42a33fd509 100644 --- a/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementEditorView.jsx @@ -17,7 +17,7 @@ import React from 'react'; import GridSection from 'nfvo-components/grid/GridSection.jsx'; import GridItem from 'nfvo-components/grid/GridItem.jsx'; -import Form from 'nfvo-components/input/validation/Form.jsx'; +import {TabsForm as Form} from 'nfvo-components/input/validation/Form.jsx'; import Tabs from 'nfvo-components/input/validation/Tabs.jsx'; import Tab from 'react-bootstrap/lib/Tab.js'; import Input from 'nfvo-components/input/validation/Input.jsx'; @@ -151,21 +151,25 @@ class LicenseAgreementEditorView extends React.Component { eventKey={LicenseAgreementEnums.SELECTED_LICENSE_AGREEMENT_TAB.GENERAL} data-test-id='general-tab' title={i18n('General')}> - this.validateLTChoice(value)} - validateName={(value)=>this.validateName(value)}/> +
+ this.validateLTChoice(value)} + validateName={(value)=>this.validateName(value)}/> +
+
{featureGroupsList.length > 0 ? - onDataChanged( { featureGroupsIds: selectedValuesList }, LA_EDITOR_FORM )}/> : -

{i18n('There is no available feature groups')}

} + onDataChanged( { featureGroupsIds: selectedValuesList }, LA_EDITOR_FORM )}/> : +

{i18n('There is no available feature groups')}

} +
} diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js index 8f2506abdd..945de4fc36 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachments.js @@ -77,8 +77,8 @@ export const mapActionsToProps = (dispatch, {softwareProductId}) => { } }), onSave: (heatCandidate, version) => SoftwareProductActionHelper.updateSoftwareProductHeatCandidate(dispatch, {softwareProductId, heatCandidate, version}), - onGoToOverview: () => { - OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId}); + onGoToOverview: ({version}) => { + OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, version}); }, onProcessAndValidate: ({heatData, heatDataCache, isReadOnlyMode, version}) => { return HeatSetupActionHelper.processAndValidateHeat(dispatch, diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx index 66fb2f8356..ef4aecf568 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/attachments/SoftwareProductAttachmentsView.jsx @@ -50,7 +50,7 @@ class HeatScreenView extends Component { iconClassName={this.props.goToOverview ? '' : 'disabled'} className={`go-to-overview-icon ${this.props.goToOverview ? '' : 'disabled'}`} labelClassName='go-to-overview-label' - onClick={this.props.goToOverview ? onGoToOverview : undefined} + onClick={this.props.goToOverview ? () => onGoToOverview({version}) : undefined} image='go-to-overview' label={i18n('Go to Overview')} data-test-id='go-to-overview'/>} diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentEditorReducer.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentEditorReducer.js index 2ae9ad0bae..41e7556749 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentEditorReducer.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentEditorReducer.js @@ -20,6 +20,7 @@ export default (state = {}, action) => { case actionTypes.COMPONENT_LOAD: return { ...state, + data: action.component, formReady: null, formName: forms.ALL_SPC_FORMS, genericFieldInfo: { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js index 9b3c9eaa73..4e526d3b56 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/components/SoftwareProductComponentsActionHelper.js @@ -16,7 +16,7 @@ import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js'; import Configuration from 'sdc-app/config/Configuration.js'; -import {actionTypes, COMPONENTS_QUESTIONNAIRE, forms} from './SoftwareProductComponentsConstants.js'; +import {actionTypes, COMPONENTS_QUESTIONNAIRE} from './SoftwareProductComponentsConstants.js'; import ValidationHelper from 'sdc-app/common/helpers/ValidationHelper.js'; function baseUrl(softwareProductId, version) { @@ -89,12 +89,12 @@ const SoftwareProductComponentsActionHelper = { }, fetchSoftwareProductComponent(dispatch, {softwareProductId, version, vspComponentId}) { - dispatch({ - type: actionTypes.COMPONENT_LOAD - }); return Promise.all([ fetchSoftwareProductComponent(softwareProductId, version, vspComponentId).then(response => { - ValidationHelper.dataChanged(dispatch,{deltaData: response.data, formName: forms.ALL_SPC_FORMS}); + dispatch({ + type: actionTypes.COMPONENT_LOAD, + component: response.data + }); return response; }), fetchSoftwareProductComponentQuestionnaire(softwareProductId, version, vspComponentId).then(response => { diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js index 9540d3f869..05a1fc7797 100644 --- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js +++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/dependencies/SoftwareProductDependencies.js @@ -25,7 +25,7 @@ export const mapStateToProps = ({softwareProduct}) => { return { isReadOnlyMode, softwareProductDependencies: softwareProductDependencies.length ? softwareProductDependencies : [{sourceId: '', targetId: '', relationType: 'dependsOn', id: 'fake'}], - componentsOptions: componentsList.map(component => ({value: component.id, label: component.name})) + componentsOptions: componentsList.map(component => ({value: component.id, label: component.displayName})) }; }; diff --git a/pom.xml b/pom.xml index 6976a82dc1..81fe758f3b 100644 --- a/pom.xml +++ b/pom.xml @@ -42,6 +42,7 @@ 2.6.2 + 2.8.1 2.6.0 diff --git a/sdc-os-chef/pom.xml b/sdc-os-chef/pom.xml index 94ea55f9aa..e511056105 100644 --- a/sdc-os-chef/pom.xml +++ b/sdc-os-chef/pom.xml @@ -223,7 +223,7 @@ true - openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity + openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity @@ -243,7 +243,7 @@ push - openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity + openecomp/sdc-backend,openecomp/sdc-frontend,openecomp/sdc-elasticsearch,openecomp/sdc-kibana,openecomp/sdc-sanity diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb index f011a51021..4287ca8617 100644 --- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb +++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb @@ -1,3 +1 @@ -# -# Example to value after replacement : default['asdctool'][:version] = "1707.0.66.73.1" -default['asdctool'][:version] = "__CATALOG-ASDCTOOL_TAR_NAME__" \ No newline at end of file +# \ No newline at end of file diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/user.py b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/user.py index d1ce9cfad8..90e44561ce 100644 --- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/user.py +++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/user.py @@ -38,9 +38,9 @@ def checkUser(userName): -def createUser( firstName, lastName, userId , email , role ): - print '[INFO] create first:[' + firstName + '], last:[' + lastName + '], Id:[' + userId + '], email:[' + email + '], role:[' + role +']' - command="curl -s -o /dev/null -w \"%{http_code}\" -X POST -i -H \"Accept: application/json; charset=UTF-8\" -H \"Content-Type: application/json\" -H \"USER_ID: jh0003\" http://localhost:8080/sdc2/rest/v1/user/ -d '{\"firstName\": '" + firstName + "', \"lastName\": '" + lastName + "',\"userId\": '" + userId + "',\"email\": '" + email + "',\"role\": '" + role + "'}'" +def createUser( firstName, lastName, userId , email_dom , role ): + print '[INFO] create first:[' + firstName + '], last:[' + lastName + '], Id:[' + userId + '], email:[' + userId + '@' + email_dom + '], role:[' + role +']' + command="curl -s -o /dev/null -w \"%{http_code}\" -X POST -i -H \"Accept: application/json; charset=UTF-8\" -H \"Content-Type: application/json\" -H \"USER_ID: jh0003\" http://localhost:8080/sdc2/rest/v1/user/ -d '{\"firstName\": '" + firstName + "', \"lastName\": '" + lastName + "',\"userId\": '" + userId + "',\"email\": '" + userId + "@" + email_dom + "',\"role\": '" + role + "'}'" proc = subprocess.Popen( command , shell=True , stdout=subprocess.PIPE) (out, err) = proc.communicate() @@ -53,11 +53,11 @@ def createUser( firstName, lastName, userId , email , role ): ############################## # Definitions ############################## -userList = [ "demo" ] -lastName = "demo" -userId = "demo" -email = "demo@openecomp.org" -role = "ADMIN" +userId = [ "demo" , "op0001" , "gv0001" , "jh0003" , "jm0007" , "cs0008" ] +firstName = [ "demo" , "Oper" , "Giuseppe" , "Jimmy" , "Joni" , "Carlos" ] +lastName = [ "demo" , "P" , "Verdi" , "Hendrix" , "Mitchell" , "Santana" ] +role = [ "ADMIN" , "OPS" , "ADMIN" , "GOVERNOR" , "TESTER" , "DESIGNER" ] +email_dom = "openecomp.org" beStat=0 @@ -80,13 +80,14 @@ if beStat == 0: print '[ERROR]: ' + time.strftime('%Y/%m/%d %H:%M:%S') + bcolors.FAIL + 'Backend is DOWN :-(' + bcolors.ENDC exit() -for user in userList: +for user in userId: myResult = checkUser(user) + pos = userId.index(user) if myResult == '200': print '[INFO]: ' + user + ' already exists' else: - myResult = createUser( user, lastName, userId, email, role ) + myResult = createUser( firstName[pos], lastName[pos], userId[pos], email_dom, role[pos] ) if myResult == '201': - print '[INFO]: ' + userId + ' created, result: [' + myResult + ']' + print '[INFO]: ' + userId[pos] + ' created, result: [' + myResult + ']' else: - print '[ERROR]: ' + bcolors.FAIL + userId + bcolors.ENDC + ' error creating , result: [' + myResult + ']' + print '[ERROR]: ' + bcolors.FAIL + userId[pos] + bcolors.ENDC + ' error creating , result: [' + myResult + ']' diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties deleted file mode 100644 index 43944eae47..0000000000 --- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/titan.properties +++ /dev/null @@ -1,6 +0,0 @@ -storage.backend=cassandra -storage.hostname=localhost -storage.port=9160 -storage.username=asdc_user -storage.password=Aa1234%^! -storage.cassandra.keyspace=sdctitan \ No newline at end of file diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb index da6bbb184c..f65bb945f3 100644 --- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb +++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/create_dox_keyspace.sh.erb @@ -12,41 +12,23 @@ echo -e "$KEYSPACE\n$KEYSPACE1" > /tmp/create_dox_keyspace.cql chmod 755 /tmp/create_dox_keyspace.cql cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS -f /tmp/create_dox_keyspace.cql > /dev/null 2>&1 -CS_VERSION=`cassandra -v` -CS_MAJOR_VERSION=`cassandra -v | cut -c1` -if [ ${CS_MAJOR_VERSION} -gt 2 ]; then - echo "`date` --- CS [${CS_VERSION}] uses system_schema.keyspaces" - res=`echo "select keyspace_name from system_schema.keyspaces ;" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS |grep -c dox 2>/dev/null` -else - echo "`date` --- CS [${CS_VERSION}] uses system.schema_keyspaces" - res=`echo "select keyspace_name from system.schema_keyspaces ;" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS |grep -c dox 2>/dev/null` -fi + +res=`echo "select keyspace_name from system.schema_keyspaces ;" | cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS |grep -c dox 2>/dev/null` if [ $res -gt 0 ]; then - echo "`date` --- dox keyspace was created " + echo "`date` --- dox keyspace was created " else - echo "`date` --- Failed to create dox keyspace" + echo "`date` --- Failed to create dox keyspace" fi echo "run create_dox_db.cql" chmod 755 /tmp/create_dox_db.cql cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS -f /tmp/create_dox_db.cql > /dev/null 2>&1 -$res=$? -if [ $res -gt 0 ]; then - echo "`date` --- dox keyspace: create_dox_db.cql failed ! " -else - echo "`date` --- dox keyspace: create_dox_db.cql completed successfully " -fi sleep 10 echo "run alter_dox_db.cql" chmod 755 /tmp/alter_dox_db.cql cqlsh -u $CASSANDRA_USER -p $CASSANDRA_PASS -f /tmp/alter_dox_db.cql > /dev/null 2>&1 -$res=$? -if [ $res -gt 0 ]; then - echo "`date` --- dox keyspace: alter_dox_db.cql failed !" -else - echo "`date` --- dox keyspace: alter_dox_db.cql completed successfully " -fi + diff --git a/test-apis-ci/.gitignore b/test-apis-ci/.gitignore new file mode 100644 index 0000000000..9b563712b6 --- /dev/null +++ b/test-apis-ci/.gitignore @@ -0,0 +1,4 @@ +/target +/build/ +/bin/ +/target/ diff --git a/test-apis-ci/pom.xml b/test-apis-ci/pom.xml new file mode 100644 index 0000000000..ec8eab07d3 --- /dev/null +++ b/test-apis-ci/pom.xml @@ -0,0 +1,381 @@ + + + 4.0.0 + + test-apis-ci + + + org.openecomp.sdc + sdc-main + 1.1.0-SNAPSHOT + + + + + com.google.guava + guava + ${guava.version} + compile + + + + junit + junit + ${junit.version} + compile + + + + org.testng + testng + ${testng.version} + compile + + + + com.aventstack + extentreports + 3.0.6 + compile + + + + org.mockito + mockito-all + ${mockito.version} + + compile + + + + com.typesafe + config + 1.0.2 + compile + + + + log4j + log4j + 1.2.17 + compile + + + + com.jcraft.jsch + com.springsource.com.jcraft.jsch + 0.1.41 + compile + + + + org.openecomp.sdc + common-app-api + ${project.version} + compile + + + + org.openecomp.sdc.be + common-be + ${project.version} + compile + + + + + org.openecomp.sdc.be + catalog-model + ${project.version} + compile + + + + + org.openecomp.sdc.be + catalog-dao + ${project.version} + compile + + + + org.functionaljava + functionaljava + ${functionaljava.version} + compile + + + + com.datastax.cassandra + cassandra-driver-core + ${cassandra.driver.version} + compile + + + + + + org.slf4j + slf4j-api + ${slf4j-api.version} + compile + + + + ch.qos.logback + logback-classic + ${logback.version} + compile + + + + ch.qos.logback + logback-core + ${logback.version} + compile + + + + com.googlecode.json-simple + json-simple + ${json-simple.version} + compile + + + + + org.apache.commons + commons-jci-core + ${commons-jci-core.version} + compile + + + + commons-codec + commons-codec + ${commons-codec} + compile + + + + + com.google.code.gson + gson + ${gson.version} + compile + + + + + org.yaml + snakeyaml + ${snakeyaml.version} + compile + + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + compile + + + + org.apache.httpcomponents + httpmime + ${httpclient.version} + compile + + + + commons-io + commons-io + 2.5 + compile + + + + commons-logging + commons-logging + ${commons-logging} + compile + + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + compile + + + + + com.thinkaurelius.titan + titan-core + ${titan.version} + compile + + + slf4j-log4j12 + org.slf4j + + + + + + com.thinkaurelius.titan + titan-cassandra + ${titan.version} + compile + + + slf4j-log4j12 + org.slf4j + + + + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.2 + compile + + + + com.fasterxml.jackson.core + jackson-databind + 2.3.1 + compile + + + + com.fasterxml.jackson.core + jackson-core + 2.3.1 + compile + + + + org.openecomp.ecompsdkos + epsdk-fw + ${ecomp.version} + compile + + + slf4j-log4j12 + org.slf4j + + + + + + org.json + json + 20090211 + + + org.openecomp.sdc.sdc-distribution-client + sdc-tosca-parser + 1.1.9-SNAPSHOT + compile + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.7 + + true + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.5.5 + + + create.jar.with.dependencies + package + + single + + + + + org.openecomp.sdc.ci.tests.run.StartTest + + + + jar-with-dependencies + + + + + + + + + + + Fortify + + false + + + + + + + + + com.fortify.ps.maven.plugin + sca-maven-plugin + 4.30 + + false + true + + + + + + + diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java new file mode 100644 index 0000000000..f9752febaf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java @@ -0,0 +1,200 @@ +/*- + * ============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.ci.tests.api; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.List; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.junit.rules.TestWatcher; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.rules.MyTestWatcher; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public abstract class AttSdcTest { + + public static StringBuilder doc = new StringBuilder(); + public static String file = null; + public static Config config = null; + // protected Gson gson = new Gson(); + protected Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + protected TestName testName = null; + protected Logger logger = null; + + protected static boolean displayException = false; + + public AttSdcTest(TestName testName, String className) { + super(); + + StartTest.enableLogger(); + + this.testName = testName; + this.logger = LoggerFactory.getLogger(className); + + String displayEx = System.getProperty("displayException"); + if (displayEx != null && Boolean.valueOf(displayEx).booleanValue()) { + displayException = true; + } + + } + + @Rule + public TestWatcher tw = new MyTestWatcher(this); + + @BeforeClass + public static void beforeClass() { + doc = new StringBuilder(); + doc.append( + ""); + + doc.append(""); + doc.append( + ""); + + doc.append(""); + + doc.append(""); + doc.append(""); + + doc.append(""); + + doc.append(""); + doc.append(""); + doc.append(""); + doc.append(""); + + if (displayException) { + doc.append(""); + } + doc.append(""); + } + + @AfterClass + public static void afterClass() { + doc.append("
").append("Test Name").append("").append("Status").append("").append("Message").append("").append("Exception").append("
"); + // writeToFile("./" + ConfigAttOdlIt.REPORT_FILE , doc.toString()); + FileUtils.writeToFile( + Config.instance().getOutputFolder() + File.separator + file + StartTest.timeOfTest + ".html", + doc.toString()); + + } + + @Before + public void beforeTest() throws FileNotFoundException { + file = FileUtils.getFileName(this.getClass().getName()); + config = Utils.getConfig(); + assertTrue(config != null); + } + + @After + public void afterTest() throws FileNotFoundException { + + } + + public void addTestSummary(String testName, boolean isSuccess) { + addTestSummary(testName, isSuccess, null); + } + + public void addTestSummary(String testName, boolean isSuccess, Throwable exception) { + + String message = exception == null ? "" : exception.getMessage(); + + String result = (isSuccess) ? "success" : "fail"; + doc.append(""); + doc.append(""); + doc.append(""); + doc.append(""); + + if (displayException) { + // doc.append(""); + doc.append(""); + } + + doc.append(""); + + if (isSuccess) { + logger.debug("Test {} {}",testName,(isSuccess ? " SUCCEEDED " : " FAILED with error " + message)); + } else { + logger.error("Test {} {}",testName,(isSuccess ? " SUCCEEDED " : " FAILED with error " + message)); + } + } + + private String convertExceptionToString(Throwable exception) { + + if (exception == null) { + return ""; + } + + StringWriter sw = new StringWriter(); + exception.printStackTrace(new PrintWriter(sw)); + String exceptionAsString = sw.toString(); + + return exceptionAsString; + } + + public Logger getLogger() { + return logger; + } + + protected boolean ignoreDueToBug(String bug) { + + List bugs = config.getBugs(); + + if (bugs != null && bugs.size() > 0) { + for (String bugNumber : bugs) { + if (bugNumber.startsWith(bug)) { + return true; + } + } + } + + return false; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java new file mode 100644 index 0000000000..a9cc119b20 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java @@ -0,0 +1,607 @@ +/*- + * ============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.ci.tests.api; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.log4j.Logger; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +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.Component; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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.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.AutomationUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.slf4j.LoggerFactory; +import org.testng.ITestContext; +import org.testng.ITestResult; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; + +public abstract class ComponentBaseTest { + +// private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName()); + + protected static Logger logger= Logger.getLogger(ComponentBaseTest.class); + + + // public ComponentBaseTest(TestName testName, String className) { + // super(testName, className); + // } + + protected static ExtentReports extentReport; + public static final String REPORT_FOLDER = "./ExtentReport/"; + private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; + private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html"; + protected static TitanGraph titanGraph; + private static Config myconfig; + public static Config config; + + + + /**************** METHODS ****************/ + public static ExtentTest getExtendTest() { + return ExtentTestManager.getTest(); + } + + public static enum ComponentOperationEnum { + CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT + }; + + public ComponentBaseTest(TestName name, String name2) { + // TODO Auto-generated constructor stub + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.getLogger("com.thinkaurelius").setLevel(Level.INFO); + lc.getLogger("com.datastax").setLevel(Level.INFO); + lc.getLogger("io.netty").setLevel(Level.INFO); + lc.getLogger("c.d").setLevel(Level.INFO); + } + + @BeforeSuite(alwaysRun = true) + public static void openTitan(ITestContext context) throws Exception { + + logger.info("<<>>"); + myconfig = Utils.getConfig(); + config = Utils.getConfig(); + + File dir = new File(REPORT_FOLDER); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + } + dir.mkdir(); + + System.out.println("BeforeSuite - get reporter"); + extentReport = ExtentManager.getReporter(REPORT_FOLDER + REPORT_FILE_NAME); + + String onboardVersion = AutomationUtils.getOnboardVersion(); + String osVersion = AutomationUtils.getOSVersion(); + String envData = myconfig.getUrl(); + // TODO: uncomment config file +// extentReport.loadConfig(AutomationUtils.getConfigFile(CONFIG_FILE)); + + extentReport.setSystemInfo("Onboard Version", onboardVersion); + extentReport.setSystemInfo("OS Version", osVersion); + extentReport.setSystemInfo("ExecutedOn", envData); + extentReport.setSystemInfo("SuiteName", context.getName()); + AutomationUtils.createVersionsInfoFile(REPORT_FOLDER + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData); + + System.out.println("BeforeSuite - open titan"); + openTitanLogic(); + + System.out.println("BeforeSuite - createConsumer"); + AtomicOperationUtils.createDefaultConsumer(true); + + System.out.println("BeforeSuite - performClean"); + performClean(); + } + + protected static void openTitanLogic() throws Exception { + + logger.trace(config.toString()); + String titanConfigFilePath = myconfig.getTitanPropertiesFile(); + titanGraph = TitanFactory.open(titanConfigFilePath); + assertNotNull(titanGraph); + + } + + @AfterClass(alwaysRun = true) + public synchronized static void cleanAfterClass() throws Exception{ + +// System.out.println("<<<<<<<>>>>"+method.getDeclaringClass()); +// System.out.println("<<<<<<<>>>>"+method.getName()); + + + System.out.println("delete components AfterClass"); + deleteCreatedComponents(getCatalogAsMap()); +// extentReport.flush(); + + } + + @AfterSuite(alwaysRun = true) + public static void shutdownTitan() throws Exception { + + System.out.println("AfterSuite - flush report"); + extentReport.flush(); + System.out.println("AfterSuite - perform clean"); + performClean(); + System.out.println("AfterSuite - close report"); +// extentReport.close(); + System.out.println("AfterSuite - close titan"); + shutdownTitanLogic(); + System.out.println("AfterSuite - suite ended"); + } + + protected static void shutdownTitanLogic() { + if (titanGraph.isOpen()) { + titanGraph.close(); + } + CassandraUtils.close(); + } + + @BeforeMethod(alwaysRun = true) + public void beforeState(java.lang.reflect.Method method) throws Exception { + + + ExtentTestManager.startTest(method.getName()); + String[] parts = this.getClass().getName().toString().split("\\."); + String lastOne1 = parts[parts.length-1]; + String lastOne2 = parts[parts.length-2]; + getExtendTest().assignCategory(lastOne2 + "-" + lastOne1); + getExtendTest().log(Status.INFO, "Test started"); + + } + + @AfterMethod(alwaysRun = true) + public void afterState(ITestResult result) throws Exception { + + String testName = result.getName(); + Throwable throwable = result.getThrowable(); + int status = result.getStatus(); + + switch(status){ + case ITestResult.SUCCESS: + getExtendTest().log(Status.PASS, "Test Result : Success"); + break; + + case ITestResult.FAILURE: + getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured"); + getExtendTest().log(Status.ERROR, result.getThrowable()); + getExtendTest().log(Status.FAIL, "Failure"); + break; + + case ITestResult.SKIP: + getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured"); + break; + default: + break; + } + + + ExtentTestManager.endTest(); + extentReport.flush(); + + + } + + protected static void performClean() throws Exception, FileNotFoundException { +// cleanComponents(); + deleteCreatedComponents(getCatalogAsMap()); + CassandraUtils.truncateAllKeyspaces(); + } + + public void verifyErrorCode(RestResponse response, String action, int expectedCode) { + assertNotNull("check response object is not null after " + action, response); + assertNotNull("check error code exists in response after " + action, response.getErrorCode()); + assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue()); + } + + private static void cleanComponents() throws Exception { + + // Components to delete + List vfResourcesToDelete = new ArrayList(); + List nonVfResourcesToDelete = new ArrayList(); + List servicesToDelete = new ArrayList(); + List productsToDelete = new ArrayList(); + + // Categories to delete + List> productGroupingsToDelete = new ArrayList<>(); + List> productSubsToDelete = new ArrayList<>(); + List> resourceSubsToDelete = new ArrayList<>(); + List productCategoriesToDelete = new ArrayList<>(); + List resourceCategoriesToDelete = new ArrayList(); + List serviceCategoriesToDelete = new ArrayList(); + + List resourcesNotToDelete = config.getResourcesNotToDelete(); + List resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete(); + List serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete(); + + Iterable vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices(); + if (vertices != null) { + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex vertex = iter.next(); + Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()); + // if (!isAbstract) { + String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty()); + String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty()); + + if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) { + String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty()); + if (name.startsWith("ci")) { + if (resourceType.equals(ResourceTypeEnum.VF.name())) { + vfResourcesToDelete.add(id); + } else { + nonVfResourcesToDelete.add(id); + } + } + } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) { + if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) { + vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); + } + } + // } + } + } + vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices(); + if (vertices != null) { + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex vertex = iter.next(); + String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty()); + if (name.startsWith("ci")) { + servicesToDelete.add(id); + } + } + } + + vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices(); + if (vertices != null) { + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex vertex = iter.next(); + String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty()); + if (name.startsWith("Ci")) { + productsToDelete.add(id); + } + } + } + + // Getting categories + + vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices(); + if (vertices != null) { + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex category = iter.next(); + String name = category.value(GraphPropertiesDictionary.NAME.getProperty()); + if (!resourceCategoriesNotToDelete.contains(name)) { + String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + resourceCategoriesToDelete.add(catId); + Iterator subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty()); + while (subs.hasNext()) { + Vertex sub = subs.next(); + String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + resourceSubsToDelete.add(new ImmutablePair(catId, subCatId)); + } + } + } + } + + vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices(); + if (vertices != null) { + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex category = iter.next(); + String name = category.value(GraphPropertiesDictionary.NAME.getProperty()); + if (!serviceCategoriesNotToDelete.contains(name)) { + String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + serviceCategoriesToDelete.add(id); + } + } + } + + vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices(); + if (vertices != null) { + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex category = iter.next(); + String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + productCategoriesToDelete.add(catId); + Iterator subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty()); + while (subs.hasNext()) { + Vertex sub = subs.next(); + String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + productSubsToDelete.add(new ImmutablePair(catId, subCatId)); + Iterator groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty()); + while (groupings.hasNext()) { + Vertex grouping = groupings.next(); + String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + productGroupingsToDelete.add(new ImmutableTriple(catId, subCatId, groupId)); + } + } + + } + } + + titanGraph.tx().commit(); + + String adminId = UserRoleEnum.ADMIN.getUserId(); + String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId(); + + // Component delete + for (String id : productsToDelete) { + RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId); + + } + for (String id : servicesToDelete) { + RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId); + + } + for (String id : vfResourcesToDelete) { + RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId); + + } + + for (String id : nonVfResourcesToDelete) { + RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId); + + } + + // Categories delete - product + String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE; + for (ImmutableTriple triple : productGroupingsToDelete) { + CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType); + } + for (ImmutablePair pair : productSubsToDelete) { + CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType); + } + for (String id : productCategoriesToDelete) { + CategoryRestUtils.deleteCategory(id, productStrategistId, componentType); + } + + // Categories delete - resource + componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE; + for (ImmutablePair pair : resourceSubsToDelete) { + CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType); + } + for (String id : resourceCategoriesToDelete) { + CategoryRestUtils.deleteCategory(id, adminId, componentType); + } + // Categories delete - resource + componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE; + for (String id : serviceCategoriesToDelete) { + CategoryRestUtils.deleteCategory(id, adminId, componentType); + } + + } + + private static void deleteCreatedComponents(Map> convertCatalogResponseToJavaObject) throws IOException { + final String userId = UserRoleEnum.DESIGNER.getUserId(); + + List resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME); + if (resourcesArrayList.size() > 0) { + List collect = buildCollectionUniqueId(resourcesArrayList); + for (String uId : collect) { + ProductRestUtils.deleteProduct(uId, userId); + } + } + + + resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME); + if (resourcesArrayList.size() > 0) { + List collect = buildCollectionUniqueId(resourcesArrayList); + for (String uId : collect) { + ServiceRestUtils.markServiceToDelete(uId, userId); + } + ServiceRestUtils.deleteMarkedServices(userId); + } + + + resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME); + + // List collect = resourcesArrayList.stream().filter(s -> + // s.getName().startsWith("ci")).map(e -> + // e.getUniqueId()).collect(Collectors.toList()); + + // List> collect = + // resourcesArrayList.stream().filter(s -> + // s.getName().startsWith("ci")).map(e -> + // e.getAllVersions()).collect(Collectors.toList()); + /* + * List collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList()); + */ + + if (!CollectionUtils.isEmpty(resourcesArrayList)) { + List collect = buildCollectionUniqueId(resourcesArrayList); + for (String uId : collect) { + ResourceRestUtils.markResourceToDelete(uId, userId); + } + ResourceRestUtils.deleteMarkedResources(userId); + } + + + + } + + private void deleteCollection(List componentArrayList, Consumer deleteHandler) { + + if (componentArrayList.size() > 0) { + List collect = buildCollectionUniqueId(componentArrayList); + for (String uId : collect) { + deleteHandler.accept(uId); + // ProductRestUtils.deleteProduct(uId, userId); + } + } + } + + protected static List buildCollectionUniqueId(List resourcesArrayList) { + + // Stream flatMap = resourcesArrayList.stream().filter(s -> + // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e -> + // e.values()).flatMap( e -> e.stream()); + + // List collect = resourcesArrayList.stream() + // // + // .filter(s -> s.getName().startsWith("ci") ) + // // + // .map(e -> e.getUniqueId()) + + // .map( e -> e.values()) + // .filter(out -> out!=null ) + // .flatMap( e -> e.stream()) + // .collect(Collectors.toList()); + + // List collect = resourcesArrayList.stream().filter(s -> + // s.getName().startsWith("ci")) + // .flatMap(e -> + // e.getAllVersions().values().stream()).collect(Collectors.toList()); + ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType(); + + List genericCollection = new ArrayList(); + + resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> { + buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i); + }); + + + // + + // List collect = + // genericCollection.stream().collect(Collectors.toList()); + + return genericCollection; + } + + public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum, + List genericCollection, String i) { + try { + switch (componentTypeEnum) { + case RESOURCE: + RestResponse resource = ResourceRestUtils.getResource(i); + Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse()); + Map allVersions = convertResourceResponseToJavaObject.getAllVersions(); + Collection values = allVersions.values(); + genericCollection.addAll(values); + + break; + case SERVICE: + RestResponse service = ServiceRestUtils.getService(i); + Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse()); + allVersions = convertServiceResponseToJavaObject.getAllVersions(); + values = allVersions.values(); + genericCollection.addAll(values); + + break; + + + case PRODUCT: + RestResponse product = ProductRestUtils.getProduct(i); + Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse()); + allVersions = convertProductResponseToJavaObject.getAllVersions(); + values = allVersions.values(); + genericCollection.addAll(values); + + break; + + // default: + // break; + } + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + protected static Map> getCatalogAsMap() throws Exception { + RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId()); + Map> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse()); + return convertCatalogResponseToJavaObject; + } + protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception { + // create new resource from Csar + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + + resourceDetails.setCsarUUID(csarId); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse()); + return createdResource; + } + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java new file mode 100644 index 0000000000..47efca66d0 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java @@ -0,0 +1,764 @@ +/*- + * ============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.ci.tests.api; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.Product; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.http.RestResponse; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.Assert; + +public class ComponentInstanceBaseTest extends ComponentBaseTest { + public static final String acceptHeaderData = "application/json"; + // Req/cap of container component + protected Map> expectedContainerCapabilities; + protected Map> expectedContainerRequirements; + protected Map>> removedRequirements; + protected Map>, Map>>> expectedContInstReqCap; + + protected User sdncPsDetails1; + protected User sdncPsDetails2; + protected User sdncPmDetails1; + protected User sdncPmDetails2; + protected User sdncDesignerDetails; + protected User sdncAdminDetails; + protected User sdncTesterDetails; + protected ResourceReqDetails resourceDetailsVFC_01; + protected ResourceReqDetails resourceDetailsVFC_02; + protected ResourceReqDetails resourceDetailsVF_01; + protected ResourceReqDetails resourceDetailsVF_02; + protected ResourceReqDetails resourceDetailsCP_01; + protected ResourceReqDetails resourceDetailsCP_02; + protected ResourceReqDetails resourceDetailsVL_01; + protected ResourceReqDetails resourceDetailsVL_02; + protected ServiceReqDetails serviceDetails_01; + protected ServiceReqDetails serviceDetails_02; + protected ServiceReqDetails serviceDetails_03; + protected ProductReqDetails productDetails_01; + protected ProductReqDetails productDetails_02; + + public void init() { + // Req/caps of inner componentInstances + expectedContainerCapabilities = new LinkedHashMap>(); + expectedContainerRequirements = new LinkedHashMap>(); + removedRequirements = new HashMap<>(); + expectedContInstReqCap = new HashMap<>(); + + sdncPsDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + sdncPsDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2); + sdncPmDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + sdncPmDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2); + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + resourceDetailsVFC_01 = ElementFactory.getDefaultResourceByType("ciVFC100", NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString()); // resourceType = VFC + 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()); + 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()); + resourceDetailsVL_02 = ElementFactory.getDefaultResourceByType("ciVL200", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString()); + serviceDetails_01 = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId()); + serviceDetails_02 = ElementFactory.getDefaultService("ciNewtestservice2", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId()); + serviceDetails_03 = ElementFactory.getDefaultService("ciNewtestservice3", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId()); + productDetails_01 = ElementFactory.getDefaultProduct("ciProduct01"); + productDetails_02 = ElementFactory.getDefaultProduct("ciProduct02"); + } + + public ComponentInstanceBaseTest(TestName testName, String className) { + super(testName, className); + } + + public void verifyVFReqCap(String componentId) throws Exception { + RestResponse restResponse = ResourceRestUtils.getResource(componentId); + Resource resource = ResponseParser.parseToObject(restResponse.getResponse(), Resource.class); + verifyReqCap(resource); + } + + public void verifyServiceReqCap(String componentId) throws Exception { + RestResponse restResponse = ServiceRestUtils.getService(componentId, sdncDesignerDetails); + Service service = ResponseParser.parseToObject(restResponse.getResponse(), Service.class); + verifyReqCap(service); + } + + public void verifyProductReqCap(String componentId) throws Exception { + RestResponse restResponse = ProductRestUtils.getProduct(componentId, sdncPsDetails1.getUserId()); + Product product = ResponseParser.parseToObject(restResponse.getResponse(), Product.class); + verifyReqCap(product); + } + + public void verifyReqCap(Component actualComponent) { + verifyContainerReqCap(actualComponent); + verifyCompInstReqCap(actualComponent); + } + + public RestResponse changeServiceInstanceVersion(String componentUniqueId, String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType, boolean isHighestLevel) throws Exception { + RestResponse changeResourceInstanceVersion = ProductRestUtils.changeServiceInstanceVersion(componentUniqueId, serviceInstanceToReplaceUniqueId, serviceUniqueId, sdncModifierDetails, componentType); + if (changeResourceInstanceVersion.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS) && isHighestLevel) { + /* + * // Add RI Capabilities and Requirements to expected MAP --> expectedVfCapabilities and expectedVfRequirements + * + * ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper( changeResourceInstanceVersion.getResponse(), ComponentInstance.class); addCompInstReqCapToExpected(componentInstance, componentType); + */ + } + return changeResourceInstanceVersion; + } + + protected void updateExpectedReqCapAfterChangeLifecycleState(String oldContainerUniqueIdToReplace, String newContainerUniqueId) { + + // Update of container req/cap + + Set compInstKeysToChange = new HashSet<>(); + + for (String expKey : expectedContainerCapabilities.keySet()) { + List expCapList = expectedContainerCapabilities.get(expKey); + for (CapabilityDefinition cap : expCapList) { + String ownerId = cap.getOwnerId(); + + if (ownerId.contains(oldContainerUniqueIdToReplace)) { + compInstKeysToChange.add(ownerId); + cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + } + } + } + + for (String expKey : expectedContainerRequirements.keySet()) { + List expCapList = expectedContainerRequirements.get(expKey); + for (RequirementDefinition cap : expCapList) { + String ownerId = cap.getOwnerId(); + if (ownerId.contains(oldContainerUniqueIdToReplace)) { + compInstKeysToChange.add(ownerId); + cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + } + } + } + + // Update of internal comp instances req/cap + for (String oldKey : compInstKeysToChange) { + ImmutablePair>, Map>> immutablePair = expectedContInstReqCap.get(oldKey); + if (immutablePair != null) { + expectedContInstReqCap.remove(oldKey); + String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId); + expectedContInstReqCap.put(newKey, immutablePair); + } + } + + // Update of removed req + for (String oldKey : compInstKeysToChange) { + Map> map = removedRequirements.get(oldKey); + if (map != null) { + removedRequirements.remove(oldKey); + String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId); + Collection> values = map.values(); + if (values != null) { + for (List list : values) { + for (RequirementDefinition reqDef : list) { + reqDef.setOwnerId(reqDef.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + } + } + } + removedRequirements.put(newKey, map); + } + } + } + + private void verifyCompInstReqCap(Component actualComponent) { + List componentInstances = actualComponent.getComponentInstances(); + if (componentInstances != null) { + assertEquals(expectedContInstReqCap.size(), componentInstances.size()); + for (ComponentInstance compInst : componentInstances) { + String uniqueId = compInst.getUniqueId(); + // System.out.println("Verifying req/cap of component instance + // "+ uniqueId); + Map> actualCompInstReq = compInst.getRequirements(); + if (actualCompInstReq == null) { + actualCompInstReq = new HashMap<>(); + } + Map> actualCompInstCap = compInst.getCapabilities(); + if (actualCompInstCap == null) { + actualCompInstCap = new HashMap<>(); + } + ImmutablePair>, Map>> expReqCap = expectedContInstReqCap.get(uniqueId); + assertNotNull(expReqCap); + // System.out.println("expected instance requirements: + // "+expReqCap.right); + // System.out.println("expected instance capabilities: + // "+expReqCap.left); + // System.out.println("actual instance requirements: + // "+actualCompInstReq); + // System.out.println("actual instance capabilities: + // "+actualCompInstCap); + + // REQ comparison + compareReqCapMaps(expReqCap.right, actualCompInstReq); + + // CAP comparison + compareReqCapMaps(expReqCap.left, actualCompInstCap); + } + + } else { + assertTrue(expectedContInstReqCap.isEmpty()); + } + } + + private void verifyContainerReqCap(Component actualComponent) { + Map> actualContainerRequirements = actualComponent.getRequirements(); + if (actualContainerRequirements == null) { + actualContainerRequirements = new HashMap<>(); + } + Map> actualContainerCapabilities = actualComponent.getCapabilities(); + if (actualContainerCapabilities == null) { + actualContainerCapabilities = new HashMap<>(); + } + // System.out.println("Verifying req/cap of container component "+ + // actualComponent.getUniqueId()); + // System.out.println("expected container requirements: + // "+expectedContainerRequirements); + // System.out.println("expected container capabilities: + // "+expectedContainerCapabilities); + // System.out.println("actual container requirements: + // "+actualContainerRequirements); + // System.out.println("actual container capabilities: + // "+actualContainerCapabilities); + + // REQ comparison + compareReqCapMaps(expectedContainerRequirements, actualContainerRequirements); + + // CAP comparison + compareReqCapMaps(expectedContainerCapabilities, actualContainerCapabilities); + } + + private void compareReqCapMaps(Map> expectedMap, Map> actualMap) { + assertEquals(expectedMap.size(), actualMap.size()); + for (String expKey : expectedMap.keySet()) { + List expCapList = expectedMap.get(expKey); + List actCapList = actualMap.get(expKey); + assertEquals(expCapList.size(), actCapList.size()); + assertEquals(new HashSet<>(expCapList), new HashSet<>(actCapList)); + } + } + + public void addCompInstReqCapToExpected(ComponentInstance componentInstance, ComponentTypeEnum containerComponentType) throws Exception { + String uniqueId = componentInstance.getUniqueId(); + String name = componentInstance.getName(); + String originComponentId = componentInstance.getComponentUid(); + RestResponse getResponse = null; + ComponentTypeEnum compInstType = getCompInstTypeByContainerType(containerComponentType); + Component component = null; + if (compInstType == ComponentTypeEnum.RESOURCE) { + getResponse = ResourceRestUtils.getResource(sdncDesignerDetails, originComponentId); + ResourceRestUtils.checkSuccess(getResponse); + component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class); + } else if (compInstType == ComponentTypeEnum.SERVICE) { + getResponse = ServiceRestUtils.getService(originComponentId, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getResponse); + component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class); + } else { + Assert.fail("Unsupported type - " + containerComponentType); + } + + Map> resourceRequirements = component.getRequirements(); + if (resourceRequirements == null) { + resourceRequirements = new HashMap<>(); + } + + Function>, List> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList())); + Map> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper)); + + Map> resourceCapabilities = component.getCapabilities(); + if (resourceCapabilities == null) { + resourceCapabilities = new HashMap<>(); + } + + Function>, List> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList())); + Map> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper)); + + setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities); + if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) { + setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy); + } + + // adding entry for expected componentInstance + ImmutablePair>, Map>> compInstReqCapPair = new ImmutablePair>, Map>>(capCopy, reqCopy); + expectedContInstReqCap.put(uniqueId, compInstReqCapPair); + } + + private void setupContainerExpectedReqCap(String uniqueId, String name, Map> componentRequirements, Map> componentCapabilities) { + for (Entry> resReq : componentRequirements.entrySet()) { + List reqListToAdd = resReq.getValue(); + for (RequirementDefinition requirementDefinition : reqListToAdd) { + requirementDefinition.setOwnerId(uniqueId); + requirementDefinition.setOwnerName(name); + } + List expectedReqList = expectedContainerRequirements.get(resReq.getKey()); + if (expectedReqList == null) { + expectedReqList = reqListToAdd; + } else { + expectedReqList.addAll(reqListToAdd); + } + expectedContainerRequirements.put(resReq.getKey(), expectedReqList); + } + + for (Entry> resCap : componentCapabilities.entrySet()) { + List capListToAdd = resCap.getValue(); + for (CapabilityDefinition capDefinition : capListToAdd) { + capDefinition.setOwnerId(uniqueId); + capDefinition.setOwnerName(name); + } + List expectedCapList = expectedContainerCapabilities.get(resCap.getKey()); + if (expectedCapList == null) { + expectedCapList = capListToAdd; + } else { + expectedCapList.addAll(capListToAdd); + } + expectedContainerCapabilities.put(resCap.getKey(), expectedCapList); + } + } + + private void setupConstInstExpectedReqCap(String uniqueId, String name, Map> componentRequirements, Map> componentCapabilities) { + for (Entry> resReq : componentRequirements.entrySet()) { + List reqListToAdd = resReq.getValue(); + for (RequirementDefinition requirementDefinition : reqListToAdd) { + requirementDefinition.setOwnerId(uniqueId); + requirementDefinition.setOwnerName(name); + } + } + + for (Entry> resCap : componentCapabilities.entrySet()) { + List capListToAdd = resCap.getValue(); + for (CapabilityDefinition capDefinition : capListToAdd) { + capDefinition.setOwnerId(uniqueId); + capDefinition.setOwnerName(name); + } + } + } + + private ComponentTypeEnum getCompInstTypeByContainerType(ComponentTypeEnum componentType) { + switch (componentType) { + case RESOURCE: + return ComponentTypeEnum.RESOURCE; + case SERVICE: + return ComponentTypeEnum.RESOURCE; + case PRODUCT: + return ComponentTypeEnum.SERVICE; + default: + break; + } + return null; + } + + public void deleteCompInstReqCapFromExpected(String componentInstanceId) { + List entriesRequirementsToRemove = new ArrayList<>(); + List entriesCapabilitiesToRemove = new ArrayList<>(); + for (Entry> reqEntry : expectedContainerRequirements.entrySet()) { + List reqList = reqEntry.getValue(); + List reqListToDelete = new ArrayList<>(); + for (RequirementDefinition requirementDefinition : reqList) { + if (requirementDefinition.getOwnerId().equals(componentInstanceId)) { + reqListToDelete.add(requirementDefinition); + } + } + reqList.removeAll(reqListToDelete); + if (reqList.isEmpty()) { + entriesRequirementsToRemove.add(reqEntry.getKey()); + } + } + + for (String ekey : entriesRequirementsToRemove) { + expectedContainerRequirements.remove(ekey); + } + + for (Entry> capEntry : expectedContainerCapabilities.entrySet()) { + List capList = capEntry.getValue(); + List capListToDelete = new ArrayList<>(); + for (CapabilityDefinition capabilityDefinition : capList) { + if (capabilityDefinition.getOwnerId().equals(componentInstanceId)) { + capListToDelete.add(capabilityDefinition); + } + } + capList.removeAll(capListToDelete); + if (capList.isEmpty()) { + entriesCapabilitiesToRemove.add(capEntry.getKey()); + } + } + for (String ekey : entriesCapabilitiesToRemove) { + expectedContainerCapabilities.remove(ekey); + } + + expectedContInstReqCap.remove(componentInstanceId); + + } + + // Automatically updates the expected req/cap of the container + protected RestResponse createAtomicInstanceForVF(ResourceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, true); + } + + // Automatically updates the expected req/cap of the container + protected RestResponse createAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true); + } + + // Automatically updates the expected req/cap of the container + protected RestResponse createVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true); + } + + // Automatically updates the expected req/cap of the container + protected RestResponse createServiceInstance(ProductReqDetails containerDetails, ServiceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, true); + } + + // Automatically updates the expected req/cap of the container + protected RestResponse deleteAtomicInstanceForVF(String compInstUniqueId, ResourceReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, true); + } + + // Automatically updates the expected req/cap of the container + protected RestResponse deleteAtomicInstanceForService(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true); + } + + // Automatically updates the expected req/cap of the container + protected RestResponse deleteVFInstance(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true); + + } + + // Automatically updates the expected req/cap of the container + protected RestResponse deleteServiceInstance(String compInstUniqueId, ProductReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, true); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse createAtomicInstanceForVFDuringSetup(ResourceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse createAtomicInstanceForServiceDuringSetup(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse createVFInstanceDuringSetup(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse createServiceInstanceDuringSetup(ProductReqDetails containerDetails, ServiceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse deleteAtomicInstanceForVFDuringSetup(String compInstUniqueId, ResourceReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse deleteAtomicInstanceForServiceDuringSetup(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse deleteVFInstanceDuringSetup(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false); + + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + protected RestResponse deleteServiceInstanceDuringSetup(String compInstUniqueId, ProductReqDetails containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, false); + } + + protected Component getComponentAndValidateRIs(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); + verifyReqCap(component); + + return component; + } + + protected void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws IOException, Exception { + updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId()); + getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations); + } + + private RestResponse createComponentInstance(ComponentReqDetails containerDetails, ComponentReqDetails compInstOriginDetails, User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel) throws IOException, Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(compInstOriginDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum); + if (createResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED) && isHighestLevel) { + // Add RI Capabilities and Requirements to expected MAP --> + // expectedVfCapabilities and expectedVfRequirements + ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, containerComponentTypeEnum); + } + return createResourceInstanceResponse; + } + + private RestResponse deleteComponentInstance(String compInstUniqueId, ComponentReqDetails containerDetails, User modifier, ComponentTypeEnum componentTypeEnum, boolean isHighestLevel) throws Exception { + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(modifier, containerDetails.getUniqueId(), compInstUniqueId, componentTypeEnum); + if (deleteResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_DELETE) && isHighestLevel) { + deleteCompInstReqCapFromExpected(compInstUniqueId); + } + return deleteResourceInstanceResponse; + } + + // Create Atomic resource ( VFC/CP/VL) + protected void createAtomicResource(ResourceReqDetails resourceDetails) throws Exception { + RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceResponse); + + } + + protected void createVF(ResourceReqDetails resourceDetails) throws Exception { + createVF(resourceDetails, sdncDesignerDetails); + + } + + protected void createVF(ResourceReqDetails resourceDetails, User sdncModifier) throws Exception { + RestResponse createVfResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifier); + ResourceRestUtils.checkCreateResponse(createVfResponse); + } + + protected void createService(ServiceReqDetails serviceDetails) throws Exception { + createService(serviceDetails, sdncDesignerDetails); + } + + protected void createService(ServiceReqDetails serviceDetails, User sdncModifier) throws Exception { + RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifier); + ResourceRestUtils.checkCreateResponse(createServiceResponse); + } + + protected void createProduct(ProductReqDetails productDetails) throws Exception { + createProduct(productDetails, sdncPmDetails1); + } + + protected void createProduct(ProductReqDetails productDetails, User sdncModifier) throws Exception { + RestResponse createProductResponse = ProductRestUtils.createProduct(productDetails, sdncModifier); + ResourceRestUtils.checkCreateResponse(createProductResponse); + } + + protected RestResponse associateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, ComponentReqDetails containerDetails, User user) throws IOException { + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, user, containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + deleteAssociatedFromExpected(requirementDef); + + return associateInstances; + } + + private void deleteAssociatedFromExpected(RequirementCapabilityRelDef requirementDef) { + // removing from requirements + RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0); + String type = relationship.getRelationship().getType(); + String fromId = requirementDef.getFromNode(); + List reqList = expectedContainerRequirements.get(type); + List capList = expectedContainerCapabilities.get(type); + RequirementDefinition toDelete = null; + if (reqList != null) { + for (RequirementDefinition reqDef : reqList) { + if (reqDef.getOwnerId().equals(fromId)) { + toDelete = reqDef; + } + } + if (toDelete != null) { + reqList.remove(toDelete); + if (reqList.isEmpty()) { + expectedContainerRequirements.remove(type); + } + String ownerId = toDelete.getOwnerId(); + Map> map = removedRequirements.get(ownerId); + if (map == null) { + map = new HashMap<>(); + removedRequirements.put(ownerId, map); + } + List list = map.get(type); + if (list == null) { + list = new ArrayList<>(); + map.put(type, list); + } + list.add(toDelete); + } + } + + for (CapabilityDefinition capabilityDefinition : capList) { + if (capabilityDefinition.getType().equals(type)) { + int minOccurrences = Integer.parseInt(capabilityDefinition.getMinOccurrences()) - 1; + if (minOccurrences < 0) + minOccurrences = 0; + String minOccurrencesString = Integer.toString(minOccurrences); + capabilityDefinition.setMinOccurrences(minOccurrencesString); + if (!capabilityDefinition.getMaxOccurrences().equals("UNBOUNDED")) { + int maxOccurrences = Integer.parseInt(capabilityDefinition.getMaxOccurrences()) - 1; + if (maxOccurrences < 0) + maxOccurrences = 0; + String maxOccurrencesString = Integer.toString(maxOccurrences); + capabilityDefinition.setMaxOccurrences(maxOccurrencesString); + } + } + } + expectedContainerCapabilities.put(type, capList); + } + + protected void dissociateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, ComponentReqDetails containerDetails, User user) throws IOException { + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user, containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(dissociateInstances); + addDissociatedToExpected(requirementDef); + } + + protected void fulfillCpRequirement(ComponentReqDetails component, String cpCompInstId, String cpReqFulfillerCompInstId, String cpReqFulfillerOwnerId, User user, ComponentTypeEnum containerCompType) throws IOException { + // Fulfilling cp's "binding" requirement - US626240 + String requirementName = "binding"; + String capType = "tosca.capabilities.network.Bindable"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(user, component); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef reqCapRelation = ElementFactory.getReqCapRelation(cpCompInstId, cpReqFulfillerCompInstId, cpCompInstId, cpReqFulfillerOwnerId, capType, requirementName, capList, reqList); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(reqCapRelation, user, component.getUniqueId(), containerCompType); + ResourceRestUtils.checkSuccess(associateInstances); + } + + protected void consumeVlCapability(ComponentReqDetails component, String vlCapConsumerCompInstId, String vlCompInstId, String vlCapConsumerOwnerId, User user, ComponentTypeEnum containerCompType) throws IOException { + // Consuming vl's "link" capability - US626240 + String requirementName = "link"; + String capType = "tosca.capabilities.network.Linkable"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(user, component); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef reqCapRelation = ElementFactory.getReqCapRelation(vlCapConsumerCompInstId, vlCompInstId, vlCapConsumerOwnerId, vlCompInstId, capType, requirementName, capList, reqList); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(reqCapRelation, user, component.getUniqueId(), containerCompType); + ResourceRestUtils.checkSuccess(associateInstances); + } + + private void addDissociatedToExpected(RequirementCapabilityRelDef requirementDef) { + // adding to requirements + RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0); + String type = relationship.getRelationship().getType(); + String fromId = requirementDef.getFromNode(); + Map> map = removedRequirements.get(fromId); + if (map != null) { + List list = map.get(type); + if (list != null && !list.isEmpty()) { + List reqList = expectedContainerRequirements.get(type); + if (reqList == null) { + reqList = new ArrayList<>(); + expectedContainerRequirements.put(type, reqList); + } + reqList.add(list.remove(0)); + } + } + + List capList = expectedContainerCapabilities.get(type); + + for (CapabilityDefinition capabilityDefinition : capList) { + if (capabilityDefinition.getType().equals(type)) { + int minOccurrences = Integer.parseInt(capabilityDefinition.getMinOccurrences()) + 1; + String minOccurrencesString = Integer.toString(minOccurrences); + capabilityDefinition.setMinOccurrences(minOccurrencesString); + if (!capabilityDefinition.getMaxOccurrences().equals("UNBOUNDED")) { + int maxOccurrences = Integer.parseInt(capabilityDefinition.getMaxOccurrences()) + 1; + String maxOccurrencesString = Integer.toString(maxOccurrences); + capabilityDefinition.setMaxOccurrences(maxOccurrencesString); + } + } + } + expectedContainerCapabilities.put(type, capList); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java new file mode 100644 index 0000000000..2b970fd8a1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java @@ -0,0 +1,72 @@ +/*- + * ============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.ci.tests.api; + +import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.reporter.ExtentHtmlReporter; +import com.aventstack.extentreports.reporter.ExtentXReporter; +import com.aventstack.extentreports.reporter.configuration.Protocol; +import com.aventstack.extentreports.reporter.configuration.Theme; + +public class ExtentManager { + + private static ExtentReports extent; + + public synchronized static ExtentReports getReporter(String filePath) { + if (extent == null) { + // initialize the HtmlReporter + ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(filePath); + + // initialize ExtentReports and attach the HtmlReporter + extent = new ExtentReports(); + + // attach all reporters + extent.attachReporter(htmlReporter); + + + } + + return extent; + } + + public synchronized static ExtentHtmlReporter setConfiguration(ExtentHtmlReporter htmlReporter) { + htmlReporter.config().setTheme(Theme.STANDARD); + + htmlReporter.config().setEncoding("UTF-8"); + + htmlReporter.config().setProtocol(Protocol.HTTPS); + + htmlReporter.config().setDocumentTitle("ASDC Automation Report"); + + htmlReporter.config().setChartVisibilityOnOpen(true); + + htmlReporter.config().setReportName(AutomationUtils.getOSVersion()); + + return htmlReporter; + } + + public synchronized static ExtentReports getReporter() { + return extent; + } +} + diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java new file mode 100644 index 0000000000..9c4acd4367 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.api; + +import java.util.HashMap; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.ExtentTest; + + +public class ExtentTestManager { + + private static HashMap extentTestMap = new HashMap(); + private static ExtentReports extent = ExtentManager.getReporter(); + + public static synchronized ExtentTest getTest() { + return extentTestMap.get(Thread.currentThread().getId()); + } + + public static synchronized void endTest() { +// extent.endTest(extentTestMap.get(Thread.currentThread().getId())); +// extentTestMap.get(Thread.currentThread().getId()); // This is test + // TODO: maybe uncomment becuase we will need it only at the end + extent.flush(); + } + + public static synchronized ExtentTest startTest(String testName) { + return startTest(testName, ""); + } + + public static synchronized ExtentTest startTest(String testName, String desc) { + ExtentTest test = extent.createTest(testName, desc); + extentTestMap.put(Thread.currentThread().getId(), test); + + return test; + } +} + 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 new file mode 100644 index 0000000000..3977f16d5a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java @@ -0,0 +1,368 @@ +/*- + * ============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.ci.tests.api; + +public interface Urls { + + final String UPLOAD_ZIP_URL = "http://%s:%s/sdc1/rest/v1/catalog/resources"; + final String GET_IMAGE_DATA_FROM_ES = "http://%s:%s/resources/imagedata/_search?q=resourceName:%s&pretty=true&size=1000"; + final String GET_SCRIPT_DATA_FROM_ES = "http://%s:%s/resources/artifactdata/_search?q=resourceName:%s&pretty=true&size=1000"; + final String GET_ID_LIST_BY_INDEX_FROM_ES = "http://%s:%s/%s/%s/_search?fields=_id&size=1000"; + + final String ES_URL = "http://%s:%s"; + final String GET_SERVICE_CSAR_API1 = "http://%s:%s/sdc2/rest/services/%s/%s"; + final String GET_SERVICE_CSAR_API2 = "http://%s:%s/sdc2/rest/services/%s/%s/csar"; + + final String GET_SERVICE_CSAR_FE_PROXY_API1 = "http://%s:%s/sdc1/portal/rest/services/%s/%s"; + final String GET_CSAR_USING_SIMULATOR = "http://%s:%s/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages/%s"; + final String COPY_CSAR_USING_SIMULATOR = "http://%s:%s/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages/%s/%s"; + + final String GET_HEALTH_CHECK_VIA_PROXY = "http://%s:%s/sdc1/rest/healthCheck"; + + // Get back-end config http://172.20.43.132:8080/sdc2/rest/configmgr/get + final String GET_CONFIG_MANAGER = "http://%s:%s/sdc2/rest/configmgr/get"; + + // Get latest version of all non-abstract resources + final String GET_RESOURCE_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/latestversion/notabstract"; + + final String GET_SERVICE_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/latestversion/notabstract"; + + // 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"; + + // get resource artifact metadata (creation, MD5, etc): + // http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts/install_apache.sh/metadata + final String GET_RESOURCE_ARTIFACT_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s/metadata"; + + // resource artifact payload: + // http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts/install_apache.sh + final String GET_RESOURCE_ARTIFACT_PAYLOAD = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s"; + + final String GET_RESOURCE_ARTIFACT_PAYLOAD_FE_PROXY = "http://%s:%s/sdc1/portal/rest/v1/catalog/resources/%s/%s/artifacts/%s"; + + // Get service list: http://172.20.43.124:8080/sdc2/rest/v1/catalog/services + final String GET_SERVICE_LIST = "http://%s:%s/sdc2/rest/v1/catalog/services"; + + // Get service versions: + // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/MyService + final String GET_SERVICE_VERSIONS = "http://%s:%s/sdc2/rest/v1/catalog/services/%s"; + + // Get service artifact list: + // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/alien.nodes.Apache/0.0.1/artifacts + final String GET_SERVICE_ARTIFACTS_LIST = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/%s/artifacts"; + + // get service artifact metadata (creation, MD5, etc): + // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/alien.nodes.Apache/0.0.1/artifacts/install_apache.sh/metadata + final String GET_SERVICE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s/metadata"; + + // service artifact payload: + // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/alien.nodes.Apache/0.0.1/artifacts/install_apache.sh + final String GET_SERVICE_ARTIFACT_PAYLOAD = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s"; + + final String GET_SEARCH_DATA_FROM_ES = "http://%s:%s/%s"; + + // ****************************************************USER + // URLs******************************************************** + final String GET_USER = "http://%s:%s/sdc2/rest/v1/user/%s"; + + final String GET_USER_ROLE = "http://%s:%s/sdc2/rest/v1/user/%s/role"; + + final String CREATE_USER = "http://%s:%s/sdc2/rest/v1/user"; + + final String UPDATE_USER = "http://%s:%s/sdc2/rest/v1/user/%s"; + + final String UPDATE_USER_ROLE = "http://%s:%s/sdc2/rest/v1/user/%s/role"; + + final String DELETE_USER = "http://%s:%s/sdc2/rest/v1/user/%s"; + + final String GET_ALL_ADMIN_USERS = "http://%s:%s/sdc2/rest/v1/user/admins"; + + final String AUTHORIZE_USER = "http://%s:%s/sdc2/rest/v1/user/authorize"; + + final String GET_ALL_TAGS = "http://%s:%s/sdc2/rest/v1/tags"; + + final String AUTH_USER = "http://%s:%s/sdc2/rest/v1/user/authorize"; + + final String GET_ALL_NOT_ABSTRACT_RESOURCES = "http://%s:%s/sdc2/rest/v1/catalog/resources/certified/notabstract"; + + final String GET_ALL_ABSTRACT_RESOURCES = "http://%s:%s/sdc2/rest/v1/catalog/resources/certified/abstract"; + + final String QUERY_NEO4J = "http://%s:%s/db/data/transaction"; + final String CHANGE_IN_NEO4J = "http://%s:%s/db/data/transaction/commit"; + + final String GET_ALL_ADMINS = "http://%s:%s/sdc2/rest/v1/user/admins"; + + final String GET_USERS_BY_ROLES = "http://%s:%s/sdc2/rest/v1/user/users?roles=%s"; + + final String GET_ALL_USERS = "http://%s:%s/sdc2/rest/v1/user/users?roles/"; + + // *****************************************ECOMP User + // URL's***************************************************** + final String ECOMP_PUSH_USER = "http://%s:%s/api/user"; + + final String ECOMP_EDIT_USER = "http://%s:%s/api/user/%s"; + + final String ECOMP_GET_USER = "http://%s:%s/api/user/%s"; + + final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/users"; + + final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/roles"; + + final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/user/%s/roles"; + + final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/user/%s/roles"; + + // *****************************************Elements************************************************************* + final String GET_TAGS_LIST = "http://%s:%s/sdc2/rest/v1/tags"; + + final String GET_PROPERTY_SCOPES_LIST = "http://%s:%s/sdc2/rest/v1/propertyScopes"; + + final String GET_CONFIGURATION = "http://%s:%s/sdc2/rest/v1/configuration/ui"; + + final String GET_ALL_ARTIFACTS = "http://%s:%s/sdc2/rest/v1/artifactTypes"; + + final String GET_FOLLWED_LIST = "http://%s:%s/sdc2/rest/v1/followed"; + + final String GET_CATALOG_DATA = "http://%s:%s/sdc2/rest/v1/screen"; + + // *****************************************Resources + // ********************************************************************** + final String GET_LIST_CERTIFIED_RESOURCE_TEMPLATES = "http://%s:%s/sdc2/rest/v1/resoourceTemplates"; + + final String CREATE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources"; + final String UPDATE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s"; + + final String IMPORT_RESOURCE_NORMATIVE = "http://%s:%s/sdc2/rest/v1/catalog/upload/multipart"; + + final String IMPORT_USER_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/upload/user-resource"; + + final String IMPORT_CAPABILITY_TYPE = "http://%s:%s/sdc2/rest/v1/catalog/uploadType/capability"; + final String IMPORT_CATEGORIES = "http://%s:%s/sdc2/rest/v1/catalog/uploadType/categories"; + final String IMPORT_GROUP_TYPE = "http://%s:%s/sdc2/rest/v1/catalog/uploadType/grouptypes"; + + // last %s is resourceId, resourceId = resourceName.resourceVersion + final String GET_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s"; + final String GET_RESOURCE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/resourceName/%s/resourceVersion/%s"; + final String GET_RESOURCE_BY_CSAR_UUID = "http://%s:%s/sdc2/rest/v1/catalog/resources/csar/%s"; + final String GET_COMPONENT_REQUIRMENTS_CAPABILITIES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/requirmentsCapabilities"; + + final String DELETE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s"; + final String DELETE_RESOURCE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s"; + final String DELETE_SERVICE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/%s"; + + final String DELETE_MARKED_RESOURCES = "http://%s:%s/sdc2/rest/v1/inactiveComponents/resource"; + final String DELETE_MARKED_SERVICES = "http://%s:%s/sdc2/rest/v1/inactiveComponents/service"; + + final String GET_FOLLOWED_RESOURCES = "http://%s:%s/sdc2/rest/v1/followed/resources/%s"; + final String CHANGE_RESOURCE_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/lifecycleState/%s"; + final String CHANGE_SERVICE_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/lifecycleState/%s"; + final String CHANGE_PRODUCT_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/products/%s/lifecycleState/%s"; + final String CHANGE_COMPONENT_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/lifecycleState/%s"; + + final String CREATE_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties"; + + final String UPDATE_RESOURCE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/metadata"; + + // ***********************************External API's + // (AssetData)**************************************** + + 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/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/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/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/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/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/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/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/sdc/v1/catalog/resources"; + + // Change LifeCycle of Resource + // https://{serverRoot}:{port}/sdc/v1/catalog/{resources|services}/{uuid}/lifecycleState/{lifecycle state} + final String POST_EXTERNAL_API_CHANGE_LIFE_CYCLE_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/lifecycleState/%s"; + + + // ***************************************************************************************************** + + final String ADD_ARTIFACT_TO_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts"; + final String UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts/%s"; + final String ADD_ARTIFACT_TO_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts"; + final String UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts/%s"; + + final String UPLOAD_DELETE_ARTIFACT_OF_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/artifacts"; + final String UPDATE_ARTIFACT_OF_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/artifacts/%s"; + final String UPLOAD_HEAT_ENV_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/artifacts/%s"; + // ***************************************************************************************************** + final String UPLOAD_ARTIFACT_BY_INTERFACE_TO_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/"; + final String UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/%s"; + + final String UPLOAD_ARTIFACT_BY_INTERFACE_TO_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/"; + final String UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/%s"; + + // ***************************************************************************************************** + // "/sdc2/v1/services//<0.1>/artifacts/aaa.hh" + final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s"; + // "/sdc2/v1/services//<0.1>/resources/{resourceName}/{resourceVersion}/artifacts/_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 = "/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"; + // ********************************************************************************** + final String UI_DOWNLOAD_RESOURCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts/%s"; + final String UI_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts/%s"; + + // ********************************************************************************************************** + final String UPDATE_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties/%s"; + + final String DELETE_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties/%s"; + + final String GET_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties/%s"; + + // ***************************************************************************************************** + + final String VALIDATE_RESOURCE_NAME = "http://%s:%s/sdc2/rest/v1/catalog/resources/validate-name/%s"; + + final String CREATE_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services"; + final String DELETE_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s"; + final String GET_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s"; + final String GET_SERVICE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/serviceName/%s/serviceVersion/%s"; + + final String GET_SERVICES_REQUIRMENTS_CAPABILITIES = "http://%s:%s/sdc2/rest/v1/catalog/requirmentsCapabilities/services/%s"; + + final String CREATE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance"; + final String DELETE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s"; + final String UPDATE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s"; + final String GET_COMPONENT_INSTANCES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/componentInstances"; + // Tal New API + final String UPDATE_MULTIPLE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/multipleComponentInstance"; + + final String CHANGE__RESOURCE_INSTANCE_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/changeVersion"; + + final String CREATE_AND_ASSOCIATE_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/createAndAssociate"; + final String ASSOCIATE__RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/associate"; + final String DISSOCIATE__RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/dissociate"; + + final String DISTRIBUTION_INIT = "http://%s:%s/init"; + final String DISTRIBUTION_INIT_RESET = "http://%s:%s/initReset"; + final String APPROVE_DISTRIBUTION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution-state/approve"; + final String REJECT_DISTRIBUTION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution-state/reject"; + final String DISTRIBUTION_DOWNLOAD_ARTIFACT = "http://%s:%s/download"; + final String ACTIVATE_DISTRIBUTION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution/%s/activate"; + final String DISTRIBUTION_SERVICE_LIST = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution"; + + final String DEPLOY_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution/%s/markDeployed"; + final String UPDATE_SERVICE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/metadata"; + + // Andrey changed name from ADD_PROPERTY_TO_RESOURCE_INSTANCE to + // UPDATE_PROPERTY_TO_RESOURCE_INSTANCE + final String UPDATE_PROPERTY_TO_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/property"; + final String DELETE_PROPERTY_FROM_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/property/%s"; + final String UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s/heatParams"; + + // Actions on artifact in resource instance + final String ADD_RESOURCE_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts"; + final String UPDATE_RESOURCE_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s"; + final String DELETE_RESOURCE_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s"; + + // Attributes On Resource instance + public static final String UPDATE_ATTRIBUTE_ON_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/attribute"; + + // ("/services/{serviceId}/resourceInstances/{resourceInstanceId}/artifacts/{artifactId}") + final String DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s"; + + // -------------------------------service api + // artifact----------------------------------------------------- + final String UPDATE_DELETE_SERVICE_API_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts/api/%s"; + + final String CREATE_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo"; + final String UPDATE_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo/%s"; + final String DELETE_ADDITIONAL_INFORMATION_RESOURCE = UPDATE_ADDITIONAL_INFORMATION_RESOURCE; + final String GET_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo/%s"; + final String GET_ALL_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo"; + + final String CREATE_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo"; + final String UPDATE_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo/%s"; + final String DELETE_ADDITIONAL_INFORMATION_SERVICE = UPDATE_ADDITIONAL_INFORMATION_SERVICE; + final String GET_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo/%s"; + final String GET_ALL_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo"; + + final String GET_COMPONENT_AUDIT_RECORDS = "http://%s:%s/sdc2/rest/v1/catalog/audit-records/%s/%s"; + + // CONSUMER + final String CREATE_CONSUMER = "http://%s:%s/sdc2/rest/v1/consumers"; + final String GET_CONSUMER = "http://%s:%s/sdc2/rest/v1/consumers/%s"; + final String DELETE_CONSUMER = "http://%s:%s/sdc2/rest/v1/consumers/%s"; + + // Categories + final String CREATE_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s"; + final String GET_ALL_CATEGORIES = "http://%s:%s/sdc2/rest/v1/categories/%s"; + final String GET_ALL_CATEGORIES_FE = "http://%s:%s/sdc1/feProxy/rest/v1/categories/%s"; + final String DELETE_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s/%s"; + final String CREATE_SUB_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory"; + final String DELETE_SUB_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s"; + final String CREATE_GROUPING = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s/grouping"; + final String DELETE_GROUPING = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s/grouping/%s"; + + // product + final String CREATE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products"; + final String DELETE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s"; + // last %s is resourceId, productId + final String GET_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s"; + final String UPDATE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s/metadata"; + final String GET_PRODUCT_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/products/productName/%s/productVersion/%s"; + + // groups + final String GET_GROUP_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/groups/%s"; + + // modules + final String GET_MODULE_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/groups/%s"; + + // inputs + final String ADD_INPUTS = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/create/inputs"; //{componentType}/{componentId}/create/inputs + final String DELETE_INPUT_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/delete/%s/input"; //{componentType}/{componentId}/delete/{inputId}/input + final String GET_COMPONENT_INPUTS = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/inputs"; //services/{componentId}/inputs + final String GET_COMPONENT_INSTANCE_INPUTS = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/componentInstances/%s/%s/inputs"; //{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs + final String GET_INPUTS_FOR_COMPONENT_INPUT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/groups/%s"; //{componentType}/{componentId}/inputs/{inputId}/inputs + + // check version + final String ONBOARD_VERSION = "http://%s:%s/onboarding-api/docs/build-info.json"; + final String OS_VERSION = "http://%s:%s/sdc2/rest/version"; + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java new file mode 100644 index 0000000000..d2e8d14c04 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java @@ -0,0 +1,696 @@ +/*- + * ============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.ci.tests.config; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import org.yaml.snakeyaml.Yaml; + +public class Config { + + private static String WINDOWS_CONFIG_FILE = "src/main/resources/ci/conf/attsdc.yaml"; + private boolean systemUnderDebug; + private boolean rerun; + private String reportDBhost; + private int reportDBport; + + private String browser; + private String catalogBeHost; + private String esHost; + private String esPort; + private String neoHost; + private String neoPort; + private String disributionClientHost; + private String disributionClientPort; + private boolean isDistributionClientRunning; + + + private String errorConfigurationFile; + private String resourceConfigDir; + private String componentsConfigDir; + private String importResourceConfigDir; + private String importResourceTestsConfigDir; + private String importTypesConfigDir; + + private String testSuites; + + private String catalogFeHost; + private String catalogFePort; + private String catalogBePort; + private String catalogBeTlsPort; + + private String neoDBusername; + private String neoDBpassword; + + private String titanPropertiesFile; + private List packages; + private List bugs; + private List resourcesNotToDelete; + private List resourceCategoriesNotToDelete; + private List serviceCategoriesNotToDelete; + private boolean stopOnClassFailure = false; + + private String outputFolder; + private String reportName; + private String url; + private String remoteTestingMachineIP; + private String remoteTestingMachinePort; + private boolean remoteTesting; + + private String cassandraHost; + private String cassandraAuditKeySpace; + private String cassandraArtifactKeySpace; + private boolean cassandraAuthenticate; + private String cassandraUsername; + private String cassandraPassword; + private boolean cassandraSsl; + private String cassandraTruststorePath; + private String cassandraTruststorePassword; + private String windowsDownloadDirectory; + private boolean captureTraffic; + private boolean useBrowserMobProxy; + + private static Config configIt = null; + + private static Yaml yaml = new Yaml(); + + + private Config() { + super(); + } + + public static class TestPackages { + + List packages; + List bugs; + + public List getPackages() { + return packages; + } + + public void setPackages(List packages) { + this.packages = packages; + } + + public List getBugs() { + return bugs; + } + + public void setBugs(List bugs) { + this.bugs = bugs; + } + + @Override + public String toString() { + return "TestPackages [packages=" + packages + ", bugs=" + bugs + "]"; + } + + } + + public synchronized static Config instance() { + if (configIt == null) { + try { + configIt = init(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + return configIt; + } + + private static Config init() throws IOException { + + Config config = null; + + String configFile = System.getProperty("config.resource"); + if (configFile == null) { + if (System.getProperty("os.name").contains("Windows")) { + configFile = WINDOWS_CONFIG_FILE; + } else { + throw new RuntimeException("Please Add Jvm Argument config.resource"); + } + } + + File file = new File(configFile); + if (false == file.exists()) { + throw new RuntimeException("The config file " + configFile + " cannot be found."); + } + + InputStream in = null; + try { + + in = Files.newInputStream(Paths.get(configFile)); + + config = yaml.loadAs(in, Config.class); + + setPackagesAndBugs(configFile, config); + + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + // JsonReader jsonReader = new JsonReader(new FileReader(configFile)); + // Config configAttOdlIt = new Gson().fromJson(jsonReader, + // Config.class); + + return config; + } + + private static void setPackagesAndBugs(String path, Config config) throws IOException { + + int separator = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/")); + String dirPath = path.substring(0, separator + 1); + String packagesFile = dirPath + File.separator + "attsdc-packages.yaml"; + File file = new File(packagesFile); + if (false == file.exists()) { + throw new RuntimeException("The config file " + packagesFile + " cannot be found."); + } + + TestPackages testPackages = null; + InputStream in = null; + try { + + in = Files.newInputStream(Paths.get(packagesFile)); + + testPackages = yaml.loadAs(in, TestPackages.class); + + List bugs = testPackages.getBugs(); + List packages = testPackages.getPackages(); + + config.setBugs(bugs); + config.setPackages(packages); + + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + } + + // public Config(String catalogBeHost, String esHost, String esPort, String + // resourceConfigDir, String componentsConfigDir, String catalogFeHost, + // String catalogFePort, String catalogBePort) { + // super(); + // this.catalogBeHost = catalogBeHost; + // this.esHost = esHost; + // this.esPort = esPort; + // this.resourceConfigDir = resourceConfigDir; + // this.componentsConfigDir = componentsConfigDir; + // this.catalogFeHost = catalogFeHost; + // this.catalogFePort = catalogFePort; + // this.catalogBePort = catalogBePort; + // } + + String configurationFile; + + public boolean getSystemUnderDebug() { + return systemUnderDebug; + } + + public void setSystemUnderDebug(boolean systemUnderDebug) { + this.systemUnderDebug = systemUnderDebug; + } + + public boolean getRerun() { + return rerun; + } + + public void setRerun(boolean rerun) { + this.rerun = rerun; + } + + public String getReportDBhost() { + return reportDBhost; + } + + public void setReportDBhost(String reportDBhost) { + this.reportDBhost = reportDBhost; + } + + public int getReportDBport() { + return reportDBport; + } + + public void setReportDBport(int reportDBport) { + this.reportDBport = reportDBport; + } +// public boolean isUsingBrowserMobProxy() { +// return useBrowserMobProxy; +// } +// +// public void setUsingBrowserMobProxy(boolean usingBrowserMobProxy) { +// this.useBrowserMobProxy = usingBrowserMobProxy; +// } + + + + + public String getBrowser() { + return browser; + } + + public boolean getUseBrowserMobProxy() { + return useBrowserMobProxy; + } + + public void setUseBrowserMobProxy(boolean useBrowserMobProxy) { + this.useBrowserMobProxy = useBrowserMobProxy; + } + + + + public boolean getCaptureTraffic() { + return captureTraffic; + } + + public void setCaptureTraffic(boolean captureTraffic) { + this.captureTraffic = captureTraffic; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public String getConfigurationFile() { + return configurationFile; + } + + public void setConfigurationFile(String configurationFile) { + this.configurationFile = configurationFile; + } + + public boolean getIsDistributionClientRunning() { + return isDistributionClientRunning; + } + + public void setIsDistributionClientRunning(boolean isDistributionClientRunning) { + this.isDistributionClientRunning = isDistributionClientRunning; + } + + public String getCatalogBePort() { + return catalogBePort; + } + + public String getDisributionClientHost() { + return disributionClientHost; + } + + public void setDisributionClientHost(String disributionClientHost) { + this.disributionClientHost = disributionClientHost; + } + + public String getDisributionClientPort() { + return disributionClientPort; + } + + public void setDisributionClientPort(String disributionClientPort) { + this.disributionClientPort = disributionClientPort; + } + + public void setCatalogBePort(String catalogBePort) { + this.catalogBePort = catalogBePort; + } + + public String getCatalogFeHost() { + return catalogFeHost; + } + + public void setCatalogFeHost(String catalogFeHost) { + this.catalogFeHost = catalogFeHost; + } + + public String getCatalogFePort() { + return catalogFePort; + } + + public void setCatalogFePort(String catalogFePort) { + this.catalogFePort = catalogFePort; + } + + public String getCatalogBeHost() { + return catalogBeHost; + } + + public void setCatalogBeHost(String catalogBeHost) { + this.catalogBeHost = catalogBeHost; + } + + public String getEsHost() { + return esHost; + } + + public void setEsHost(String esHost) { + this.esHost = esHost; + } + + public String getEsPort() { + return esPort; + } + + public void setEsPort(String esPort) { + this.esPort = esPort; + } + + public String getResourceConfigDir() { + return resourceConfigDir; + } + + public void setResourceConfigDir(String resourceConfigDir) { + this.resourceConfigDir = resourceConfigDir; + } + + public String getComponentsConfigDir() { + return componentsConfigDir; + } + + public void setComponentsConfigDir(String componentsConfigDir) { + this.componentsConfigDir = componentsConfigDir; + } + + public String getOutputFolder() { + return outputFolder; + } + + public void setOutputFolder(String outputFolder) { + this.outputFolder = outputFolder; + } + + public String getReportName() { + return reportName; + } + + public void setReportName(String reportName) { + this.reportName = reportName; + } + + public String getNeoPort() { + return neoPort; + } + + public void setNeoPort(String neoPort) { + this.neoPort = neoPort; + } + + public String getNeoHost() { + return neoHost; + } + + public void setNeoHost(String neoHost) { + this.neoHost = neoHost; + } + + public String getNeoDBpassword() { + return neoDBpassword; + } + + public String getNeoDBusername() { + return neoDBusername; + } + + public void setNeoDBusername(String neoDBusername) { + this.neoDBusername = neoDBusername; + } + + public void setNeoDBpassword(String neoDBpassword) { + this.neoDBpassword = neoDBpassword; + } + + public String getTitanPropertiesFile() { + return titanPropertiesFile; + } + + public void setTitanPropertiesFile(String titanPropertiesFile) { + this.titanPropertiesFile = titanPropertiesFile; + } + + public List getPackages() { + return packages; + } + + public void setPackages(List packages) { + this.packages = packages; + } + + public List getBugs() { + return bugs; + } + + public void setBugs(List bugs) { + this.bugs = bugs; + } + + public boolean isStopOnClassFailure() { + return stopOnClassFailure; + } + + public void setStopOnClassFailure(boolean stopOnClassFailure) { + this.stopOnClassFailure = stopOnClassFailure; + } + + public String getImportResourceConfigDir() { + return importResourceConfigDir; + } + + public void setImportResourceConfigDir(String importResourceConfigDir) { + this.importResourceConfigDir = importResourceConfigDir; + } + + public String getImportResourceTestsConfigDir() { + return importResourceTestsConfigDir; + } + + public void setImportResourceTestsConfigDir(String importResourceTestsConfigDir) { + this.importResourceTestsConfigDir = importResourceTestsConfigDir; + } + + public String getErrorConfigurationFile() { + return errorConfigurationFile; + } + + public void setErrorConfigurationFile(String errorConfigurationFile) { + this.errorConfigurationFile = errorConfigurationFile; + } + + public String getCatalogBeTlsPort() { + return catalogBeTlsPort; + } + + public void setCatalogBeTlsPort(String catalogBeTlsPort) { + this.catalogBeTlsPort = catalogBeTlsPort; + } + + public List getResourcesNotToDelete() { + return resourcesNotToDelete; + } + + public void setResourcesNotToDelete(List resourcesNotToDelete) { + this.resourcesNotToDelete = resourcesNotToDelete; + } + + public List getResourceCategoriesNotToDelete() { + return resourceCategoriesNotToDelete; + } + + public void setResourceCategoriesNotToDelete(List resourceCategoriesNotToDelete) { + this.resourceCategoriesNotToDelete = resourceCategoriesNotToDelete; + } + + public List getServiceCategoriesNotToDelete() { + return serviceCategoriesNotToDelete; + } + + public void setServiceCategoriesNotToDelete(List serviceCategoriesNotToDelete) { + this.serviceCategoriesNotToDelete = serviceCategoriesNotToDelete; + } + + public String getImportTypesConfigDir() { + return importTypesConfigDir; + } + + public void setImportTypesConfigDir(String importTypesConfigDir) { + this.importTypesConfigDir = importTypesConfigDir; + } + + public String getCassandraHost() { + return cassandraHost; + } + + public void setCassandraHost(String cassandraHost) { + this.cassandraHost = cassandraHost; + } + + public String getCassandraAuditKeySpace() { + return cassandraAuditKeySpace; + } + + public void setCassandraAuditKeySpace(String cassandraAuditKeySpace) { + this.cassandraAuditKeySpace = cassandraAuditKeySpace; + } + + public String getCassandraArtifactKeySpace() { + return cassandraArtifactKeySpace; + } + + public void setCassandraArtifactKeySpace(String cassandraArtifactKeySpace) { + this.cassandraArtifactKeySpace = cassandraArtifactKeySpace; + } + + + public String getWindowsDownloadDirectory() { + return windowsDownloadDirectory; + } + + public void setWindowsDownloadDirectory(String windowsDownloadDirectory) { + this.windowsDownloadDirectory = windowsDownloadDirectory; + } + + @Override + public String toString() { + return "Config [systemUnderDebug=" + systemUnderDebug + ", rerun=" + rerun + ", reportDBhost=" + reportDBhost + + ", reportDBport=" + reportDBport + ", browser=" + browser + ", catalogBeHost=" + catalogBeHost + + ", esHost=" + esHost + ", esPort=" + esPort + ", neoHost=" + neoHost + ", neoPort=" + neoPort + + ", disributionClientHost=" + disributionClientHost + ", disributionClientPort=" + + disributionClientPort + ", isDistributionClientRunning=" + isDistributionClientRunning + + ", errorConfigurationFile=" + errorConfigurationFile + ", resourceConfigDir=" + resourceConfigDir + + ", componentsConfigDir=" + componentsConfigDir + ", importResourceConfigDir=" + + importResourceConfigDir + ", importResourceTestsConfigDir=" + importResourceTestsConfigDir + + ", importTypesConfigDir=" + importTypesConfigDir + ", testSuites=" + testSuites + ", catalogFeHost=" + + catalogFeHost + ", catalogFePort=" + catalogFePort + ", catalogBePort=" + catalogBePort + + ", catalogBeTlsPort=" + catalogBeTlsPort + ", neoDBusername=" + neoDBusername + ", neoDBpassword=" + + neoDBpassword + ", titanPropertiesFile=" + titanPropertiesFile + ", packages=" + packages + ", bugs=" + + bugs + ", resourcesNotToDelete=" + resourcesNotToDelete + ", resourceCategoriesNotToDelete=" + + resourceCategoriesNotToDelete + ", serviceCategoriesNotToDelete=" + serviceCategoriesNotToDelete + + ", stopOnClassFailure=" + stopOnClassFailure + ", outputFolder=" + outputFolder + ", reportName=" + + reportName + ", url=" + url + ", remoteTestingMachineIP=" + remoteTestingMachineIP + + ", remoteTestingMachinePort=" + remoteTestingMachinePort + ", remoteTesting=" + remoteTesting + + ", cassandraHost=" + cassandraHost + ", cassandraAuditKeySpace=" + cassandraAuditKeySpace + + ", cassandraArtifactKeySpace=" + cassandraArtifactKeySpace + ", cassandraAuthenticate=" + + cassandraAuthenticate + ", cassandraUsername=" + cassandraUsername + ", cassandraPassword=" + + cassandraPassword + ", cassandraSsl=" + cassandraSsl + ", cassandraTruststorePath=" + + cassandraTruststorePath + ", cassandraTruststorePassword=" + cassandraTruststorePassword + + ", windowsDownloadDirectory=" + windowsDownloadDirectory + ", captureTraffic=" + captureTraffic + + ", useBrowserMobProxy=" + useBrowserMobProxy + ", configurationFile=" + configurationFile + "]"; + } + + public boolean isRemoteTesting() { + return remoteTesting; + } + + public void setRemoteTesting(boolean remoteTesting) { + this.remoteTesting = remoteTesting; + } + + public String getUrl() { + try { + return url; + } catch (Exception e) { + return null; + } + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRemoteTestingMachineIP() { + return remoteTestingMachineIP; + } + + public void setRemoteTestingMachineIP(String remoteTestingMachineIP) { + this.remoteTestingMachineIP = remoteTestingMachineIP; + } + + public String getRemoteTestingMachinePort() { + return remoteTestingMachinePort; + } + + public void setRemoteTestingMachinePort(String remoteTestingMachinePort) { + this.remoteTestingMachinePort = remoteTestingMachinePort; + } + + public boolean getCassandraAuthenticate() { + return cassandraAuthenticate; + } + + public void setCassandraAuthenticate(boolean cassandraAuthenticate) { + this.cassandraAuthenticate = cassandraAuthenticate; + } + + public String getCassandraUsername() { + return cassandraUsername; + } + + public void setCassandraUsername(String cassandraUsername) { + this.cassandraUsername = cassandraUsername; + } + + public String getCassandraPassword() { + return cassandraPassword; + } + + public void setCassandraPassword(String cassandraPassword) { + this.cassandraPassword = cassandraPassword; + } + + public boolean getCassandraSsl() { + return cassandraSsl; + } + + public void setCassandraSsl(boolean cassandraSsl) { + this.cassandraSsl = cassandraSsl; + } + + public String getCassandraTruststorePath() { + return cassandraTruststorePath; + } + + public void setCassandraTruststorePath(String cassandraTruststorePath) { + this.cassandraTruststorePath = cassandraTruststorePath; + } + + public String getCassandraTruststorePassword() { + return cassandraTruststorePassword; + } + + public void setCassandraTruststorePassword(String cassandraTruststorePassword) { + this.cassandraTruststorePassword = cassandraTruststorePassword; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java new file mode 100644 index 0000000000..fbc493ffd6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java @@ -0,0 +1,63 @@ +/*- + * ============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.ci.tests.config; + +import java.util.HashMap; +import java.util.Map; + +import org.testng.IInvokedMethod; +import org.testng.IInvokedMethodListener; +import org.testng.ITestResult; +import org.testng.SkipException; +import org.testng.internal.TestResult; + +public class InvokedMethodListener implements IInvokedMethodListener { + + static Map methodFailCount = new HashMap(); + + @Override + + public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { + + if (methodFailCount.get(method.getTestMethod().getMethodName()) != null + && methodFailCount.get(method.getTestMethod().getMethodName()) > 1) + throw new SkipException("Skipped due to failure count > 1"); + ; + + } + + @Override + + public void afterInvocation(IInvokedMethod method, ITestResult testResult) { + + if (testResult.getStatus() == TestResult.FAILURE) { + if (methodFailCount.get(method.getTestMethod().getMethodName()) == null) + methodFailCount.put(method.getTestMethod().getMethodName(), 1); + else { + methodFailCount.put(method.getTestMethod().getMethodName(), + methodFailCount.get(method.getTestMethod().getMethodName()) + 1); + } + + } + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java new file mode 100644 index 0000000000..41936e2c30 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java @@ -0,0 +1,135 @@ +/*- + * ============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.ci.tests.datatypes; + +public class ArtifactAssetStructure { + + String artifactName; + String artifactType; + String artifactURL; + String artifactDescription; + int artifactTimeout;// optional + String artifactChecksum; + String artifactUUID; + String artifactVersion; + String generatedFromUUID;// optional + + public ArtifactAssetStructure(String artifactName, String artifactType, String artifactURL, + String artifactDescription, int artifactTimeout, String artifactChecksum, String artifactUUID, + String artifactVersion, String generatedFromUUID) { + super(); + this.artifactName = artifactName; + this.artifactType = artifactType; + this.artifactURL = artifactURL; + this.artifactDescription = artifactDescription; + this.artifactTimeout = artifactTimeout; + this.artifactChecksum = artifactChecksum; + this.artifactUUID = artifactUUID; + this.artifactVersion = artifactVersion; + this.generatedFromUUID = generatedFromUUID; + } + + public ArtifactAssetStructure() { + super(); + // TODO Auto-generated constructor stub + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public int getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(int artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + @Override + public String toString() { + return "ArtifactAssetStructure [artifactName=" + artifactName + ", artifactType=" + artifactType + + ", artifactURL=" + artifactURL + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" + + artifactTimeout + ", artifactChecksum=" + artifactChecksum + ", artifactUUID=" + artifactUUID + + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java new file mode 100644 index 0000000000..93f65b9f63 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java @@ -0,0 +1,243 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; + +public class ArtifactReqDetails { + + public ArtifactReqDetails() { + + } + + public ArtifactReqDetails(String artifactName, String artifactType, String artifactDescription, String payloadData, + String artifactLable) { + super(); + this.artifactName = artifactName; + this.artifactType = artifactType; + this.description = artifactDescription; + this.payloadData = payloadData; + this.artifactLabel = artifactLable; + } + + public ArtifactReqDetails(String artifactLable, ArtifactReqDetails a) { + super(); + this.artifactName = a.getArtifactName(); + this.artifactType = a.getArtifactType(); + this.description = a.getArtifactType(); + this.payloadData = a.getPayload(); + this.artifactLabel = artifactLable; + } + + private String uniqueId; + private String artifactName; + private String artifactType; + private String description; + private String payloadData; + private String artifactLabel; + private String apiUrl; + private String artifactGroupType; + private Integer timeout; + private String userIdLastUpdater; + private String creatorFullName; + private String updaterFullName; + private String artifactChecksum; + private String artifactDisplayName; + private List heatParameters; + + private boolean mandatory; + private boolean serviceApi; + + public boolean isServiceApi() { + return serviceApi; + } + + public void setServiceApi(boolean serviceApi) { + this.serviceApi = serviceApi; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getPayload() { + return payloadData; + } + + public void setPayload(String payload) { + this.payloadData = payload; + } + + public void setPayloadData(String payloadData) { + this.payloadData = payloadData; + } + + public String getArtifactGroupType() { + return artifactGroupType; + } + + public void setArtifactGroupType(String artifactGroupType) { + this.artifactGroupType = artifactGroupType; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + + public boolean isMandatory() { + return mandatory; + } + + public void setMandatory(boolean mandatory) { + this.mandatory = mandatory; + } + + public String getUrl() { + return apiUrl; + } + + public void setUrl(String url) { + this.apiUrl = url; + } + + @Override + public String toString() { + if (!apiUrl.isEmpty()) { + return "ArtifactReqDetails [artifactName=" + artifactName + ", artifactType=" + artifactType + + ", description=" + description + ", payloadData=" + payloadData + ", artifactLabel=" + + artifactLabel + ", mandatory=" + mandatory + ", url=" + apiUrl + "]"; + } + + return "ArtifactReqDetails [artifactName=" + artifactName + ", artifactType=" + artifactType + ", description=" + + description + ", payloadData=" + payloadData + ", artifactLabel=" + artifactLabel + + ", artifactUniqueId=" + uniqueId + ", mandatory=" + mandatory + ", serviceApi=" + serviceApi + "]"; + + } + + // public String getPayloadData() { + // return payloadData; + // } + // + // public void setPayloadData(String payloadData) { + // this.payloadData = payloadData; + // } + + // public String getUserIdCreator() { + // return userIdCreator; + // } + // + // public void setUserIdCreator(String userIdCreator) { + // this.userIdCreator = userIdCreator; + // } + // + public String getArtifactDisplayName() { + + return artifactDisplayName; + } + + public void setArtifactDisplayName(String artifactDisplayName) { + this.artifactDisplayName = artifactDisplayName; + } + + public String getUserIdLastUpdater() { + return userIdLastUpdater; + } + + public void setUserIdLastUpdater(String userIdLastUpdater) { + this.userIdLastUpdater = userIdLastUpdater; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getUpdaterFullName() { + return updaterFullName; + } + + public void setUpdaterFullName(String updaterFullName) { + this.updaterFullName = updaterFullName; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String artifactUniqueId) { + this.uniqueId = artifactUniqueId; + } + + public List getHeatParameters() { + return heatParameters; + } + + public void setHeatParameters(List heatParameters) { + this.heatParameters = heatParameters; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java new file mode 100644 index 0000000000..8820b05772 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java @@ -0,0 +1,122 @@ +/*- + * ============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.ci.tests.datatypes; + +public class AssetStructure { + + private String uuid; + private String invariantUUID; + private String name; + private String version; + private String toscaModelURL; + private String category; + private String lifecycleState; + private String lastUpdaterUserId; + + public AssetStructure() { + super(); + } + + public AssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL, + String category, String lifecycleState, String lastUpdaterUserId) { + super(); + this.uuid = uuid; + this.invariantUUID = invariantUUID; + this.name = name; + this.version = version; + this.toscaModelURL = toscaModelURL; + this.category = category; + this.lifecycleState = lifecycleState; + this.lastUpdaterUserId = lastUpdaterUserId; + } + + @Override + public String toString() { + return "AssetStructure [uuid=" + uuid + ", invariantUUID=" + invariantUUID + ", name=" + name + ", version=" + + version + ", toscaModelURL=" + toscaModelURL + ", category=" + category + ", lifecycleState=" + + lifecycleState + ", lastUpdaterUserId=" + lastUpdaterUserId + "]"; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getToscaModelURL() { + return toscaModelURL; + } + + public void setToscaModelURL(String toscaModelURL) { + this.toscaModelURL = toscaModelURL; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java new file mode 100644 index 0000000000..549700f384 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java @@ -0,0 +1,121 @@ +/*- + * ============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.ci.tests.datatypes; + +import org.openecomp.sdc.be.model.ComponentInstance; + +public class ComponentInstanceReqDetails { + + String componentUid; + String description; + String posX; + String posY; + String name; + String uniqueId; + + public ComponentInstanceReqDetails() { + super(); + // TODO Auto-generated constructor stub + } + + public ComponentInstanceReqDetails(ComponentInstance componentInstance) { + super(); + this.setUniqueId(componentInstance.getUniqueId()); + this.description = componentInstance.getDescription(); + this.posX = componentInstance.getPosX(); + this.posY = componentInstance.getPosY(); + // this.name = "myResourceInstance"; + this.name = componentInstance.getName(); + } + + public ComponentInstanceReqDetails(String resourceUid, String description, String posX, String posY, String name) { + super(); + this.componentUid = resourceUid; + this.description = description; + this.posX = posX; + this.posY = posY; + // this.name = "myResourceInstance"; + this.name = name; + } + + public ComponentInstanceReqDetails(String resourceUid, String description, String posX, String posY) { + super(); + this.componentUid = resourceUid; + this.description = description; + this.posX = posX; + this.posY = posY; + } + + public String getComponentUid() { + return componentUid; + } + + public void setComponentUid(String resourceUid) { + this.componentUid = resourceUid; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getPosX() { + return posX; + } + + public void setPosX(String posX) { + this.posX = posX; + } + + public String getPosY() { + return posY; + } + + public void setPosY(String posY) { + this.posY = posY; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + @Override + public String toString() { + return "ResourceInstanceReqDetails [resourceUid=" + componentUid + ", description=" + description + ", posX=" + + posX + ", posY=" + posY + ", name=" + name + ", uniqueId=" + uniqueId + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java new file mode 100644 index 0000000000..8546732414 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java @@ -0,0 +1,272 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; + +public abstract class ComponentReqDetails { + + protected String name; + protected String description; + protected List tags = new ArrayList<>(); + protected String contactId; + protected String icon; + protected String uniqueId; + protected String creatorUserId; + protected String creatorFullName; + protected String lastUpdaterUserId; + protected String lastUpdaterFullName; + protected Long creationDate; + protected Long lastUpdateDate; + protected LifecycleStateEnum lifecycleState; + protected String version; + protected String UUID; + protected List categories; + protected String projectCode; + protected String csarUUID; + protected String csarVersion; + protected String importedToscaChecksum; + protected String invariantUUID; + + public String getCsarVersion() { + return csarVersion; + } + + public void setCsarVersion(String csarVersion) { + this.csarVersion = csarVersion; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + tags.add(name); + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + // public String getCategory() { + // return category; + // } + // + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public void setCreationDate(Long creationDate) { + this.creationDate = creationDate; + } + + public void setLastUpdateDate(Long lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + public void setLifecycleState(LifecycleStateEnum lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public void setUUID(String uUID) { + this.UUID = uUID; + } + + public String getCreatorUserId() { + return creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public Long getCreationDate() { + return creationDate; + } + + public Long getLastUpdateDate() { + return lastUpdateDate; + } + + public LifecycleStateEnum getLifecycleState() { + return lifecycleState; + } + + public String getUUID() { + return UUID; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + public void removeAllCategories() { + this.categories = new ArrayList<>(); + } + + public void addCategoryChain(String category, String subCategory) { + if (category != null || subCategory != null) { + if (categories == null) { + categories = new ArrayList<>(); + } + CategoryDefinition selectedCategory = null; + for (CategoryDefinition categoryDef : categories) { + if (categoryDef.getName().equals(category)) { + selectedCategory = categoryDef; + } + } + if (selectedCategory == null) { + selectedCategory = new CategoryDefinition(); + selectedCategory.setName(category); + categories.add(selectedCategory); + } + if (subCategory != null) { + List subcategories = selectedCategory.getSubcategories(); + if (subcategories == null) { + subcategories = new ArrayList<>(); + selectedCategory.setSubcategories(subcategories); + } + SubCategoryDefinition selectedSubcategory = null; + for (SubCategoryDefinition subcategory : subcategories) { + if (subcategory.getName().equals(subCategory)) { + selectedSubcategory = subcategory; + } + } + if (selectedSubcategory == null) { + selectedSubcategory = new SubCategoryDefinition(); + selectedSubcategory.setName(subCategory); + subcategories.add(selectedSubcategory); + } + } + } + } + + public void addCategory(String category) { + addCategoryChain(category, null); + } + + public String getProjectCode() { + return projectCode; + } + + public void setProjectCode(String projectCode) { + this.projectCode = projectCode; + } + + public String getCsarUUID() { + return csarUUID; + } + + public void setCsarUUID(String csarUUID) { + this.csarUUID = csarUUID; + } + + public String getImportedToscaChecksum() { + return importedToscaChecksum; + } + + public void setImportedToscaChecksum(String importedToscaChecksum) { + this.importedToscaChecksum = importedToscaChecksum; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CsarArtifacts.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CsarArtifacts.java new file mode 100644 index 0000000000..f3379766e2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CsarArtifacts.java @@ -0,0 +1,59 @@ +/*- + * ============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.ci.tests.datatypes; + +public class CsarArtifacts { + + private String artifactType; + private String artifactName; + + public CsarArtifacts() { + super(); + } + + public CsarArtifacts(String artifactName, String artifactType) { + super(); + this.artifactName = artifactName; + this.artifactType = artifactType; + } + + @Override + public String toString() { + return "AssetStructure [artifactName=" + artifactName + ", artifactType=" + artifactType + "]"; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java new file mode 100644 index 0000000000..03bedd6746 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java @@ -0,0 +1,86 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class GroupHeatMetaDefinition { + + private int group = 0; +// private List artifactList = new ArrayList(); + private List artifactList = new ArrayList(); + @Override + public String toString() { + return "GroupHeatMetaDefinition [group=" + group + ", artifactList=" + artifactList + ", artifactMap=" + artifactMap + ", propertyHeatMetaDefinition=" + propertyHeatMetaDefinition + "]"; + } + + public List getArtifactList() { + return artifactList; + } + + public void setArtifactList(List artifactList) { + this.artifactList = artifactList; + } + + private Map artifactMap = new HashMap<>(); + PropertyHeatMetaDefinition propertyHeatMetaDefinition; + + public Map getArtifactMap() { + return artifactMap; + } + + public void setArtifactMap(Map artifactMap) { + this.artifactMap = artifactMap; + } + + + public PropertyHeatMetaDefinition getPropertyHeatMetaDefinition() { + return propertyHeatMetaDefinition; + } + + public void setPropertyHeatMetaDefinition(PropertyHeatMetaDefinition propertyHeatMetaDefinition) { + this.propertyHeatMetaDefinition = propertyHeatMetaDefinition; + } + + public GroupHeatMetaDefinition() { + super(); + } + + public int getGroup() { + return group; + } + + public void setGroup(int group) { + this.group = group; + } + +// public List getArtifactList() { +// return artifactList; +// } +// +// public void setArtifactList(List artifactList) { +// this.artifactList = artifactList; +// } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatMetaFirstLevelDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatMetaFirstLevelDefinition.java new file mode 100644 index 0000000000..4e760227f3 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatMetaFirstLevelDefinition.java @@ -0,0 +1,76 @@ +/*- + * ============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.ci.tests.datatypes; + +public class HeatMetaFirstLevelDefinition { + + public HeatMetaFirstLevelDefinition(String fileName, String type, String checkSum) { + super(); + this.fileName = fileName; + this.type = type; + this.checkSum = checkSum; + + } + + private String fileName; + private String type; + private String checkSum; + + public HeatMetaFirstLevelDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + + public String getCheckSum() { + return checkSum; + } + + public void setCheckSum(String checkSum) { + this.checkSum = checkSum; + } + + @Override + public String toString() { + return "HeatMetaFirstLevelDefinition [fileName=" + fileName + ", type=" + type + ", checkSum=" + checkSum + "]"; + } + + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java new file mode 100644 index 0000000000..638ece8c6d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java @@ -0,0 +1,335 @@ +/*- + * ============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.ci.tests.datatypes; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.yaml.snakeyaml.Yaml; + +public class ImportReqDetails extends ResourceReqDetails { + + private String payloadName; + private String payloadData; + + private Map requirements; + private Map capabilities; + + private List derivedList; + private String derivedFromField; + + public ImportReqDetails(String resourceName, String description, List tags, List derivedFrom, + String vendorName, String vendorRelease, String contactId, String icon) { + super(resourceName, description, tags, null, derivedFrom, vendorName, vendorRelease, contactId, icon); + } + + public String getPayloadName() { + return payloadName; + } + + public void setPayloadName(String payloadName) { + this.payloadName = payloadName; + } + + public String getPayloadData() { + return payloadData; + } + + public void setPayloadData(String payloadData) { + this.payloadData = payloadData; + } + + @Override + public String toString() { + return "ImportReqDetails [payloadName=" + payloadName + ", payloadData=" + payloadData + "]"; + } + + public void setReqirementsAndCapabilities(String path, String fileName, User user, String derivedFromSource) + throws Exception { + setRequirements(path, fileName, user, derivedFromSource); + setCapabilities(path, fileName, user, derivedFromSource); + } + + public List getDerivedList() { + return derivedList; + } + + public void setDerivedList(List derivedList) { + this.derivedList = derivedList; + } + + public String getDerivedFromField() { + return derivedFromField; + } + + public void setDerivedFromField(String derivedFromField) { + this.derivedFromField = derivedFromField; + } + + public Map getRequirements() { + return requirements; + } + + public void setRequirements(String path, String fileName, User user, String derivedFromSource) throws Exception { + Map requirementsFromFile = getRequirementsMapFromFile(path + File.separator + fileName, + toscaResourceName, "requirements"); + Map requirements = organizeRequirementsMap(requirementsFromFile); + getDerivedReqCap(user, requirements, "requirements", derivedFromSource); + this.requirements = requirements; + } + + private void getDerivedReqCap(User user, Map reqCapMap, String field, String derivedFromResource) + throws IOException, JSONException { + + if (derivedFromResource == null) { + derivedFromResource = "Root"; + } + + RestResponse rest = getResourceSource(user, derivedFromResource); + Map parsedFieldFromResponseAsMap = ResponseParser.getJsonValueAsMap(rest, field); + Iterator iterator = parsedFieldFromResponseAsMap.keySet().iterator(); + Map convertListToMap = null; + while (iterator.hasNext()) { + String type = iterator.next(); + List lst = (List) parsedFieldFromResponseAsMap.get(type); + convertListToMap = convertListToMap(lst); + + if (field.equals("capabilities")) { + convertListToMap.replace("capabilitySources", derivedList); + lst = new ArrayList(Arrays.asList(convertListToMap)); + } + + Object existingValue = reqCapMap.get(type); + if (existingValue != null) { + Map convertedExistingValue = convertListToMap((List) existingValue); + if (convertedExistingValue.get("name").toString().toLowerCase() + .equals(convertListToMap.get("name").toString().toLowerCase())) { + lst = new ArrayList(Arrays.asList(convertedExistingValue)); + } else { + lst.add(convertedExistingValue); + } + } + + reqCapMap.put(type, lst); + } + } + + private RestResponse getResourceSource(User user, String source) throws IOException, JSONException { + org.codehaus.jettison.json.JSONObject getResourceJSONObject = null; + RestResponse rest = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), source, "1.0"); + if (rest.getErrorCode().intValue() == 200) { + JSONArray jArray = new JSONArray(rest.getResponse()); + for (int i = 0; i < jArray.length(); i++) { + getResourceJSONObject = jArray.getJSONObject(i); + String resourceType = getResourceJSONObject.get("resourceType").toString(); + if (!resourceType.equals("VF")) { + rest.setResponse(getResourceJSONObject.toString()); + } + } + } + return rest; + } + + public Map getCapabilities() { + return capabilities; + } + + public void setCapabilities(String path, String fileName, User user, String derivedFromSource) throws Exception { + Map capabilitiesFromFile = getCapabilitiesMapFromFile(path + File.separator + fileName, + toscaResourceName, "capabilities"); + Map capabilities = organizeCapabilitiesMap(capabilitiesFromFile); + getDerivedReqCap(user, capabilities, "capabilities", derivedFromSource); + this.capabilities = capabilities; + } + + private Map organizeCapabilitiesMap(Map capabilitiesFromFile) { + Iterator iterator = capabilitiesFromFile.keySet().iterator(); + Map capMap = new HashMap(); + while (iterator.hasNext()) { + List valueList = new ArrayList(); + String next = iterator.next(); + Map valuesMap = (Map) capabilitiesFromFile.get(next); + String key = valuesMap.remove("type").toString(); + valuesMap.put("name", next); + valuesMap.put("capabilitySources", derivedList); + valuesMap.put("type", key); + + if (!valuesMap.containsKey("occurrences")) { + valuesMap.put("minOccurrences", "1"); + valuesMap.put("maxOccurrences", "UNBOUNDED"); + } + + Object tempValue = capMap.get(key); + if (tempValue == null) { + valueList.add(valuesMap); + } else { + Map convertValue = convertListToMap((List) tempValue); + valueList = new ArrayList(Arrays.asList(convertValue, valuesMap)); + } + capMap.put(key, valueList); + } + return capMap; + } + + private Map getCapabilitiesMapFromFile(String fileName, String toscaResourceName, + String fieldToTest) throws Exception { + Map resourceToscaMap = getToscaResourceFromFile(fileName, toscaResourceName); + Object capMap = resourceToscaMap.get(fieldToTest); + if (capMap == null) { + return new HashMap(); + } + return (Map) capMap; + } + + private Map organizeRequirementsMap(Map requirementsFromFile) { + Map reqMap = new HashMap(); + List valueList = new ArrayList(); + Iterator iterator = requirementsFromFile.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + Map valuesMap = (Map) requirementsFromFile.get(key); + valuesMap.put("name", key); + String capability = valuesMap.get("capability").toString(); + + List occurencesList = (List) valuesMap.remove("occurrences"); + if (occurencesList != null) { + valuesMap.put("minOccurrences", occurencesList.get(0).toString()); + valuesMap.put("maxOccurrences", occurencesList.get(1).toString()); + } + + valueList.add(valuesMap); + reqMap.put(capability, valueList); + } + + return reqMap; + } + + private Map getRequirementsMapFromFile(String fileName, String toscaResourceName, + String fieldToTest) throws Exception { + Map resourceToscaMap = getToscaResourceFromFile(fileName, toscaResourceName); + List reqListFromFile = (List) resourceToscaMap.get(fieldToTest); + if (reqListFromFile == null) { + return new HashMap(); + } + Map testedMapFromFile = convertListToMap(reqListFromFile); + return testedMapFromFile; + } + + private Map getToscaResourceFromFile(String fullFileName, String toscaResourceName) + throws Exception { + Map nodesTypesMap = getNodesTypesMapFromFile(fullFileName); + Map resourceToscaMap = (Map) nodesTypesMap.get(toscaResourceName); + + derivedFromField = resourceToscaMap.get("derived_from").toString(); + + return resourceToscaMap; + } + + private Map getNodesTypesMapFromFile(String fullFileName) throws FileNotFoundException { + Yaml yaml = new Yaml(); + File file = new File(fullFileName); + InputStream inputStream = new FileInputStream(file); + Map mapFromFile = (Map) yaml.load(inputStream); + Map nodesTypesMap = (Map) mapFromFile.get("node_types"); + return nodesTypesMap; + } + + private Map convertListToMap(List testedListFromFile) { + Map testedMapFromFile = new HashMap(); + for (int i = 0; i < testedListFromFile.size(); i++) { + Object req = testedListFromFile.get(i); + ObjectMapper m = new ObjectMapper(); + Map mappedObject = m.convertValue(req, Map.class); + testedMapFromFile.putAll(mappedObject); + } + return testedMapFromFile; + } + + public void compareRequirementsOrCapabilities(Map exepectedReq, Map actualReq) { + Iterator iterator = exepectedReq.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + List expectedValues = (List) exepectedReq.get(key); + List actualValues = (List) actualReq.get(key); + assertNotNull(actualValues); + + List> expectedMapsList = convertListToMapList(expectedValues); + List> actualMapsList = convertListToMapList(actualValues); + assertEquals(expectedMapsList.size(), actualMapsList.size()); + + for (int i = 0; i < expectedMapsList.size(); i++) { + Map expectedMap = expectedMapsList.get(i); + Map actualdMap = actualMapsList.get(i); + if (expectedMap.get("name").equals(actualdMap.get("name"))) { + Iterator iterator2 = expectedMap.keySet().iterator(); + while (iterator2.hasNext()) { + String innerKey = iterator2.next(); + assertTrue( + "check " + innerKey + " in " + key + ":\nexpected: " + + expectedMap.get(innerKey).toString() + "\nactual: " + + actualdMap.get(innerKey).toString(), + expectedMap.get(innerKey).equals(actualdMap.get(innerKey))); + + } + + } + } + } + } + + private List> convertListToMapList(List testedListFromFile) { + List> listOfMaps = new ArrayList>(); + for (int i = 0; i < testedListFromFile.size(); i++) { + Object req = testedListFromFile.get(i); + ObjectMapper m = new ObjectMapper(); + Map mappedObject = m.convertValue(req, Map.class); + mappedObject.remove("uniqueId"); + Map testedMapFromFile = new HashMap(); + testedMapFromFile.putAll(mappedObject); + listOfMaps.add(testedMapFromFile); + } + return listOfMaps; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java new file mode 100644 index 0000000000..f2484e274d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java @@ -0,0 +1,88 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class ProductReqDetails extends ComponentReqDetails { + + private String fullName; + private List contacts; + private String isActive; + + public ProductReqDetails(String name, List category) { + this.categories = category; + this.name = name; + } + + public ProductReqDetails(String name) { + this.name = name; + } + + public void addCategory(CategoryDefinition category) { + if (categories == null) { + categories = new ArrayList<>(); + } + categories.add(category); + } + + public void addContact(String contactUserId) { + if (contacts == null) { + contacts = new ArrayList<>(); + } + contacts.add(contactUserId); + } + + public List getContacts() { + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getActive() { + return isActive; + } + + public void setActive(String isActive) { + this.isActive = isActive; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java new file mode 100644 index 0000000000..5c9083d757 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java @@ -0,0 +1,63 @@ +/*- + * ============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.ci.tests.datatypes; + +public class PropertyHeatMetaDefinition { + + String name; + boolean value; + + public PropertyHeatMetaDefinition() { + super(); + } + + + + public String getName() { + return name; + } + + + + public void setName(String name) { + this.name = name; + } + + + + public boolean getValue() { + return value; + } + + + + public void setValue(boolean value) { + this.value = value; + } + + + + @Override + public String toString() { + return "PropertyHeatMetaDefinition [name=" + name + ", value=" + value + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java new file mode 100644 index 0000000000..208e4aa3ea --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java @@ -0,0 +1,145 @@ +/*- + * ============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.ci.tests.datatypes; + +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; + +public class PropertyReqDetails { + String name; + String type; + Boolean required = false; + String defaultValue; + String description; + String propertyRangeMin; + String propertyRangeMax; + Boolean isPassword = false; + SchemaDefinition schema; + + public PropertyReqDetails() { + super(); + } + + public PropertyReqDetails(String propertyName, String propertyType, Boolean propertyRequired, + String propertyDefaultValue, String propertyDescription, String propertyRangeMin, String propertyRangeMax, + Boolean propertyPassword) { + super(); + this.name = propertyName; + this.type = propertyType; + this.required = propertyRequired; + this.defaultValue = propertyDefaultValue; + this.description = propertyDescription; + this.propertyRangeMin = propertyRangeMin; + this.propertyRangeMax = propertyRangeMax; + this.isPassword = propertyPassword; + } + + public PropertyReqDetails(String propertyName, String propertyType, String propertyDefaultValue, + String propertyDescription, SchemaDefinition schema) { + super(); + this.name = propertyName; + this.type = propertyType; + this.defaultValue = propertyDefaultValue; + this.description = propertyDescription; + this.schema = schema; + } + + public SchemaDefinition getSchema() { + return schema; + } + + public void setSchema(SchemaDefinition schema) { + this.schema = schema; + } + + public String getName() { + return name; + } + + public void setName(String propertyName) { + this.name = propertyName; + } + + public String getPropertyType() { + return type; + } + + public void setPropertyType(String propertyType) { + this.type = propertyType; + } + + public Boolean getPropertyRequired() { + return required; + } + + public void setPropertyRequired(Boolean propertyRequired) { + this.required = propertyRequired; + } + + public String getPropertyDefaultValue() { + return defaultValue; + } + + public void setPropertyDefaultValue(String propertyDefaultValue) { + this.defaultValue = propertyDefaultValue; + } + + public String getPropertyDescription() { + return description; + } + + public void setPropertyDescription(String propertyDescription) { + this.description = propertyDescription; + } + + public String getPropertyRangeMin() { + return propertyRangeMin; + } + + public void setPropertyRangeMin(String propertyRangeMin) { + this.propertyRangeMin = propertyRangeMin; + } + + public String getPropertyRangeMax() { + return propertyRangeMax; + } + + public void setPropertyRangeMax(String propertyRangeMax) { + this.propertyRangeMax = propertyRangeMax; + } + + public Boolean getPropertyPassword() { + return isPassword; + } + + public void setPropertyPassword(Boolean propertyPassword) { + this.isPassword = propertyPassword; + } + + public String propertyToJsonString() { + String jsonString; + jsonString = "{\"" + this.getName() + "\":{" + "\"type\":\"" + this.getPropertyType() + "\"," + "\"required\":" + + this.getPropertyRequired() + "," + "\"defaultValue\":\"" + this.getPropertyDefaultValue() + "\"," + + "\"description\":\"" + this.getPropertyDescription() + "\"," + "\"constraints\":[{\"inRange\":[\"" + + this.getPropertyRangeMin() + "\",\"" + this.getPropertyRangeMax() + "\"]}]," + "\"isPassword\":" + + this.getPropertyPassword() + "}}"; + return jsonString; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java new file mode 100644 index 0000000000..62f5e0c8f0 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java @@ -0,0 +1,76 @@ +/*- + * ============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.ci.tests.datatypes; + +public class ResourceAssetStructure extends AssetStructure { + + private String subCategory; + private String resourceType; + protected String lastUpdaterFullName; + protected String toscaResourceName; + + public ResourceAssetStructure() { + super(); + } + + public ResourceAssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL, + String category, String lifecycleState, String lastUpdaterUserId) { + super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId); + } + + @Override + public String toString() { + return "ResourceAssetStructure [subCategory=" + subCategory + ", resourceType=" + resourceType + "]"; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java new file mode 100644 index 0000000000..b521b4bf08 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes; + +import java.util.List; + +public class ResourceDetailedAssetStructure extends ResourceAssetStructure { + + private List resources; + private List artifacts; + + public ResourceDetailedAssetStructure() { + super(); + } + + public ResourceDetailedAssetStructure(String lastUpdaterFullName, String toscaResourceName, + List resources, List artifacts) { + super(); + this.lastUpdaterFullName = lastUpdaterFullName; + this.toscaResourceName = toscaResourceName; + this.resources = resources; + this.artifacts = artifacts; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + @Override + public String toString() { + return "ResourceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", toscaResourceName=" + + toscaResourceName + ", resources=" + resources + ", artifacts=" + artifacts + ", toString()=" + + super.toString() + ", getSubCategory()=" + getSubCategory() + ", getResourceType()=" + + getResourceType() + ", getUuid()=" + getUuid() + ", getInvariantUUID()=" + getInvariantUUID() + + ", getName()=" + getName() + ", getVersion()=" + getVersion() + ", getToscaModelURL()=" + + getToscaModelURL() + ", getCategory()=" + getCategory() + ", getLifecycleState()=" + + getLifecycleState() + ", getLastUpdaterUserId()=" + getLastUpdaterUserId() + ", getClass()=" + + getClass() + ", hashCode()=" + hashCode() + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java new file mode 100644 index 0000000000..a5132e8bf6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java @@ -0,0 +1,105 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; + +public class ResourceExternalReqDetails extends ComponentReqDetails { + String vendorName; + String vendorRelease; + String category; + String subcategory; + + private String resourceType = ResourceTypeEnum.VFC.toString(); // Default + // value + public ResourceExternalReqDetails() { + super(); + } + + + public ResourceExternalReqDetails(String resourceName, String description, List tags, + String vendorName, String vendorRelease, String contactId, String icon, + String resourceType, String resourceCategory, String resourceSubcategory) { + super(); + this.resourceType = resourceType; + this.name = resourceName; + this.description = description; + this.tags = tags; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.contactId = contactId; + this.icon = icon; + this.category = resourceCategory; + this.subcategory = resourceSubcategory; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + + @Override + public String toString() { + return "ResourceReqDetails [name=" + name + ", vendorName=" + vendorName + + ", vendorRelease=" + vendorRelease + ", version=" + version + + ", resourceType=" + resourceType + ", category=" + category + ", subcategory=" + subcategory +"]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java new file mode 100644 index 0000000000..6a69120a05 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java @@ -0,0 +1,116 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +public class ResourceInstanceAssetStructure { + + String resourceInstanceName; + String resourceName; + String resourceInvariantUUID; + String resourceVersion; + String resoucreType; + String resourceUUID; + List artifacts; + + public ResourceInstanceAssetStructure() { + super(); + } + + public ResourceInstanceAssetStructure(String resourceInstanceName, String resourceName, + String resourceInvariantUUID, String resourceVersion, String resoucreType, String resourceUUID, + List artifacts) { + super(); + this.resourceInstanceName = resourceInstanceName; + this.resourceName = resourceName; + this.resourceInvariantUUID = resourceInvariantUUID; + this.resourceVersion = resourceVersion; + this.resoucreType = resoucreType; + this.resourceUUID = resourceUUID; + this.artifacts = artifacts; + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResoucreType() { + return resoucreType; + } + + public void setResoucreType(String resoucreType) { + this.resoucreType = resoucreType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + @Override + public String toString() { + return "ResourceInstanceAssetStructure [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + + resourceName + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion=" + + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + ", artifacts=" + + artifacts + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java new file mode 100644 index 0000000000..8456e5b35b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java @@ -0,0 +1,220 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; + +public class ResourceReqDetails extends ComponentReqDetails { + List derivedFrom; + String vendorName; + String vendorRelease; + + // Unsettable/unupdatable fields + + Boolean isAbstract; + Boolean isHighestVersion; + String cost; + String licenseType; + String toscaResourceName; + + private String resourceType = ResourceTypeEnum.VFC.toString(); // Default + // value + + public ResourceReqDetails() { + super(); + } + + public ResourceReqDetails(Resource resource) { + super(); + this.resourceType = resource.getResourceType().toString(); + this.name = resource.getName(); + this.description = resource.getDescription(); + this.tags = resource.getTags(); + // this.category = resource.getCategories(); + this.derivedFrom = resource.getDerivedFrom(); + this.vendorName = resource.getVendorName(); + this.vendorRelease = resource.getVendorRelease(); + this.contactId = resource.getContactId(); + this.icon = resource.getIcon(); + this.toscaResourceName = resource.getToscaResourceName(); + this.uniqueId = resource.getUniqueId(); + this.creatorUserId = resource.getCreatorUserId(); + this.creatorFullName = resource.getCreatorFullName(); + this.lastUpdaterUserId = resource.getLastUpdaterUserId(); + this.lastUpdaterFullName = resource.getLastUpdaterFullName(); + this.lifecycleState = resource.getLifecycleState(); + this.version = resource.getVersion(); + this.UUID = resource.getUUID(); + this.categories = resource.getCategories(); + this.importedToscaChecksum = resource.getImportedToscaChecksum(); + + } + + public ResourceReqDetails(String resourceName, String description, List tags, String category, + List derivedFrom, String vendorName, String vendorRelease, String contactId, String icon) { + this(resourceName, description, tags, category, derivedFrom, vendorName, vendorRelease, contactId, icon, + ResourceTypeEnum.VFC.toString()); + } + + // new + public ResourceReqDetails(String resourceName, String description, List tags, String category, + List derivedFrom, String vendorName, String vendorRelease, String contactId, String icon, + String resourceType) { + super(); + this.resourceType = resourceType; + this.name = resourceName; + this.description = description; + this.tags = tags; + // this.category = category; + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.contactId = contactId; + this.icon = icon; + if (category != null) { + String[] arr = category.split("/"); + if (arr.length == 2) { + addCategoryChain(arr[0], arr[1]); + } + } + this.toscaResourceName = resourceName; + } + + public ResourceReqDetails(ResourceReqDetails originalResource, String version) { + super(); + this.name = originalResource.getName(); + this.description = originalResource.getDescription(); + this.tags = originalResource.getTags(); + // this.category = originalResource.getCategory(); + this.derivedFrom = originalResource.getDerivedFrom(); + this.vendorName = originalResource.getVendorName(); + this.vendorRelease = originalResource.getVendorRelease(); + this.contactId = originalResource.getContactId(); + this.icon = originalResource.getIcon(); + this.version = version; + this.uniqueId = originalResource.getUniqueId(); + this.categories = originalResource.getCategories(); + this.toscaResourceName = originalResource.getToscaResourceName(); + this.resourceType = originalResource.getResourceType(); + } + + public ResourceReqDetails(String resourceName, List derivedFrom, String vendorName, String vendorRelease, + String resourceVersion, Boolean isAbstract, Boolean isHighestVersion, String cost, String licenseType, + String resourceType) { + super(); + this.name = resourceName; + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.version = resourceVersion; + this.isAbstract = isAbstract; + this.isHighestVersion = isHighestVersion; + this.cost = cost; + this.licenseType = licenseType; + this.resourceType = resourceType; + this.toscaResourceName = resourceName; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + public List getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getCost() { + return cost; + } + + public void setCost(String cost) { + this.cost = cost; + } + + public String getLicenseType() { + return licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + + // Unupdatable fields - to check that they are not updated + public void setIsAbstract(Boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public void setIsHighestVersion(Boolean isHighestVersion) { + this.isHighestVersion = isHighestVersion; + } + + public Boolean getIsAbstract() { + return isAbstract; + } + + public Boolean getIsHighestVersion() { + return isHighestVersion; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + @Override + public String toString() { + return "ResourceReqDetails [name=" + name + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName + + ", vendorRelease=" + vendorRelease + ", version=" + version + ", isAbstract=" + isAbstract + + ", isHighestVersion=" + isHighestVersion + ", cost=" + cost + ", licenseType=" + licenseType + + ", resourceType=" + resourceType + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java new file mode 100644 index 0000000000..8779c49915 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java @@ -0,0 +1,369 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class ResourceRespJavaObject { + String uniqueId; + String name; + String version; + String creatorUserId; + String creatorFullName; + String lastUpdaterUserId; + String lastUpdaterFullName; + String description; + String icon; + List tags; + String isHighestVersion; + String creationDate; + String lastUpdateDate; + // String category; + String lifecycleState; + List derivedFrom; + String vendorName; + String vendorRelease; + String contactId; + String abstractt; + String highestVersion; + List artifacts; + List interfaces; + String uuid; + String cost; + String licenseType; + String resourceType; + List categories; + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public ResourceRespJavaObject(String uniqueId, String resourceName, String resourceVersion, String creatorUserId, + String creatorFullName, String lastUpdaterUserId, String lastUpdaterFullName, String description, + String icon, List tags, String isHighestVersion, String creationDate, String lastUpdateDate, + String category, String lifecycleState, List derivedFrom, String vendorName, String vendorRelease, + String contactId, String abstractt, String highestVersion, List artifacts, List interfaces, + String uuid, String cost, String licenseType, String resourceType) { + super(); + this.uniqueId = uniqueId; + this.name = resourceName; + this.version = resourceVersion; + this.creatorUserId = creatorUserId; + this.creatorFullName = creatorFullName; + this.lastUpdaterUserId = lastUpdaterUserId; + this.lastUpdaterFullName = lastUpdaterFullName; + this.description = description; + this.icon = icon; + this.tags = tags; + this.isHighestVersion = isHighestVersion; + this.creationDate = creationDate; + this.lastUpdateDate = lastUpdateDate; + // this.category = category; + this.lifecycleState = lifecycleState; + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.contactId = contactId; + this.abstractt = abstractt; + this.highestVersion = highestVersion; + this.artifacts = artifacts; + this.interfaces = interfaces; + this.uuid = uuid; + this.cost = cost; + this.licenseType = licenseType; + this.resourceType = resourceType; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getCost() { + return cost; + } + + public void setCost(String cost) { + this.cost = cost; + } + + public String getLicenseType() { + return licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + + public String getUuid() { + return uuid; + } + + public String setUuid() { + return uuid; + } + + public List getInterfaces() { + return interfaces; + } + + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + public ResourceRespJavaObject() { + super(); + // TODO Auto-generated constructor stub + } + + // public ResourceRespJavaObject(String uniqueId, String resourceName, + // String resourceVersion, String creatorUserId, + // String creatorFullName, String lastUpdaterUserId, + // String lastUpdaterFullName, String description, String icon, + // List tags, String isHighestVersion, String creationDate, + // String lastUpdateDate, String category, String lifecycleState, + // List derivedFrom, String vendorName, String vendorRelease, + // String contactId, String abstractt, String highestVersion) { + // super(); + // this.uniqueId = uniqueId; + // this.resourceName = resourceName; + // this.resourceVersion = resourceVersion; + // this.creatorUserId = creatorUserId; + // this.creatorFullName = creatorFullName; + // this.lastUpdaterUserId = lastUpdaterUserId; + // this.lastUpdaterFullName = lastUpdaterFullName; + // this.description = description; + // this.icon = icon; + // this.tags = tags; + // this.isHighestVersion = isHighestVersion; + // this.creationDate = creationDate; + // this.lastUpdateDate = lastUpdateDate; + // this.category = category; + // this.lifecycleState = lifecycleState; + // this.derivedFrom = derivedFrom; + // this.vendorName = vendorName; + // this.vendorRelease = vendorRelease; + // this.contactId = contactId; + // this.abstractt = abstractt; + // this.highestVersion = highestVersion; + // } + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getName() { + return name; + } + + public void setName(String resourceName) { + this.name = resourceName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String resourceVersion) { + this.version = resourceVersion; + } + + public String getCreatorUserId() { + return creatorUserId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getIsHighestVersion() { + return isHighestVersion; + } + + public void setIsHighestVersion(String isHighestVersion) { + this.isHighestVersion = isHighestVersion; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getLastUpdateDate() { + return lastUpdateDate; + } + + public void setLastUpdateDate(String lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + // public String getCategory() { + // return category; + // } + // public void setCategory(String category) { + // this.category = category; + // } + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public List getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getAbstractt() { + return abstractt; + } + + public void setAbstractt(String abstractt) { + this.abstractt = abstractt; + } + + public String getHighestVersion() { + return highestVersion; + } + + public void setHighestVersion(String highestVersion) { + this.highestVersion = highestVersion; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + @Override + public String toString() { + return "ResourceRespJavaObject [uniqueId=" + uniqueId + ", resourceName=" + name + ", resourceVersion=" + + version + ", creatorUserId=" + creatorUserId + ", creatorFullName=" + creatorFullName + + ", lastUpdaterUserId=" + lastUpdaterUserId + ", lastUpdaterFullName=" + lastUpdaterFullName + + ", description=" + description + ", icon=" + icon + ", tags=" + tags + ", isHighestVersion=" + + isHighestVersion + ", creationDate=" + creationDate + ", lastUpdateDate=" + lastUpdateDate + + ", lifecycleState=" + lifecycleState + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName + + ", vendorRelease=" + vendorRelease + ", contactId=" + contactId + ", abstractt=" + abstractt + + ", highestVersion=" + highestVersion + ", artifacts=" + artifacts + ", interfaces=" + interfaces + + ", uuid=" + uuid + ", cost=" + cost + ", licenseType=" + licenseType + ", resourceType=" + + resourceType + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java new file mode 100644 index 0000000000..015d228acf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes; + +public class ServiceAssetStructure extends AssetStructure { + + private String distributionStatus; + + public ServiceAssetStructure() { + super(); + } + + public ServiceAssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL, + String category, String lifecycleState, String lastUpdaterUserId) { + super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId); + } + + @Override + public String toString() { + return "ServiceAssetStructure [distributionStatus=" + distributionStatus + "]"; + } + + public String getDistributionStatus() { + return distributionStatus; + } + + public void setDistributionStatus(String distributionStatus) { + this.distributionStatus = distributionStatus; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java new file mode 100644 index 0000000000..cc283a3169 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes; + +import java.util.List; + +public class ServiceDetailedAssetStructure extends ServiceAssetStructure { + + String lastUpdaterFullName; + List resources; + List artifacts; + + public ServiceDetailedAssetStructure() { + super(); + } + + public ServiceDetailedAssetStructure(String uuid, String invariantUUID, String name, String version, + String toscaModelURL, String category, String lifecycleState, String lastUpdaterUserId) { + super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId); + } + + public ServiceDetailedAssetStructure(String lastUpdaterFullName, List resources, + List artifacts) { + super(); + this.lastUpdaterFullName = lastUpdaterFullName; + this.resources = resources; + this.artifacts = artifacts; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + @Override + public String toString() { + return "ServiceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", resources=" + resources + + ", artifacts=" + artifacts + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java new file mode 100644 index 0000000000..dde1f27cca --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java @@ -0,0 +1,80 @@ +/*- + * ============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.ci.tests.datatypes; + +public class ServiceDistributionStatus { + + private String distributionID; + private String timestamp; + private String userId; + private String deployementStatus; + + public ServiceDistributionStatus() { + super(); + // TODO Auto-generated constructor stub + } + + public ServiceDistributionStatus(String distributionID, String timestamp, String userId, String deployementStatus) { + super(); + this.distributionID = distributionID; + this.timestamp = timestamp; + this.userId = userId; + this.deployementStatus = deployementStatus; + } + + @Override + public String toString() { + return "ServiceDistributionStatus [distributionID=" + distributionID + ", timestamp=" + timestamp + ", userId=" + userId + ", deployementStatus=" + deployementStatus + "]"; + } + + public String getDistributionID() { + return distributionID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getDeployementStatus() { + return deployementStatus; + } + + public void setDeployementStatus(String deployementStatus) { + this.deployementStatus = deployementStatus; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java new file mode 100644 index 0000000000..e33183ca94 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java @@ -0,0 +1,91 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.ArrayList; + +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class ServiceReqDetails extends ComponentReqDetails { + + public ServiceReqDetails(String serviceName, String category, ArrayList tags, String description, + String contactId, String icon) { + this.name = serviceName; + // this.category = category; + this.tags = tags; + this.description = description; + this.contactId = contactId; + this.icon = icon; + projectCode = "12345"; + CategoryDefinition categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(category); + categories = new ArrayList<>(); + categories.add(categoryDefinition); + + } + + public ServiceReqDetails(Service service) { + this.contactId = service.getContactId(); + this.categories = service.getCategories(); + this.creatorUserId = service.getCreatorUserId(); + this.creatorFullName = service.getCreatorFullName(); + this.description = service.getDescription(); + this.icon = service.getIcon(); + this.name = service.getName(); + this.projectCode = service.getProjectCode(); + this.tags = service.getTags(); + this.uniqueId = service.getUniqueId(); + this.UUID = service.getUUID(); + this.version = service.getVersion(); + + } + + public ServiceReqDetails() { + contactId = "aa1234"; + projectCode = "12345"; + } + + public ServiceReqDetails(ServiceReqDetails a, String newServiceName) { + a.setName(newServiceName); + } + + @Override + public String toString() { + return "ServiceDetails [name=" + name + ", category=" + getCategory() + ", tags=" + tags + ", description=" + + description + ", contactId=" + contactId + ", icon=" + icon + "]"; + } + + public ServiceReqDetails(ServiceReqDetails aService) { + this(aService.getName(), aService.getCategory(), (ArrayList) aService.getTags(), + aService.getDescription(), aService.getContactId(), aService.getIcon()); + uniqueId = aService.getUniqueId(); + version = aService.getVersion(); + } + + public String getCategory() { + if (categories != null && categories.size() >= 1) { + return categories.get(0).getName(); + } + return null; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java new file mode 100644 index 0000000000..723f6a47c6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java @@ -0,0 +1,268 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.ArrayList; +import java.util.List; + +public class ServiceRespJavaObject { + + String category; + String creatorUserId; + String creatorFullName; + String lastUpdaterUserId; + String lastUpdaterFullName; + String serviceName; + String version; + String creationDate; + String icon; + String name; + String description; + ArrayList tags; + String uniqueId; + String lastUpdateDate; + String contactId; + String vendorName; + String vendorRelease; + String lifecycleState; + String highestVersion; + ArrayList artifacts; + ArrayList ResourceInstances; + ArrayList ResourceInstancesRelations; + + public ServiceRespJavaObject() { + super(); + // TODO Auto-generated constructor stub + } + + public ServiceRespJavaObject(String category, String creatorUserId, String creatorFullName, + String lastUpdaterUserId, String lastUpdaterFullName, String serviceName, String version, + String creationDate, String icon, String name, String description, ArrayList tags, String uniqueId, + String lastUpdateDate, String contactId, String vendorName, String vendorRelease, String lifecycleState, + String highestVersion, ArrayList artifacts, ArrayList resourceInstances, + ArrayList resourceInstancesRelations) { + super(); + this.category = category; + this.creatorUserId = creatorUserId; + this.creatorFullName = creatorFullName; + this.lastUpdaterUserId = lastUpdaterUserId; + this.lastUpdaterFullName = lastUpdaterFullName; + this.serviceName = serviceName; + this.version = version; + this.creationDate = creationDate; + this.icon = icon; + this.name = name; + this.description = description; + this.tags = tags; + this.uniqueId = uniqueId; + this.lastUpdateDate = lastUpdateDate; + this.contactId = contactId; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.lifecycleState = lifecycleState; + this.highestVersion = highestVersion; + this.artifacts = artifacts; + ResourceInstances = resourceInstances; + ResourceInstancesRelations = resourceInstancesRelations; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getCreatorUserId() { + return creatorUserId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public ArrayList getTags() { + return tags; + } + + public void setTags(ArrayList tags) { + this.tags = tags; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getLastUpdateDate() { + return lastUpdateDate; + } + + public void setLastUpdateDate(String lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public String getHighestVersion() { + return highestVersion; + } + + public void setHighestVersion(String highest) { + this.highestVersion = highest; + } + + public ArrayList getArtifacts() { + return artifacts; + } + + public void setArtifacts(ArrayList artifacts) { + this.artifacts = artifacts; + } + + public ArrayList getResourceInstances() { + return ResourceInstances; + } + + public void setResourceInstances(ArrayList resourceInstances) { + ResourceInstances = resourceInstances; + } + + public ArrayList getResourceInstancesRelations() { + return ResourceInstancesRelations; + } + + public void setResourceInstancesRelations(ArrayList resourceInstancesRelations) { + ResourceInstancesRelations = resourceInstancesRelations; + } + + @Override + public String toString() { + return "ServiceRespJavaObject [category=" + category + ", creatorUserId=" + creatorUserId + ", creatorFullName=" + + creatorFullName + ", lastUpdaterUserId=" + lastUpdaterUserId + ", lastUpdaterFullName=" + + lastUpdaterFullName + ", serviceName=" + serviceName + ", version=" + version + ", creationDate=" + + creationDate + ", icon=" + icon + ", name=" + name + ", description=" + description + ", tags=" + tags + + ", uniqueId=" + uniqueId + ", lastUpdateDate=" + lastUpdateDate + ", contactId=" + contactId + + ", vendorName=" + vendorName + ", vendorRelease=" + vendorRelease + ", lifecycleState=" + + lifecycleState + ", lifecycleState=" + lifecycleState + ", artifacts=" + artifacts + + ", ResourceInstances=" + ResourceInstances + ", ResourceInstancesRelations=" + + ResourceInstancesRelations + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java new file mode 100644 index 0000000000..d0f029242f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java @@ -0,0 +1,57 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +public class TypeHeatMetaDefinition { + + String typeName; + + List groupHeatMetaDefinition; + + public TypeHeatMetaDefinition() { + super(); + } + + public String getTypeName() { + return typeName; + } + + public void setTypeName(String typeName) { + this.typeName = typeName; + } + + public List getGroupHeatMetaDefinition() { + return groupHeatMetaDefinition; + } + + public void setGroupHeatMetaDefinition(List groupHeatMetaDefinition) { + this.groupHeatMetaDefinition = groupHeatMetaDefinition; + } + + @Override + public String toString() { + return "TypeHeatMetaDefinition [typeName=" + typeName + ", groupHeatMetaDefinition=" + groupHeatMetaDefinition + + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java new file mode 100644 index 0000000000..4e4c87f112 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java @@ -0,0 +1,77 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +import java.util.ArrayList; +import java.util.List; + +/** + * Enum That Represents possible Artifacts Types. + * + */ +public enum ArtifactTypeEnum { + CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), ICON("ICON"), UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG("MURANO_PKG"), + HEAT_ENV("HEAT_ENV"), YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"), NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), + TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"), VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"), VENDOR_LICENSE("VENDOR_LICENSE"), + MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"), + HEAT_ARTIFACT("HEAT_ARTIFACT"), VF_MODULES_METADATA("VF_MODULES_METADATA"), + // DCAE Artifacts + DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"), DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), + DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), + DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), + // AAI Artifacts + AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), + // MIB artifacts + SNMP_POLL ("SNMP_POLL"), SNMP_TRAP("SNMP_TRAP"), GUIDE("GUIDE") + ; + + ArtifactTypeEnum(String type) { + this.type = type; + } + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public static ArtifactTypeEnum findType(final String type) { + for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { + // According to Pavel/Ella + if (ate.getType().equalsIgnoreCase(type)) { + return ate; + } + } + return null; + } + + public static List getAllTypes() { + List types = new ArrayList(); + for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { + types.add(ate.getType()); + } + return types; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java new file mode 100644 index 0000000000..82e9a36780 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java @@ -0,0 +1,39 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum AssocType { + + BINDABLE("tosca.capabilities.network.Bindable"), HOSTEDON("tosca.relationships.HostedOn"), LINKABLE("tosca.capabilities.network.Linkable"), + CONTAINER("tosca.capabilities.Container"), NODE("tosca.capabilities.Node"); + + private String assocType; + + private AssocType(String assocType) { + this.assocType = assocType; + + } + + public String getAssocType() { + return assocType; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java new file mode 100644 index 0000000000..a713d5089f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java @@ -0,0 +1,39 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum AuditEnum { + + ACTION("ACTION"), RESOURCE_NAME("RESOURCE_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), PREV_VERSION("PREV_VERSION"), CURR_VERSION("CURR_VERSION"), MODIFIER("MODIFIER"), PREV_STATE("PREV_STATE"), + CURR_STATE("CURR_STATE"), STATUS("STATUS-Type"), DESC("DESC"), URL("URL"), USER("USER"), AUTH_STATUS("AUTH_STATUS"), REALM("REALM"); + + String value; + + private AuditEnum(String value) { + this.value = value; + } + + public String getValue() { + + return value.toLowerCase(); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java new file mode 100644 index 0000000000..308ea5c990 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java @@ -0,0 +1,40 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum AuditJsonKeysEnum { + + ACTION("ACTION"), RESOURCE_NAME("RESOURCE_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), PREV_VERSION("PREV_VERSION"), CURR_VERSION("CURR_VERSION"), PREV_STATE("PREV_STATE"), CURR_STATE("CURR_STATE"), + DPREV_STATUS("DPREV_STATUS"), DCURR_STATUS("DCURR_STATUS"), STATUS("STATUS"), DESCRIPTION("DESCRIPTION"), ARTIFACT_DATA("ARTIFACT_DATA"), CONSUMER_ID("CONSUMER_ID"), RESOURCE_URL("RESOURCE_URL"), + COMMENT("COMMENT"), DID("DID"), TOPIC_NAME("TOPIC_NAME"), TOSCA_NODE_TYPE("TOSCA_NODE_TYPE"), CURR_ARTIFACT_UUID("CURR_ARTIFACT_UUID"), PREV_ARTIFACT_UUID("PREV_ARTIFACT_UUID"), DETAILS("DETAILS"), + MODIFIER("MODIFIER"), SERVICE_INSTANCE_ID("SERVICE_INSTANCE_ID"), INVARIANT_UUID("INVARIANT_UUID"); + + private String auditJsonKeyName; + + private AuditJsonKeysEnum(String auditJsonKeyName) { + this.auditJsonKeyName = auditJsonKeyName; + } + + public String getAuditJsonKeyName() { + return auditJsonKeyName.toLowerCase(); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java new file mode 100644 index 0000000000..3d242e8c52 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java @@ -0,0 +1,37 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum ComponentType { + + RESOURCE("Resource"), SERVICE("Service"), ARTIFACT("Artifact"); + + String value; + + private ComponentType(String value) { + this.value = value; + } + + public String getValue() { + + return value; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java new file mode 100644 index 0000000000..7042a954e7 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes.enums; + +public enum DistributionNotificationStatusEnum { + + + DEPLOY_OK("DEPLOY_OK"), + DOWNLOAD_OK("DOWNLOAD_OK"), + NOTIFIED("NOTIFIED"), + NOT_NOTIFIED("NOT_NOTIFIED"); + + private String value; + + private DistributionNotificationStatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static DistributionNotificationStatusEnum findState(String state) { + + for (DistributionNotificationStatusEnum distributionStatus : DistributionNotificationStatusEnum.values()) { + if (distributionStatus.name().equalsIgnoreCase(state) + || distributionStatus.getValue().equalsIgnoreCase(state)) { + return distributionStatus; + } + } + return null; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java new file mode 100644 index 0000000000..c2a28a1edf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java @@ -0,0 +1,93 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public class ErrorInfo { + + private Integer code; + private String message; + private String messageId; + + public ErrorInfo() { + super(); + // TODO Auto-generated constructor stub + } + + public ErrorInfo(Integer code, String message, String messageId) { + super(); + this.code = code; + this.message = message; + this.messageId = messageId; + } + + public ErrorInfo(Integer code, String message) { + super(); + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public String getMessageAndReplaceVariables(Object... variables) { + String formatReadyString = message.replaceAll("%[\\d]+", "%s"); + formatReadyString = String.format(formatReadyString, variables); + return formatReadyString; + } + + public String getAuditDesc(Object... variables) { + String messageAndReplaceVariables = getMessageAndReplaceVariables(variables); + String res; + if (messageId != null) { + res = messageId + ": " + messageAndReplaceVariables; + } else { + res = messageAndReplaceVariables; + } + return res; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + @Override + public String toString() { + return "ErrorInfo [code=" + code + ", message=" + message + ", messageId=" + messageId + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java new file mode 100644 index 0000000000..6bfbd8af7d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java @@ -0,0 +1,64 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public class EsIndexTypeIdToDelete { + + String index; + String type; + String id; + + public EsIndexTypeIdToDelete() { + super(); + } + + public EsIndexTypeIdToDelete(String index, String type, String id) { + super(); + this.index = index; + this.type = type; + this.id = id; + } + + public String getIndex() { + return index; + } + + public void setIndex(String index) { + this.index = index; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java new file mode 100644 index 0000000000..59d1dec453 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java @@ -0,0 +1,36 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum ExceptionEnumType { + + SERVICE_EXCEPTION("serviceException"), POLICY_EXCPTION("policyException"); + + String value; + + private ExceptionEnumType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java new file mode 100644 index 0000000000..21901e4635 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java @@ -0,0 +1,95 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +import java.util.Arrays; +import java.util.List; + +import org.openecomp.sdc.be.dao.api.ActionStatus; + +public enum ImportTestTypesEnum { + + MISSING_CONTACT("tosca.nodes.missing_contact", "missing_contact", ActionStatus.COMPONENT_MISSING_CONTACT, Arrays.asList("Resource"), true), + MISSING_RESOURCE_NAME("tosca.nodes.missing_resource_name", "missing_resource_name", ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Resource"), true), + MISSING_DESC("tosca.nodes.missing_desc", "missing_desc", ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Resource"), true), + MISSING_ICON("tosca.nodes.missing_icon", "missing_icon", ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Resource"), true), + MISSING_TAGS("tosca.nodes.missing_tags", "missing_tags", ActionStatus.COMPONENT_MISSING_TAGS, null, true), + MISSING_CATEGORY("tosca.nodes.missing_category", "missing_category", ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Resource"), true), + // MISSING_PAYLOADNAME("tosca.nodes.missing_payloadName", + // "missing_payloadName", ActionStatus.INVALID_TOSCA_FILE_EXTENSION, null, + // true), + + EMPTY_RESOURCE_NAME("tosca.nodes.empty_resource_name", "missing_resource_name"/* "empty_resource_name" */, ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Resource"), false), + EMPTY_CONTACT("tosca.nodes.empty_contact", "missing_contact"/* "empty_contact" */, ActionStatus.COMPONENT_MISSING_CONTACT, Arrays.asList("Resource"), false), + EMPTY_CATEGORY("tosca.nodes.empty_category", "missing_category"/* "empty_category" */, ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Resource"), false), + EMPTY_DESC("tosca.nodes.empty_desc", "missing_desc"/* "empty_desc" */, ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Resource"), false), + EMPTY_ICON("tosca.nodes.empty_icon", "missing_icon"/* "empty_icon" */, ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Resource"), false), + EMPTY_PAYLOADNAME("tosca.nodes.empty_payloadName", "missing_payloadName"/* "empty_payloadName" */, ActionStatus.INVALID_TOSCA_FILE_EXTENSION, null, false), + EMPTY_TAG("tosca.nodes.empty_tag", "empty_tag", ActionStatus.INVALID_FIELD_FORMAT, Arrays.asList("Resource", "tag"), false), + VALIDATE_PROPORTIES_1("tosca.nodes.validateProporties_typeBoolean_valueInit", "validateProporties_typeBoolean_valueInit", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "boolean", "123456"), false), + VALIDATE_PROPORTIES_2("tosca.nodes.validateProporties_typeBoolean_valueString", "validateProporties_typeBoolean_valueString", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "boolean", "abcd"), false), + VALIDATE_PROPORTIES_3("tosca.nodes.validateProporties_typeFloat_valueBoolean", "validateProporties_typeFloat_valueBoolean", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "float", "true"), false), + VALIDATE_PROPORTIES_4("tosca.nodes.validateProporties_typeFloat_valueString", "validateProporties_typeFloat_valueString", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "float", "abcd"), false), + VALIDATE_PROPORTIES_5("tosca.nodes.validateProporties_typeInit_valueBoolean", "validateProporties_typeInit_valueBoolean", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "integer", "true"), false), + VALIDATE_PROPORTIES_6("tosca.nodes.validateProporties_typeInit_valueFloat", "validateProporties_typeInit_valueFloat", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "integer", "0.123"), false), + VALIDATE_PROPORTIES_7("tosca.nodes.validateProporties_typeInit_valueString", "validateProporties_typeInit_valueString", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "integer", "abcd"), false); + // VALIDATE_PROPORTIES_8("tosca.nodes.validateProporties_happyScenarios","validateProporties_happyScenarios", ActionStatus.OK, null, false); + + private String normativeName; + private String folderName; + private ActionStatus actionStatus; + private Boolean validateAudit; + private List errorParams; + private Boolean validateYaml; + + // private enum ActionStatus; + + private ImportTestTypesEnum(String resourceName, String folderName, ActionStatus actionStatus, + List errorParams, Boolean validateAudit) { + this.normativeName = resourceName; + this.folderName = folderName; + this.actionStatus = actionStatus; + this.errorParams = errorParams; + this.validateAudit = validateAudit; + + } + + public String getNormativeName() { + return normativeName; + } + + public String getFolderName() { + return folderName; + } + + public ActionStatus getActionStatus() { + return actionStatus; + } + + public Boolean getvalidateAudit() { + return validateAudit; + } + + public List getErrorParams() { + return errorParams; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java new file mode 100644 index 0000000000..9edfb9aced --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java @@ -0,0 +1,77 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +import java.util.List; + +public enum LifeCycleStatesEnum { + + CHECKOUT("checkout", "NOT_CERTIFIED_CHECKOUT"), + CHECKIN("checkin", "NOT_CERTIFIED_CHECKIN"), + CERTIFICATIONREQUEST("certificationRequest", "READY_FOR_CERTIFICATION"), + UNDOCHECKOUT("undoCheckout", ""), + CANCELCERTIFICATION("cancelCertification", ""), + STARTCERTIFICATION("startCertification", "CERTIFICATION_IN_PROGRESS"), + FAILCERTIFICATION("failCertification", ""), + CERTIFY("certify", "CERTIFIED"); + + private String state; + private String componentState; + + private LifeCycleStatesEnum(String state, String componentState) { + this.state = state; + this.componentState = componentState; + + } + + public String getState() { + return state; + } + + public String getComponentState() { + return componentState; + } + + public static LifeCycleStatesEnum findByCompState(String compState) { + + for (LifeCycleStatesEnum lifeCycleStatesEnum : LifeCycleStatesEnum.values()) { + if (lifeCycleStatesEnum.getComponentState().equals(compState)) { + return lifeCycleStatesEnum; + } + } + + return null; + + } + + public static LifeCycleStatesEnum findByState(String state) { + + for (LifeCycleStatesEnum lifeCycleStatesEnum : LifeCycleStatesEnum.values()) { + if (lifeCycleStatesEnum.name().equals(state)) { + return lifeCycleStatesEnum; + } + } + + return null; + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java new file mode 100644 index 0000000000..58892439b0 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes.enums; + +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; + +public enum MandatoryResourceArtifactTypeEnum { + + TEST_SCRIPTS(null, "testscripts"), FEATURES(null, "features"), CAPACITY(null, "capacity"), VENDOR_TEST_RESULT(null, "vendortestresult"), CLOUD_QUESTIONNAIRE(null, "cloudQuestionnaire"); + + String artifactName; + String logicalName; + + private MandatoryResourceArtifactTypeEnum(String artifactName, String logicalName) { + this.artifactName = artifactName; + this.logicalName = logicalName; + } + + public String getArtifactName() { + return artifactName; + } + + public String getLogicalName() { + return logicalName; + } + + public ArtifactGroupTypeEnum getGroupType() { + return ArtifactGroupTypeEnum.INFORMATIONAL; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java new file mode 100644 index 0000000000..b73d5a8fee --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java @@ -0,0 +1,66 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum MandatoryServiceArtifactTypeEnum { + + MESSAGE_FLOWS(null, "messageflows".toLowerCase(), "Message Flows"), + INSTANT_FLOWS(null, "instantiationflows".toLowerCase(), "Management Flows"), + SERVICE_ART_PLAN(null, "serviceartifactplan".toLowerCase(), "Service Artifact Plan"), + SUM_OF_ELEMENTS(null, "summaryofimpactstoecompelements".toLowerCase(), "Summary of impacts to ECOMP elements,OSSs, BSSs"), + CONTROL_LOOP_FUN(null, "controlloopfunctions".toLowerCase(), "Control Loop Functions"), + DIMENSIONNING_INFO(null, "dimensioninginfo".toLowerCase(), "Dimensioning Info"), + AFFINITY_RULES(null, "affinityrules".toLowerCase(), "Affinity Rules"), + OPERATIONAL_POLICIES(null, "operationalpolicies".toLowerCase(), "Operational Policies"), + SERVICE_SPECIFIC_POLICIES(null, "servicespecificpolicies".toLowerCase(), "Service-specific Policies"), + ENGINEERING_RULES(null, "engineeringrules".toLowerCase(), "Engineering Rules (ERD)"), + DISTRIB_INSTRUCTIONS(null, "distributioninstructions".toLowerCase(), "Distribution Instructions"), + DEPLOYMENT_VOTING_REC(null, "deploymentvotingrecord".toLowerCase(), "Deployment Voting Record"), + CERTIFICATION_TEST_RESULT(null, "certificationtestresults".toLowerCase(), "TD Certification Test Results"); + // SERVICE_QUESTIONNAIRE(null, "serviceQuestionnaire".toLowerCase()); + + String artifactName; + String logicalName; + String artifactDisplayName; + + private MandatoryServiceArtifactTypeEnum(String artifactName, String logicalName, String artifactDisplayName) { + this.artifactName = artifactName; + this.logicalName = logicalName; + this.artifactDisplayName = artifactDisplayName; + } + + public String getArtifactName() { + return artifactName; + } + + public String getLogicalName() { + return logicalName; + } + + public String getArtifactDisplayName() { + return artifactDisplayName; + } + + public void setArtifactDisplayName(String artifactDisplayName) { + this.artifactDisplayName = artifactDisplayName; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java new file mode 100644 index 0000000000..389b962f1c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java @@ -0,0 +1,45 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum NormativeTypesEnum { + ROOT("tosca.nodes.Root", "root"), COMPUTE("tosca.nodes.Compute", "compute"), BLOCK_STORAGE("tosca.nodes.BlockStorage", "blockStorage"), CONTAINER_APPLICATION("tosca.nodes.Container.Application", "containerApplication"), + CONTAINER_RUNTIME("tosca.nodes.Container.Runtime","containerRuntime"), DATABASE("tosca.nodes.Database", "database"), DBMS("tosca.nodes.DBMS", "DBMS"), LOAD_BALANCER("tosca.nodes.LoadBalancer", "loadBalancer"), + OBJECT_STORAGE("tosca.nodes.ObjectStorage", "objectStorage"), NETWORK("tosca.nodes.network.Network", "network"), PORT("tosca.nodes.network.Port", "port"), SOFTWARE_COMPONENT("tosca.nodes.SoftwareComponent", "softwareComponent"), + WEB_APPLICATION("tosca.nodes.webapplication","webApplication"), WEB_SERVER("tosca.nodes.WebServer", "webServer"); + + public String normativeName; + private String folderName; + + private NormativeTypesEnum(String resourceName, String folderName) { + this.normativeName = resourceName; + this.folderName = folderName; + } + + public String getNormativeName() { + return normativeName; + } + + public String getFolderName() { + return folderName; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java new file mode 100644 index 0000000000..d85a496241 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java @@ -0,0 +1,74 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; + +public enum OriginTypeEnum { + PRODUCT("Product", "Product", "product instance", ComponentTypeEnum.PRODUCT), + SERVICE("Service", "Service", "service instance", ComponentTypeEnum.SERVICE), + VF("VF", "VF (Virtual Function)", "resource instance", ComponentTypeEnum.RESOURCE), + 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), + VFi("VFi", "VFi (Virtual Function Instance)", "resource instance", ComponentTypeEnum.RESOURCE_INSTANCE); + + + private String value; + private String displayValue; + private String instanceType; + private ComponentTypeEnum componentType; + + private OriginTypeEnum(String value, String displayValue, String instanceType, ComponentTypeEnum componentType) { + this.value = value; + this.displayValue = displayValue; + this.instanceType = instanceType; + this.componentType = componentType; + } + + public String getValue() { + return value; + } + + public String getDisplayValue() { + return displayValue; + } + + public String getInstanceType() { + return instanceType; + } + + public ComponentTypeEnum getComponentType() { + return componentType; + } + + public static OriginTypeEnum findByValue(String value) { + OriginTypeEnum ret = null; + for (OriginTypeEnum curr : OriginTypeEnum.values()) { + if (curr.getValue().equals(value)) { + ret = curr; + break; + } + } + return ret; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java new file mode 100644 index 0000000000..8a1dc84684 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java @@ -0,0 +1,107 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; + +public enum PropertyTypeEnum { + INTEGER("defaultIntegerPropName1", "integer", "125", "default integer type property description", null), + STRING("defaultStringPropName1", "string", "string", "default string type property description", null), + BOOLEAN("defaultBooleanPropName1", "boolean", "true", "default boolean type property description", null), + FLOAT("defaultBooleanPropName1", "float", "1.2", "default float type property description", null), + STRING_LIST("defaultStringListPropName", "list", "[a,b]", "outer description", getDefaultStringSchema(ToscaPropertyType.STRING.getType())), + INTEGER_LIST("defaultIntegerListPropName", "list", "[1,2]", "outer description", getDefaultStringSchema(ToscaPropertyType.INTEGER.getType())), + BOOLEAN_LIST("defaultBooleanListPropName", "list", "[true,false]", "outer description", getDefaultStringSchema(ToscaPropertyType.BOOLEAN.getType())), + FLOAT_LIST("defaultFloatMapPropName", "list", "[1.0,2.0]", "outer description", getDefaultStringSchema(ToscaPropertyType.FLOAT.getType())), + STRING_MAP("defaultStringMapPropName", "map", "{\"key1\":val1 , \"key2\":val2}", "outer description", getDefaultStringSchema(ToscaPropertyType.STRING.getType())), + INTEGER_MAP("defaultIntegerMapPropName", "map", "{\"key1\":123 , \"key2\":-456}", "outer description", getDefaultStringSchema(ToscaPropertyType.INTEGER.getType())), + BOOLEAN_MAP("defaultBooleanMapPropName", "map", "{\"key1\":true , \"key2\":false}", "outer description", getDefaultStringSchema(ToscaPropertyType.BOOLEAN.getType())), + FLOAT_MAP("defaultFloatMapPropName", "map", "{\"key1\":0.2123 , \"key2\":43.545f}", "outer description", getDefaultStringSchema(ToscaPropertyType.FLOAT.getType())); + + private String name; + private String type; + private String value; + private String description; + private SchemaDefinition schemaDefinition; + + private PropertyTypeEnum(String name, String type, String value, String description, + SchemaDefinition schemaDefinition) { + this.name = name; + this.type = type; + this.value = value; + this.description = description; + this.schemaDefinition = schemaDefinition; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public SchemaDefinition getSchemaDefinition() { + return schemaDefinition; + } + + public void setSchemaDefinition(SchemaDefinition schemaDefinition) { + this.schemaDefinition = schemaDefinition; + } + + private static SchemaDefinition getDefaultStringSchema(String innerType) { + SchemaDefinition schema = new SchemaDefinition(); + String description = "inner description"; + PropertyDefinition property = new PropertyDefinition(); + property.setType(innerType); + property.setDescription(description); + schema.setProperty(property); + return schema; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java new file mode 100644 index 0000000000..47123a61e7 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java @@ -0,0 +1,57 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum ResourceCategoryEnum { + + NETWORK_L2_3_ROUTERS("Network L2-3", "Router"), NETWORK_L2_3_GETEWAY("Network L2-3","Gateway"), NETWORK_L2_3_WAN_CONNECTORS("Network L2-3", "WAN Connectors"), NETWORK_L2_3_LAN_CONNECTORS("Network L2-3", "LAN Connectors"), + NETWORK_L2_3_INFRASTRUCTURE("Network L2-3", "Infrastructure"), NETWORK_L4("Network L4+", "Common Network Resources"), APPLICATION_L4_BORDER("Application L4+", "Border Element"), + APPLICATION_L4_APP_SERVER("Application L4+", "Application Server"), APPLICATION_L4_WEB_SERVERS("Application L4+", "Web Server"), APPLICATION_L4_CALL_CONTROL("Application L4+","Call Control"), + APPLICATION_L4_MEDIA_SERVER("Application L4+", "Media Servers"), APPLICATION_L4_LOAD_BALANCER("Application L4+", "Load Balancer"), APPLICATION_L4_DATABASE("Application L4+","Database"), + APPLICATION_L4_FIREWALL("Application L4+", "Firewall"), GENERIC_INFRASTRUCTURE("Generic", "Infrastructure"), GENERIC_ABSTRACT("Generic", "Abstract"), GENERIC_NETWORK_ELEMENTS("Generic","Network Elements"), + GENERIC_DATABASE("Generic", "Database"), NETWORK_CONNECTIVITY_CON_POINT("Network Connectivity", "Connection Points"), NETWORK_CONNECTIVITY_VIRTUAL_LINK("Network Connectivity","Virtual Links"), + TEMPLATE_MONITORING_TEMPLATE("Template", "Monitoring Template"), ALLOTTED_RESOURCE("Allotted Resource", "Allotted Resource"); + + private String category; + private String subCategory; + + ResourceCategoryEnum(String category, String subCategory) { + this.category = category; + this.subCategory = subCategory; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java new file mode 100644 index 0000000000..a977e38fe2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java @@ -0,0 +1,40 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum RespJsonKeysEnum { + + IS_ABSTRACT("abstract"), UNIQUE_ID("uniqueId"), RESOURCE_NAME("name"), RESOURCE_VERSION("version"), TAGS("tags"), LIFE_CYCLE_STATE("lifecycleState"), DERIVED_FROM("derivedFrom"), RESOURCE_DESC("description"), + VENDOR_NAME("vendorName"), VENDOR_RELEASE("vendorRelease"), CONTACT_ID("contactId"), ICON("icon"), HIGHEST_VERSION("highestVersion"), CREATOR_ATT_UID("creatorUserId"), CREATOR_FULL_NAME("creatorFullName"), + LAST_UPDATER_ATT_UID("lastUpdaterUserId"), LAST_UPDATER_FULL_NAME("lastUpdaterFullName"), ARTIFACTS("artifacts"), DESCRIPTION("description"), UUID("uuid"), COST("cost"), LICENSE_TYPE("licenseType"), + RESOURCE_TYPE("resourceType"), CATEGORIES("categories"); + + private String respJsonKeyName; + + private RespJsonKeysEnum(String respJsonKeyName) { + this.respJsonKeyName = respJsonKeyName; + } + + public String getRespJsonKeyName() { + return respJsonKeyName; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java new file mode 100644 index 0000000000..f26423a35d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java @@ -0,0 +1,38 @@ +/*- + * ============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.ci.tests.datatypes.enums; + + + +public enum SearchCriteriaEnum { + + RESOURCE_TYPE("resourceType"), CATEGORY("category"), SUBCATEGORY("subCategory"); + + private String value; + + private SearchCriteriaEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java new file mode 100644 index 0000000000..4cfcc8a558 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java @@ -0,0 +1,35 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum ServiceApiArtifactEnum { + CONFIGURATION("Configuration".toLowerCase()), INSTANTIATION("Instantiation".toLowerCase()), MONITORING("Monitoring".toLowerCase()), REPORTING("Reporting".toLowerCase()), LOGGING("Logging".toLowerCase()), TESTING("Testing".toLowerCase()); + + String logicalName; + + private ServiceApiArtifactEnum(String logicalName) { + this.logicalName = logicalName; + } + + public String getLogicalName() { + return logicalName; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java new file mode 100644 index 0000000000..61d4e487e2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java @@ -0,0 +1,37 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum ServiceCategoriesEnum { + + VOIP("VoIP Call Control"), MOBILITY("Mobility"), NETWORK_L4("Network L4+"), NETWORK_L3("Network L1-3"); + String value; + + private ServiceCategoriesEnum(String value) { + this.value = value; + } + + public String getValue() { + + return value; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java new file mode 100644 index 0000000000..b8635b3bda --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java @@ -0,0 +1,46 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum ToscaKeysEnum { + + TOSCA_DEFINITION_VERSION("tosca_definitions_version"), METADATA("metadata"), IMPORTS("imports"), NODE_TYPES("node_types"), TOPOLOGY_TEMPLATE("topology_template"); + + private String toscaKey; + + public String getToscaKey() { + return toscaKey; + } + + private ToscaKeysEnum(String toscaKey) { + this.toscaKey = toscaKey; + } + + public static ToscaKeysEnum findToscaKey(final String toscaKey) { + for (ToscaKeysEnum toscaKeyEnum : ToscaKeysEnum.values()) { + if (toscaKeyEnum.getToscaKey().equalsIgnoreCase(toscaKey)) { + return toscaKeyEnum; + } + } + return null; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java new file mode 100644 index 0000000000..fb04f6a68b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java @@ -0,0 +1,77 @@ +/*- + * ============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.ci.tests.datatypes.enums; + +public enum UserRoleEnum { + + ADMIN("jh0003", "Jimmy", "Hendrix"), DESIGNER("cs0008", "Carlos", "Santana"), DESIGNER2("me0009", "Melissa","Etheridge"), TESTER("jm0007", "Joni", "Mitchell"), ADMIN4("km2000", "Kot", "May"), + GOVERNOR("gv0001","David", "Shadmi"), OPS("op0001", "Steve", "Regev"), PRODUCT_STRATEGIST1("ps0001", "Eden","Rozin"), PRODUCT_STRATEGIST2("ps0002", "Ella", "Kvetny"), PRODUCT_STRATEGIST3("ps0003", "Geva", "Alon"), + PRODUCT_MANAGER1("pm0001", "Teddy", "Isashar"), PRODUCT_MANAGER2("pm0002", "Sarah", "Bettens"); + private String userId; + private String firstName; + private String lastName; + private String userName; + + private UserRoleEnum(String userId, String userName) { + this.userId = userId; + this.userName = userName; + } + + private UserRoleEnum(String userId, String firstName, String lastName) { + this.userId = userId; + this.firstName = firstName; + this.lastName = lastName; + this.userName = firstName + " " + lastName; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java new file mode 100644 index 0000000000..344f353348 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java @@ -0,0 +1,166 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedArtifactAudit { + + private String action; + private String resourceName; + private String resourceType; + private String prevVersion; + private String currVersion; + private String modifier; + private String prevState; + private String currState; + private String prevArtifactUuid; + private String currArtifactUuid; + private String artifactData; + private String status; + private String desc; + + public ExpectedArtifactAudit(String action, String resourceName, String resourceType, String prevVersion, + String currVersion, String modifier, String prevState, String currState, String prevArtifactUuid, + String currArtifactUuid, String artifactData, String status, String desc) { + super(); + this.action = action; + this.resourceName = resourceName; + this.resourceType = resourceType; + this.prevVersion = prevVersion; + this.currVersion = currVersion; + this.modifier = modifier; + this.prevState = prevState; + this.currState = currState; + this.prevArtifactUuid = prevArtifactUuid; + this.currArtifactUuid = currArtifactUuid; + this.artifactData = artifactData; + this.status = status; + this.desc = desc; + } + + public ExpectedArtifactAudit() { + super(); + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getPrevVersion() { + return prevVersion; + } + + public void setPrevVersion(String prevVersion) { + this.prevVersion = prevVersion; + } + + public String getCurrVersion() { + return currVersion; + } + + public void setCurrVersion(String currVersion) { + this.currVersion = currVersion; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getPrevState() { + return prevState; + } + + public void setPrevState(String prevState) { + this.prevState = prevState; + } + + public String getCurrState() { + return currState; + } + + public void setCurrState(String currState) { + this.currState = currState; + } + + public String getPrevArtifactUuid() { + return prevArtifactUuid; + } + + public void setPrevArtifactUuid(String prevArtifactUuid) { + this.prevArtifactUuid = prevArtifactUuid; + } + + public String getCurrArtifactUuid() { + return currArtifactUuid; + } + + public void setCurrArtifactUuid(String currArtifactUuid) { + this.currArtifactUuid = currArtifactUuid; + } + + public String getArtifactData() { + return artifactData; + } + + public void setArtifactData(String artifactData) { + this.artifactData = artifactData; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java new file mode 100644 index 0000000000..0d6a5f3b3c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java @@ -0,0 +1,90 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedAuthenticationAudit { + + private String url; + private String realm; + private String user; + private String action; + private String authStatus; + + public ExpectedAuthenticationAudit(String url, String user, String action, String authStatus) { + super(); + this.url = url; + this.user = user; + this.action = action; + this.authStatus = authStatus; + this.realm = "ASDC"; + } + + public ExpectedAuthenticationAudit() { + + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRealm() { + return realm; + } + + public void setRealm(String realm) { + this.realm = realm; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getAuthStatus() { + return authStatus; + } + + public void setAuthStatus(String authStatus) { + this.authStatus = authStatus; + } + + @Override + public String toString() { + return "ExpectedAuthenticationAudit [url=" + url + ", realm=" + realm + ", user=" + user + ", action=" + action + + ", authStatus=" + authStatus + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java new file mode 100644 index 0000000000..b11f7f585a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java @@ -0,0 +1,151 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedCategoryAudit { + String action; + String modifier; + String modifierUid; + String modifierName; + String categoryName; + String subCategoryName; + String groupingName; + String resourceType; + String status; + String desc; + String details; + + public ExpectedCategoryAudit(String action, String modifier, String categoryName, String subCategoryName, + String groupingName, String resourceType, String status, String desc) { + super(); + this.action = action; + this.modifier = modifier; + this.categoryName = categoryName; + this.subCategoryName = subCategoryName; + this.groupingName = groupingName; + this.resourceType = resourceType; + this.status = status; + this.desc = desc; + } + + public ExpectedCategoryAudit() { + action = null; + modifier = null; + categoryName = null; + subCategoryName = null; + groupingName = null; + resourceType = null; + status = null; + desc = null; + details = null; + modifierName = null; + modifierUid = null; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + public String getSubCategoryName() { + return subCategoryName; + } + + public void setSubCategoryName(String subCategoryName) { + this.subCategoryName = subCategoryName; + } + + public String getGroupingName() { + return groupingName; + } + + public void setGroupingName(String groupingName) { + this.groupingName = groupingName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getDetails() { + return details; + } + + public void setDetails(String details) { + this.details = details; + } + + public String getModifierUid() { + return modifierUid; + } + + public void setModifierUid(String modifierUid) { + this.modifierUid = modifierUid; + } + + public String getModifierName() { + return modifierName; + } + + public void setModifierName(String modifierName) { + this.modifierName = modifierName; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java new file mode 100644 index 0000000000..4b135f66f6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java @@ -0,0 +1,79 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedDistDownloadAudit { + + String action; + String consumerId; + String resourceUrl; + String status; + String desc; + + public ExpectedDistDownloadAudit(String action, String consumerId, String resourceUrl, String status, String desc) { + super(); + this.action = action; + this.consumerId = consumerId; + this.resourceUrl = resourceUrl; + this.status = status; + this.desc = desc; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public String getResourceUrl() { + return resourceUrl; + } + + public void setResourceUrl(String resourceUrl) { + this.resourceUrl = resourceUrl; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java new file mode 100644 index 0000000000..1414742423 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java @@ -0,0 +1,88 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedEcomConsumerAudit { + + String action; + String modifier; + String ecomUser; + String status; + String desc; + + public ExpectedEcomConsumerAudit(String action, String modifier, String ecomUser, String status, String desc) { + super(); + this.action = action; + this.modifier = modifier; + this.ecomUser = ecomUser; + this.status = status; + this.desc = desc; + } + + public ExpectedEcomConsumerAudit() { + action = null; + modifier = null; + ecomUser = null; + status = null; + desc = null; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getEcomUser() { + return ecomUser; + } + + public void setEcomUser(String ecomUser) { + this.ecomUser = ecomUser; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java new file mode 100644 index 0000000000..e689a3921b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java @@ -0,0 +1,179 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedExternalAudit { + + String ACTION; + String CONSUMER_ID; + String RESOURCE_URL; + String STATUS; + String DESC; + String RESOURCE_NAME; + String RESOURCE_TYPE; + String SERVICE_INSTANCE_ID;// resource/ service UUID + String MODIFIER; + String PREV_ARTIFACT_UUID; + String CURR_ARTIFACT_UUID; + String ARTIFACT_DATA; + + public ExpectedExternalAudit() { + super(); + // TODO Auto-generated constructor stub + } + + public String getRESOURCE_NAME() { + return RESOURCE_NAME; + } + + public void setRESOURCE_NAME(String rESOURCE_NAME) { + RESOURCE_NAME = rESOURCE_NAME; + } + + public String getRESOURCE_TYPE() { + return RESOURCE_TYPE; + } + + public void setRESOURCE_TYPE(String rESOURCE_TYPE) { + RESOURCE_TYPE = rESOURCE_TYPE; + } + + public String getSERVICE_INSTANCE_ID() { + return SERVICE_INSTANCE_ID; + } + + public void setSERVICE_INSTANCE_ID(String sERVICE_INSTANCE_ID) { + SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID; + } + + public ExpectedExternalAudit(String aCTION, String cONSUMER_ID, String rESOURCE_URL, String sTATUS, String dESC, + String rESOURCE_NAME, String rESOURCE_TYPE, String sERVICE_INSTANCE_ID) { + super(); + ACTION = aCTION; + CONSUMER_ID = cONSUMER_ID; + RESOURCE_URL = rESOURCE_URL; + STATUS = sTATUS; + DESC = dESC; + RESOURCE_NAME = rESOURCE_NAME; + RESOURCE_TYPE = rESOURCE_TYPE; + SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID; + } + + public ExpectedExternalAudit(String aCTION, String cONSUMER_ID, String rESOURCE_URL, String sTATUS, String dESC) { + super(); + ACTION = aCTION; + CONSUMER_ID = cONSUMER_ID; + RESOURCE_URL = rESOURCE_URL; + STATUS = sTATUS; + DESC = dESC; + } + + public ExpectedExternalAudit(String aCTION, String cONSUMER_ID, String rESOURCE_URL, String sTATUS, String dESC, + String rESOURCE_NAME, String rESOURCE_TYPE, String sERVICE_INSTANCE_ID, String mODIFIER, + String pREV_ARTIFACT_UUID, String cURR_ARTIFACT_UUID, String aRTIFACT_DATA) { + super(); + ACTION = aCTION; + CONSUMER_ID = cONSUMER_ID; + RESOURCE_URL = rESOURCE_URL; + STATUS = sTATUS; + DESC = dESC; + RESOURCE_NAME = rESOURCE_NAME; + RESOURCE_TYPE = rESOURCE_TYPE; + SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID; + MODIFIER = mODIFIER; + PREV_ARTIFACT_UUID = pREV_ARTIFACT_UUID; + CURR_ARTIFACT_UUID = cURR_ARTIFACT_UUID; + ARTIFACT_DATA = aRTIFACT_DATA; + } + + public String getACTION() { + return ACTION; + } + + public void setACTION(String aCTION) { + ACTION = aCTION; + } + + public String getCONSUMER_ID() { + return CONSUMER_ID; + } + + public void setCONSUMER_ID(String cONSUMER_ID) { + CONSUMER_ID = cONSUMER_ID; + } + + public String getRESOURCE_URL() { + return RESOURCE_URL; + } + + public void setRESOURCE_URL(String rESOURCE_URL) { + RESOURCE_URL = rESOURCE_URL; + } + + public String getSTATUS() { + return STATUS; + } + + public void setSTATUS(String sTATUS) { + STATUS = sTATUS; + } + + public String getDESC() { + return DESC; + } + + public void setDESC(String dESC) { + DESC = dESC; + } + + public String getMODIFIER() { + return MODIFIER; + } + + public void setMODIFIER(String mODIFIER) { + MODIFIER = mODIFIER; + } + + public String getPREV_ARTIFACT_UUID() { + return PREV_ARTIFACT_UUID; + } + + public void setPREV_ARTIFACT_UUID(String pREV_ARTIFACT_UUID) { + PREV_ARTIFACT_UUID = pREV_ARTIFACT_UUID; + } + + public String getCURR_ARTIFACT_UUID() { + return CURR_ARTIFACT_UUID; + } + + public void setCURR_ARTIFACT_UUID(String cURR_ARTIFACT_UUID) { + CURR_ARTIFACT_UUID = cURR_ARTIFACT_UUID; + } + + public String getARTIFACT_DATA() { + return ARTIFACT_DATA; + } + + public void setARTIFACT_DATA(String aRTIFACT_DATA) { + ARTIFACT_DATA = aRTIFACT_DATA; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java new file mode 100644 index 0000000000..561b92a317 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java @@ -0,0 +1,88 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedGetUserListAudit { + + String action; + String modifier; + String status; + String desc; + String details; + + public ExpectedGetUserListAudit(String action, String modifier, String status, String desc, String details) { + super(); + this.action = action; + this.modifier = modifier; + this.status = status; + this.desc = desc; + this.details = details; + } + + public ExpectedGetUserListAudit() { + action = null; + modifier = null; + details = null; + status = null; + desc = null; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getDetails() { + return details; + } + + public void setDetails(String details) { + this.details = details; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java new file mode 100644 index 0000000000..b481cb77af --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java @@ -0,0 +1,121 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedGroupingAudit { + String action; + String modifier; + String categoryName; + String subCategoryName; + String groupingName; + String resourceType; + String status; + String desc; + + public ExpectedGroupingAudit(String action, String modifier, String categoryName, String subCategoryName, + String groupingName, String resourceType, String status, String desc) { + super(); + this.action = action; + this.modifier = modifier; + this.categoryName = categoryName; + this.subCategoryName = subCategoryName; + this.groupingName = groupingName; + this.resourceType = resourceType; + this.status = status; + this.desc = desc; + } + + public ExpectedGroupingAudit() { + action = null; + modifier = null; + categoryName = null; + subCategoryName = null; + groupingName = null; + resourceType = null; + status = null; + desc = null; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + public String getSubCategoryName() { + return subCategoryName; + } + + public void setSubCategoryName(String subCategoryName) { + this.subCategoryName = subCategoryName; + } + + public String getGroupingName() { + return groupingName; + } + + public void setGroupingName(String groupingName) { + this.groupingName = groupingName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java new file mode 100644 index 0000000000..40b86fa528 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java @@ -0,0 +1,142 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedProductAudit { + + String ACTION; + String MODIFIER; + String STATUS; + String DESC; + String RESOURCE_NAME; + String RESOURCE_TYPE; + String PREV_VERSION; + String CURR_VERSION; + String PREV_STATE; + String CURR_STATE; + String TIMESTAMP; + String SERVICE_INSTANCE_ID; + String COMMENT; + + public String getCOMMENT() { + return COMMENT; + } + + public void setCOMMENT(String cOMMENT) { + COMMENT = cOMMENT; + } + + public String getSERVICE_INSTANCE_ID() { + return SERVICE_INSTANCE_ID; + } + + public void setSERVICE_INSTANCE_ID(String sERVICE_INSTANCE_ID) { + SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID; + } + + public String getACTION() { + return ACTION; + } + + public void setACTION(String aCTION) { + ACTION = aCTION; + } + + public String getMODIFIER() { + return MODIFIER; + } + + public void setMODIFIER(String mODIFIER) { + MODIFIER = mODIFIER; + } + + public String getSTATUS() { + return STATUS; + } + + public void setSTATUS(String sTATUS) { + STATUS = sTATUS; + } + + public String getDESC() { + return DESC; + } + + public void setDESC(String dESC) { + DESC = dESC; + } + + public String getRESOURCE_NAME() { + return RESOURCE_NAME; + } + + public void setRESOURCE_NAME(String rESOURCE_NAME) { + RESOURCE_NAME = rESOURCE_NAME; + } + + public String getRESOURCE_TYPE() { + return RESOURCE_TYPE; + } + + public void setRESOURCE_TYPE(String rESOURCE_TYPE) { + RESOURCE_TYPE = rESOURCE_TYPE; + } + + public String getPREV_VERSION() { + return PREV_VERSION; + } + + public void setPREV_VERSION(String pREV_VERSION) { + PREV_VERSION = pREV_VERSION; + } + + public String getCURR_VERSION() { + return CURR_VERSION; + } + + public void setCURR_VERSION(String cURR_VERSION) { + CURR_VERSION = cURR_VERSION; + } + + public String getPREV_STATE() { + return PREV_STATE; + } + + public void setPREV_STATE(String pREV_STATE) { + PREV_STATE = pREV_STATE; + } + + public String getCURR_STATE() { + return CURR_STATE; + } + + public void setCURR_STATE(String cURR_STATE) { + CURR_STATE = cURR_STATE; + } + + public String getTIMESTAMP() { + return TIMESTAMP; + } + + public void setTIMESTAMP(String tIMESTAMP) { + TIMESTAMP = tIMESTAMP; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java new file mode 100644 index 0000000000..7fdc899317 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java @@ -0,0 +1,311 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedResourceAuditJavaObject { + + String ACTION; + String MODIFIER_NAME; + String MODIFIER_UID; + String STATUS; + String DESC; + String RESOURCE_NAME; + String RESOURCE_TYPE; + String PREV_VERSION; + String CURR_VERSION; + String PREV_STATE; + String CURR_STATE; + String TIMESTAMP; + String ARTIFACT_DATA; + String DPREV_STATUS; + String DCURR_STATUS; + String COMMENT; + String DID; + String TOPIC_NAME; + String TOSCA_NODE_TYPE; + String CURR_ARTIFACT_UUID; + String PREV_ARTIFACT_UUID; + String ARTIFACT_TIMEOUT; + String MODIFIER; + String SERVICE_INSTANCE_ID; + String CONSUMER_ID; + String RESOURCE_URL; + + // TODO: Remove comment +// String INVARIANT_UUID; +// +// public String getINVARIANT_UUID() { +// return INVARIANT_UUID; +// } +// +// public void setINVARIANT_UUID(String invariant_uuid) { +// INVARIANT_UUID = invariant_uuid; +// } + + public String getCONSUMER_ID() { + return CONSUMER_ID; + } + + public void setCONSUMER_ID(String consumer_id) { + CONSUMER_ID = consumer_id; + } + + public String getRESOURCE_URL() { + return RESOURCE_URL; + } + + public void setRESOURCE_URL(String resource_url) { + RESOURCE_URL = resource_url; + } + + public String getSERVICE_INSTANCE_ID() { + return SERVICE_INSTANCE_ID; + } + + public void setSERVICE_INSTANCE_ID(String sERVICE_INSTANCE_ID) { + SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID; + } + + public String getMODIFIER() { + return MODIFIER; + } + + public void setMODIFIER(String mODIFIER) { + MODIFIER = mODIFIER; + } + + public String getArtifactTimeout() { + return ARTIFACT_TIMEOUT; + } + + public void setArtifactTimeout(String artifactTimeout) { + this.ARTIFACT_TIMEOUT = artifactTimeout; + } + + public String getCurrArtifactUuid() { + return CURR_ARTIFACT_UUID; + } + + public void setCurrArtifactUuid(String currArtifactUuid) { + this.CURR_ARTIFACT_UUID = currArtifactUuid; + } + + public String getPrevArtifactUuid() { + return PREV_ARTIFACT_UUID; + } + + public void setPrevArtifactUuid(String prevArtifactUuid) { + this.PREV_ARTIFACT_UUID = prevArtifactUuid; + } + + public String getToscaNodeType() { + return TOSCA_NODE_TYPE; + } + + public void setToscaNodeType(String ToscaNodeType) { + this.TOSCA_NODE_TYPE = ToscaNodeType; + } + + public String getTopicName() { + return TOPIC_NAME; + } + + public void setTopicName(String topicName) { + this.TOPIC_NAME = topicName; + } + + public String getDistributionId() { + return DID; + } + + public void setDistributionId(String did) { + this.DID = did; + } + + public ExpectedResourceAuditJavaObject() { + super(); + // TODO Auto-generated constructor stub + } + + public ExpectedResourceAuditJavaObject(String action, String modifierName, String modifierUid, String status, + String desc, String resourceName, String resourceType, String prevVersion, String currVersion, + String prevState, String currState, String timestamp, String toscaNodesType, String timeout, + String modifier, String serviceInstanceId) { + super(); + this.ACTION = action; + this.MODIFIER_NAME = modifierName; + this.MODIFIER_UID = modifierUid; + this.STATUS = status; + this.DESC = desc; + this.RESOURCE_NAME = resourceName; + this.RESOURCE_TYPE = resourceType; + this.PREV_VERSION = prevVersion; + this.CURR_VERSION = currVersion; + this.PREV_STATE = prevState; + this.CURR_STATE = currState; + this.TIMESTAMP = timestamp; + this.TOSCA_NODE_TYPE = toscaNodesType; + this.ARTIFACT_TIMEOUT = timeout; + this.MODIFIER = modifier; + this.SERVICE_INSTANCE_ID = serviceInstanceId; + } + + public String getAction() { + return ACTION; + } + + public void setAction(String action) { + this.ACTION = action; + } + + public String getModifierName() { + return MODIFIER_NAME; + } + + public void setModifierName(String modifierName) { + this.MODIFIER_NAME = modifierName; + } + + public String getModifierUid() { + return MODIFIER_UID; + } + + public void setModifierUid(String modifierUid) { + this.MODIFIER_UID = modifierUid; + } + + public String getStatus() { + return STATUS; + } + + public void setStatus(String status) { + this.STATUS = status; + } + + public String getDesc() { + return DESC; + } + + public void setDesc(String desc) { + this.DESC = desc; + } + + public String getResourceName() { + return RESOURCE_NAME; + } + + public void setResourceName(String resourceName) { + this.RESOURCE_NAME = resourceName; + } + + public String getResourceType() { + return RESOURCE_TYPE; + } + + public void setResourceType(String resourceType) { + this.RESOURCE_TYPE = resourceType; + } + + public String getPrevVersion() { + return PREV_VERSION; + } + + public void setPrevVersion(String prevVersion) { + this.PREV_VERSION = prevVersion; + } + + public String getCurrVersion() { + return CURR_VERSION; + } + + public void setCurrVersion(String currVersion) { + this.CURR_VERSION = currVersion; + } + + public String getPrevState() { + return PREV_STATE; + } + + public void setPrevState(String prevState) { + this.PREV_STATE = prevState; + } + + public String getCurrState() { + return CURR_STATE; + } + + public void setCurrState(String currState) { + this.CURR_STATE = currState; + } + + public String getTimestamp() { + return TIMESTAMP; + } + + public void setTimestamp(String timestamp) { + this.TIMESTAMP = timestamp; + } + + public String getArtifactData() { + return ARTIFACT_DATA; + } + + public void setArtifactData(String artifactData) { + this.ARTIFACT_DATA = artifactData; + } + + public String getDprevStatus() { + return DPREV_STATUS; + } + + public void setDprevStatus(String dprevStatus) { + this.DPREV_STATUS = dprevStatus; + } + + public String getDcurrStatus() { + return DCURR_STATUS; + } + + public void setDcurrStatus(String dcurrStatus) { + this.DCURR_STATUS = dcurrStatus; + } + + public String getComment() { + return COMMENT; + } + + public void setComment(String comment) { + this.COMMENT = comment; + } + + @Override + public String toString() { + return "ExpectedResourceAuditJavaObject [ACTION=" + ACTION + ", STATUS=" + STATUS + ", DESC=" + DESC + + ", RESOURCE_NAME=" + RESOURCE_NAME + ", RESOURCE_TYPE=" + RESOURCE_TYPE + ", PREV_VERSION=" + + PREV_VERSION + ", CURR_VERSION=" + CURR_VERSION + ", PREV_STATE=" + PREV_STATE + ", CURR_STATE=" + + CURR_STATE + ", TIMESTAMP=" + TIMESTAMP + ", ARTIFACT_DATA=" + ARTIFACT_DATA + ", DPREV_STATUS=" + + DPREV_STATUS + ", DCURR_STATUS=" + DCURR_STATUS + ", COMMENT=" + COMMENT + ", DID=" + DID + + ", TOPIC_NAME=" + TOPIC_NAME + ", TOSCA_NODE_TYPE=" + TOSCA_NODE_TYPE + ", CURR_ARTIFACT_UUID=" + + CURR_ARTIFACT_UUID + ", PREV_ARTIFACT_UUID=" + PREV_ARTIFACT_UUID + ", ARTIFACT_TIMEOUT=" + + ARTIFACT_TIMEOUT + ", MODIFIER=" + MODIFIER + ", SERVICE_INSTANCE_ID=" + SERVICE_INSTANCE_ID + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java new file mode 100644 index 0000000000..2bc8625057 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java @@ -0,0 +1,98 @@ +/*- + * ============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.ci.tests.datatypes.expected; + +public class ExpectedUserCRUDAudit { + String action; + String modifier; + String status; + String desc; + String userBefore; + String userAfter; + + public ExpectedUserCRUDAudit(String action, String modifier, String status, String desc, String userBefore, + String userAfter) { + super(); + this.action = action; + this.modifier = modifier; + this.status = status; + this.desc = desc; + this.userBefore = userBefore; + this.userAfter = userAfter; + } + + public ExpectedUserCRUDAudit() { + action = null; + modifier = null; + userBefore = null; + userAfter = null; + status = null; + desc = null; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getUserBefore() { + return userBefore; + } + + public void setUserBefore(String userBefore) { + this.userBefore = userBefore; + } + + public String getUserAfter() { + return userAfter; + } + + public void setUserAfter(String userAfter) { + this.userAfter = userAfter; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java new file mode 100644 index 0000000000..2c23b08717 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.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.ci.tests.datatypes.http; + +public class HeaderData { + String contentMd5; + String contentType; + String HttpCspUserId; + String HttpCspFirstName; + String HttpCspLastName; + String HttpCspWsType; + String HttpIvRemoteAddress; + String HttpIvUser; + + public HeaderData() { + super(); + } + + public HeaderData(String contentMd5, String contentType, String httpCspUserId, String httpCspFirstName, + String httpCspLastName, String httpCspWsType, String httpIvRemoteAddress, String httpIvUser) { + super(); + this.contentMd5 = contentMd5; + this.contentType = contentType; + HttpCspUserId = httpCspUserId; + HttpCspFirstName = httpCspFirstName; + HttpCspLastName = httpCspLastName; + HttpCspWsType = httpCspWsType; + HttpIvRemoteAddress = httpIvRemoteAddress; + HttpIvUser = httpIvUser; + } + + public String getContentMd5() { + return contentMd5; + } + + public void setContentMd5(String contentMd5) { + this.contentMd5 = contentMd5; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getHttpCspUserId() { + return HttpCspUserId; + } + + public void setHttpCspUserId(String httpCspUserId) { + HttpCspUserId = httpCspUserId; + } + + public String getHttpCspFirstName() { + return HttpCspFirstName; + } + + public void setHttpCspFirstName(String httpCspFirstName) { + HttpCspFirstName = httpCspFirstName; + } + + public String getHttpCspLastName() { + return HttpCspLastName; + } + + public void setHttpCspLastName(String httpCspLastName) { + HttpCspLastName = httpCspLastName; + } + + public String getHttpCspWsType() { + return HttpCspWsType; + } + + public void setHttpCspWsType(String httpCspWsType) { + HttpCspWsType = httpCspWsType; + } + + public String getHttpIvRemoteAddress() { + return HttpIvRemoteAddress; + } + + public void setHttpIvRemoteAddress(String httpIvRemoteAddress) { + HttpIvRemoteAddress = httpIvRemoteAddress; + } + + public String getHttpIvUser() { + return HttpIvUser; + } + + public void setHttpIvUser(String httpIvUser) { + HttpIvUser = httpIvUser; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java new file mode 100644 index 0000000000..4a2ad9ab82 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java @@ -0,0 +1,38 @@ +/*- + * ============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.ci.tests.datatypes.http; + +public enum HeaderValue { + + APPLICATION_JSON("application/json"); + + String value; + + private HeaderValue(String value) { + this.value = value; + } + + public String getValue() { + + return value; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java new file mode 100644 index 0000000000..cd3beee150 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java @@ -0,0 +1,58 @@ +/*- + * ============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.ci.tests.datatypes.http; + +public enum HttpHeaderEnum { + + Content_MD5("Content-MD5"), + USER_ID("USER_ID"), + HTTP_CSP_FIRSTNAME("HTTP_CSP_FIRSTNAME"), + HTTP_CSP_LASTNAME("HTTP_CSP_LASTNAME"), + HTTP_CSP_WSTYPE("HTTP_CSP_WSTYPE"), + HTTP_IV_REMOTE_ADDRESS("HTTP_IV_REMOTE_ADDRESS"), + HTTP_IV_USER("HTTP_IV_USER"), + HTTP_CSP_EMAIL("HTTP_CSP_EMAIL"), + CONTENT_TYPE("Content-Type"), + ACCEPT("Accept"), + X_ECOMP_REQUEST_ID_HEADER("X-ECOMP-RequestID"), + CACHE_CONTROL("Cache-Control"), + X_ECOMP_INSTANCE_ID("X-ECOMP-InstanceID"), + AUTHORIZATION("Authorization"), + CONTENT_LENGTH("Content-Length"), + CONTENT_DISPOSITION("Content-Disposition"), + HOST("Host"), + X_ECOMP_SERVICE_ID_HEADER("X-ECOMP-ServiceID"), + WWW_AUTHENTICATE("WWW-Authenticate"), + ECOMP_PASSWORD("password"), + ECOMP_USERNAME("username"); + + String value; + + private HttpHeaderEnum(String value) { + this.value = value; + } + + public String getValue() { + + return value; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java new file mode 100644 index 0000000000..c1f559a870 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java @@ -0,0 +1,889 @@ +/*- + * ============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.ci.tests.datatypes.http; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Scanner; + +import javax.net.ssl.HttpsURLConnection; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.annotation.NotThreadSafe; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class HttpRequest { + static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName()); + + public RestResponse httpSendGet(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + url = url.replaceAll("\\s", "%20"); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + // optional default is GET + con.setRequestMethod("GET"); + // add request header + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + int responseCode = con.getResponseCode(); + logger.debug("Send GET http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + String result; + + try { + + result = IOUtils.toString(con.getInputStream()); + response.append(result); + + } catch (Exception e) { + } + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e) { + } + + logger.debug("Response body: {}" ,response); + + // print result + + restResponse.setErrorCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setErrorCode(responseCode); + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + public RestResponse httpsSendGet(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); + // optional default is GET + con.setRequestMethod("GET"); + // add request header + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + int responseCode = con.getResponseCode(); + logger.debug("Send GET http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + // result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setErrorCode(responseCode); + // restResponse.setResponse(result); + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + public RestResponse httpSendByMethod(String url, String method, String body, Map headers) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod(method); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + if (body != null && !body.isEmpty() && !method.equals("DELETE")) { + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send {} http request, url: {}",method,url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + // response = null; + logger.debug("response body is null"); + } + + String result; + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + // if (response == null) { + // restResponse.setResponse(null); + // } else { + // restResponse.setResponse(response.toString()); + // } + + if (response != null) { + restResponse.setResponse(response.toString()); + } + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse sendHttpPost(String url, String body, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("POST"); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + if (body != null) { + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendPost(String url, String body, Map headers) throws IOException { + return httpSendPost(url, body, headers, "POST"); + } + + public RestResponse httpSendPut(String url, String body, Map headers) throws IOException { + return httpSendPost(url, body, headers, "PUT"); + } + + public RestResponse httpSendPost(String url, String body, Map headers, String methodType) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod(methodType); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + if (body != null) { + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendDeleteWithBody2(String url, String body, Map headers) + throws ClientProtocolException, IOException { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + RestResponse restResponse = new RestResponse(); + HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + httpDelete.addHeader(key, value); + } + } + + // add body to request + StringEntity input = new StringEntity(body, ContentType.APPLICATION_JSON); + httpDelete.setEntity(input); + + // execute request + CloseableHttpResponse response = httpclient.execute(httpDelete); + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + + return restResponse; + } + + public RestResponse httpSendDeleteWithBody(String url, String body, Map headers) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("DELETE"); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send DELETE http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}", response); + + // print result + + restResponse.setErrorCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendPostWithOutBody(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("POST"); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + // response = null; + logger.debug("response body is null"); + } + + String result; + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + // if (response == null) { + // restResponse.setResponse(null); + // } else { + // restResponse.setResponse(response.toString()); + // } + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendPostMultipart(String url, Map headers, String jsonLocation, + String zipLocation) throws IOException { + + Gson gson = new Gson(); + String gsonToSend = null; + RestResponse restResponse = new RestResponse(); + BufferedReader br = null; + // + // + // + // + // try { + // + // String sCurrentLine; + // + // br = new BufferedReader(new FileReader(jsonLocation)); + // + // while ((sCurrentLine = br.readLine()) != null) { + // System.out.println(sCurrentLine); + // } + // + // } catch (IOException e) { + // e.printStackTrace(); + // } finally { + // try { + // if (br != null)br.close(); + // gsonToSend = br.toString(); + // } catch (IOException ex) { + // ex.printStackTrace(); + // } + // } + + gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next(); + logger.debug("gsonToSend: {}",gsonToSend); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation))); + mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON)); + + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("USER_ID", "adminid"); + httpPost.setEntity(mpBuilder.build()); + + CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = client.execute(httpPost); + try { + logger.debug("----------------------------------------"); + logger.debug("response.getStatusLine(): {}",response.getStatusLine()); + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + logger.debug("Response content length: {}",resEntity.getContentLength()); + } + EntityUtils.consume(resEntity); + } finally { + + response.close(); + client.close(); + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(response.getEntity().toString()); + + return restResponse; + + } + + public RestResponse httpSendPostWithAuth(String url, String body, Map headers, String username, + String password) throws IOException { + + String userPassword = username + ":" + password; + String encoding = Base64.encodeBase64String(userPassword.getBytes()); + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("POST"); + + con.setRequestProperty("Authorization", "Basic " + encoding); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + response = null; + + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + if (response == null) { + restResponse.setResponse(null); + } else { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendDelete(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + con.setDoOutput(true); + con.setRequestMethod("DELETE"); + int responseCode = con.getResponseCode(); + logger.debug("Send DELETE http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setErrorCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setErrorCode(con.getResponseCode()); + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map headers) + throws IOException, ClientProtocolException { + CloseableHttpResponse response = null; + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + for (Entry entry : headers.entrySet()) { + httpPost.addHeader(entry.getKey(), entry.getValue()); + } + + httpPost.setEntity(requestEntity); + response = client.execute(httpPost); + HttpEntity responseEntity = response.getEntity(); + String responseBody = null; + if (responseEntity != null) { + InputStream instream = responseEntity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + } + + @NotThreadSafe + class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { + public static final String METHOD_NAME = "DELETE"; + + public String getMethod() { + return METHOD_NAME; + } + + public HttpDeleteWithBody(final String uri) { + super(); + setURI(URI.create(uri)); + } + + public HttpDeleteWithBody(final URI uri) { + super(); + setURI(uri); + } + + public HttpDeleteWithBody() { + super(); + } + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java new file mode 100644 index 0000000000..6937608d2a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java @@ -0,0 +1,53 @@ +/*- + * ============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.ci.tests.datatypes.http; + +import java.util.HashMap; +import java.util.Map; + +public class MustHeaders { + + private Map headers = new HashMap(); + + public MustHeaders(HeaderData headerData) { + + super(); + headers.put(HttpHeaderEnum.Content_MD5.getValue(), headerData.getContentMd5()); + headers.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), headerData.getContentType()); + headers.put(HttpHeaderEnum.ACCEPT.getValue(), headerData.getContentType()); + headers.put(HttpHeaderEnum.USER_ID.getValue(), headerData.getHttpCspUserId()); + headers.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), headerData.getHttpCspFirstName()); + headers.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), headerData.getHttpCspLastName()); + headers.put(HttpHeaderEnum.HTTP_CSP_WSTYPE.getValue(), headerData.getHttpCspWsType()); + headers.put(HttpHeaderEnum.HTTP_IV_REMOTE_ADDRESS.getValue(), headerData.getHttpIvRemoteAddress()); + headers.put(HttpHeaderEnum.HTTP_IV_USER.getValue(), headerData.getHttpIvUser()); + + } + + public MustHeaders() { + super(); + } + + public Map getMap() { + return headers; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java new file mode 100644 index 0000000000..f11d35a646 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes.http; + +import java.util.List; +import java.util.Map; + +public class RestResponse { + + Integer errorCode; + String response; + Map> headerFields; + String responseMessage; + + public RestResponse() { + super(); + } + + public RestResponse(Integer errorCode, String response, Map> headerFields, + String responseMessage) { + super(); + this.errorCode = errorCode; + this.response = response; + this.headerFields = headerFields; + this.responseMessage = responseMessage; + } + + public Integer getErrorCode() { + return errorCode; + } + + public void setErrorCode(Integer errorCode) { + this.errorCode = errorCode; + } + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public Map> getHeaderFields() { + return headerFields; + } + + public void setHeaderFields(Map> headerFields) { + this.headerFields = headerFields; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + @Override + public String toString() { + return "RestResponse [errorCode=" + errorCode + ", response=" + response + ", headerFields=" + headerFields + + ", responseMessage=" + responseMessage + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java new file mode 100644 index 0000000000..71e75c9a1e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java @@ -0,0 +1,135 @@ +/*- + * ============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.ci.tests.execute.TODO; + +import org.testng.annotations.AfterClass; +import org.testng.annotations.Test; +import org.testng.AssertJUnit; +import java.io.File; +import java.io.IOException; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.DbUtils.TitanState; + +import fj.data.Either; + +public class ImportCapabilityTypeCITest { + public static final DbUtils DbUtils = new DbUtils(); + + @AfterClass + public static void afterClass() { + DbUtils.shutDowntitan(); + } + + static Config config = Config.instance(); + + // private final String IMPORT_CAPABILITY_TYPES_PATH = + // "src/test/resources/CI/importResourceTests/import_capabilitiesTypes/"; + + @Test + public void testAddingCapabilityTypes() throws IOException { + TitanState originalState = DbUtils.getCurrentTitanState(); + + String importResourceDir = config.getImportResourceConfigDir(); + + String capabilityTypes = importResourceDir + File.separator + "capabilityTypesCi.zip"; + // importCapabilityType("src/test/resources/CI/importResource/capabilityTypesCi.zip"); + importCapabilityType(capabilityTypes); + Either eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.Test.Ci"); + AssertJUnit.assertTrue(eitherVertex.isLeft()); + DbUtils.restoreToTitanState(originalState); + eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.Test.Ci"); + AssertJUnit.assertTrue(eitherVertex.isRight()); + } + + @Test + public void AddingCapabilityNotFound() throws IOException { + TitanState originalState = DbUtils.getCurrentTitanState(); + String importResourceTestsDir = config.getImportResourceTestsConfigDir(); + String capabilitiesTests = importResourceTestsDir + File.separator + "capabilityTypesCi.zip"; + importCapabilityType(capabilitiesTests); + Either eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.NonExsitingCapability"); + AssertJUnit.assertTrue(eitherVertex.isRight()); + DbUtils.restoreToTitanState(originalState); + } + + public static Integer importAllCapabilityTypes() throws IOException { + + String importResourceDir = config.getImportResourceConfigDir() + File.separator + "capabilityTypes.zip"; + // return + // importCapabilityType("src/test/resources/CI/importResource/capabilityTypes.zip"); + return importCapabilityType(importResourceDir); + } + + private static Integer importCapabilityType(String filePath) throws IOException { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("capabilityTypeZip", new FileBody(new File(filePath))); + + String url = String.format(Urls.IMPORT_CAPABILITY_TYPE, config.getCatalogBeHost(), config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("USER_ID", "jh0003"); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + return response.getStatusLine().getStatusCode(); + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + System.out.println("failed to close client or response: " + e.getMessage()); + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + System.out.println("failed to close client or response: " + e.getMessage()); + } + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java new file mode 100644 index 0000000000..7e363202bb --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java @@ -0,0 +1,658 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpResponseException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.codehaus.jackson.map.ObjectMapper; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactUiDownloadData; +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.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.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.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.general.FileUtils; +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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +import fj.data.Either; + +public class ArtifactServletTest extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(ArtifactServletTest.class.getName()); + protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K"; + protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk"; + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + protected Gson gson = new Gson(); + protected JSONParser jsonParser = new JSONParser(); + protected String serviceVersion; + protected Resource resourceDetailsVFCcomp; + protected Service defaultService1; + + protected User sdncUserDetails; + + @Rule + public static TestName name = new TestName(); + + public ArtifactServletTest() { + super(name, ArtifactServletTest.class.getName()); + + } + + @BeforeMethod + public void create() throws Exception { + + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + Either resourceDetailsVFCcompE = AtomicOperationUtils + .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE, + ResourceCategoryEnum.APPLICATION_L4_APP_SERVER, UserRoleEnum.DESIGNER, true); + resourceDetailsVFCcomp = resourceDetailsVFCcompE.left().value(); + Either defaultService1e = AtomicOperationUtils + .createDefaultService(UserRoleEnum.DESIGNER, true); + defaultService1 = defaultService1e.left().value(); + } + + @Test + public void upadteArtifactWithPayLoadToResourcseTest() throws Exception { + + ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact(); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + int status = response.getErrorCode(); + AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200, + status); + + defaultArtifact.setDescription("kjglkh"); + defaultArtifact.setArtifactName("install_apache.sh"); + defaultArtifact.setArtifactType("SHELL"); + defaultArtifact.setPayload("new payload"); + + response = ArtifactRestUtils.updateInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + status = response.getErrorCode(); + AssertJUnit.assertEquals("failed to update artifact metatdata: " + response.getErrorCode(), 200, status); + + response = ArtifactRestUtils.deleteInformationalArtifactFromResource(resourceDetailsVFCcomp.getUniqueId(), + defaultArtifact, sdncUserDetails); + status = response.getErrorCode(); + AssertJUnit.assertEquals("failed to remove artifact: " + response.getErrorCode(), 200, status); + + } + + @Test + public void createAndUpdateArtifactToInterface() throws Exception { + + CloseableHttpResponse response; + int status; + CloseableHttpClient httpclient = HttpClients.createDefault(); + + try { + // upload artifact to interface + String interfaceName = "Standard"; + String operationName = "configure"; + + String userBodyJson = createUploadArtifactBodyJson(); + String url = String.format(Urls.UPLOAD_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName); + + HttpPost httpPost = createPostAddArtifactRequeast(userBodyJson, url, true); + response = httpclient.execute(httpPost); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200); + + // get artifact uniqueId + String artifactId = getLifecycleArtifactUid(response); + + Map jsonBody = new HashMap(); + jsonBody.put("artifactName", "TLV_prv.ppk"); + jsonBody.put("artifactDisplayName", "configure"); + jsonBody.put("artifactType", "SHELL"); + jsonBody.put("mandatory", "false"); + String newDescription = "new something"; + jsonBody.put("description", newDescription); + jsonBody.put("artifactLabel", "configure"); + userBodyJson = gson.toJson(jsonBody); + + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName, + artifactId); + + httpPost = createPostAddArtifactRequeast(userBodyJson, url, false); + + response = httpclient.execute(httpPost); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, 200, status); + + url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceDetailsVFCcomp.getUniqueId()); + HttpGet httpGet = createGetRequest(url); + response = httpclient.execute(httpGet); + AssertJUnit.assertTrue(response.getStatusLine().getStatusCode() == 200); + String responseString = new BasicResponseHandler().handleResponse(response); + + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + responseMap = (JSONObject) responseMap.get("interfaces"); + responseMap = (JSONObject) responseMap.get(interfaceName.toLowerCase()); + responseMap = (JSONObject) responseMap.get("operations"); + responseMap = (JSONObject) responseMap.get(operationName.toLowerCase()); + responseMap = (JSONObject) responseMap.get("implementation"); + String description = (String) responseMap.get("description"); + + AssertJUnit.assertEquals("the new description value was not set", newDescription, description); + + // delete artifact + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName, + artifactId); + HttpDelete httpDelete = createDeleteArtifactRequest(url); + + response = httpclient.execute(httpDelete); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200); + } finally { + httpclient.close(); + } + + } + + protected String createUploadArtifactBodyJson() { + Map jsonBody = new HashMap(); + jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME); + jsonBody.put("artifactDisplayName", "configure"); + jsonBody.put("artifactType", "SHELL"); + jsonBody.put("mandatory", "false"); + jsonBody.put("description", "ff"); + jsonBody.put("payloadData", UPLOAD_ARTIFACT_PAYLOAD); + jsonBody.put("artifactLabel", "configure"); + return gson.toJson(jsonBody); + } + + protected ArtifactDefinition getArtifactDataFromJson(String json) { + Gson gson = new Gson(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact = gson.fromJson(json, ArtifactDefinition.class); + + /* + * atifact.setArtifactName(UPLOAD_ARTIFACT_NAME); + * artifact.setArtifactDisplayName("configure"); + * artifact.setArtifactType("SHELL"); artifact.setMandatory(false); + * artifact.setDescription("ff"); + * artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD); + * artifact.setArtifactLabel("configure"); + */ + return artifact; + } + + protected HttpGet createGetRequest(String url) { + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + httpGet.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + return httpGet; + } + + protected String getArtifactUid(HttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + String artifactId = (String) responseMap.get("uniqueId"); + return artifactId; + } + + protected String getArtifactEsId(HttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + String esId = (String) responseMap.get("EsId"); + return esId; + } + + protected ArtifactDefinition addArtifactDataFromResponse(HttpResponse response, ArtifactDefinition artifact) + throws HttpResponseException, IOException, ParseException { + // String responseString = new + // BasicResponseHandler().handleResponse(response); + HttpEntity entity = response.getEntity(); + String responseString = EntityUtils.toString(entity); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + artifact.setEsId((String) responseMap.get("esId")); + artifact.setUniqueId((String) responseMap.get("uniqueId")); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType((String) responseMap.get("artifactGroupType"))); + artifact.setTimeout(((Long) responseMap.get("timeout")).intValue()); + return artifact; + } + + protected String getLifecycleArtifactUid(CloseableHttpResponse response) + throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + responseMap = (JSONObject) responseMap.get("implementation"); + String artifactId = (String) responseMap.get("uniqueId"); + return artifactId; + } + + protected HttpDelete createDeleteArtifactRequest(String url) { + HttpDelete httpDelete = new HttpDelete(url); + httpDelete.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + httpDelete.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + return httpDelete; + } + + protected HttpPost createPostAddArtifactRequeast(String jsonBody, String url, boolean addMd5Header) + throws UnsupportedEncodingException { + HttpPost httppost = new HttpPost(url); + httppost.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (addMd5Header) { + httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody)); + } + StringEntity input = new StringEntity(jsonBody); + input.setContentType("application/json"); + httppost.setEntity(input); + log.debug("Executing request {}", httppost.getRequestLine()); + return httppost; + } + + protected String createLoadArtifactBody() { + Map json = new HashMap(); + json.put("artifactName", "install_apache2.sh"); + json.put("artifactType", "SHELL"); + json.put("description", "ddd"); + json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz"); + json.put("artifactLabel", "name123"); + + String jsonStr = gson.toJson(json); + return jsonStr; + } + + protected void checkDeleteResponse(RestResponse response) { + BaseRestUtils.checkStatusCode(response, "delete request failed", false, 204, 404); + } + + protected ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + try { + ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, + ArtifactUiDownloadData.class); + return artifactUiDownloadData; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + // TODO + // @Ignore("") + @Test + public void addArtifactNoPayLoadToResourcseTest() throws Exception { + ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact(); + defaultArtifact.setPayload(null); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + int status = response.getErrorCode(); + AssertJUnit.assertTrue(status == 400); + + } + + @Test + public void upadteArtifactNoPayLoadToResourcseTest() throws Exception { + + ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact(); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + int status = response.getErrorCode(); + AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200, + status); + + defaultArtifact.setDescription("kjglkh"); + defaultArtifact.setArtifactName("install_apache.sh"); + defaultArtifact.setArtifactType("SHELL"); + defaultArtifact.setPayload(null); + + response = ArtifactRestUtils.updateInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + status = response.getErrorCode(); + AssertJUnit.assertEquals("failed to update artifact metatdata: " + response.getErrorCode(), 200, status); + + response = ArtifactRestUtils.deleteInformationalArtifactFromResource(resourceDetailsVFCcomp.getUniqueId(), + defaultArtifact, sdncUserDetails); + status = response.getErrorCode(); + AssertJUnit.assertEquals("failed to remove artifact: " + response.getErrorCode(), 200, status); + + } + + // TODO + @Test(enabled = false) + public void updateDeploymentArtifactToResourcseTest() throws Exception { + + ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultDeploymentArtifactForType("HEAT"); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + int status = response.getErrorCode(); + AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200, + status); + + response = ArtifactRestUtils.updateInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + status = response.getErrorCode(); + AssertJUnit.assertEquals("failed to update artifact metatdata: " + response.getErrorCode(), 200, status); + + response = ArtifactRestUtils.deleteInformationalArtifactFromResource(resourceDetailsVFCcomp.getUniqueId(), + defaultArtifact, sdncUserDetails); + status = response.getErrorCode(); + AssertJUnit.assertEquals("failed to remove artifact: " + response.getErrorCode(), 200, status); + + } + + // -------------------- + @Test + public void addArtifactToResourcse_AlreadyExistsTest() throws Exception { + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + String jsonBody = createLoadArtifactBody(); + + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId()); + HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true); + CloseableHttpResponse response = httpclient.execute(httppost); + int status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertTrue("failed to add artifact", status == 200); + + String artifactId = getArtifactUid(response); + + httppost = createPostAddArtifactRequeast(jsonBody, url, true); + response = httpclient.execute(httppost); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("the returned status code is in correct", status, 400); + + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), artifactId); + HttpDelete httpDelete = createDeleteArtifactRequest(url); + response = httpclient.execute(httpDelete); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertTrue("failed to remove artifact", status == 200); + } finally { + httpclient.close(); + } + + } + + @Test + public void addArtifactToResourcse_MissingContentTest() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + Map json = new HashMap(); + json.put("description", "desc"); + json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz"); + json.put("Content-MD5", "YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); + + String jsonBody = gson.toJson(json); + + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId()); + HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true); + CloseableHttpResponse response = httpclient.execute(httppost); + int status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("the returned status code is in correct", status, 400); + } finally { + httpclient.close(); + } + + } + + @Test + public void addArtifactToResourcse_MissingMd5Test() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + HashMap json = new HashMap(); + json.put("artifactName", "install_apache.sh"); + json.put("artifactType", "SHELL"); + json.put("description", "kjglkh"); + json.put("payloadData", "UEsDBYTEIWUYIFHWFMABCNAoAAAAIAAeLb0bDQz"); + json.put("artifactLabel", "name123"); + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId()); + String jsonBody = gson.toJson(json); + HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, false); + CloseableHttpResponse response = httpclient.execute(httppost); + int status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertTrue("failed to update artifact metatdata", status == 400); + } finally { + httpclient.close(); + } + + } + + @Test + public void deleteArtifact_NotExistsTest() throws Exception { + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), "someFakeId"); + HttpDelete httpDelete = createDeleteArtifactRequest(url); + CloseableHttpResponse response = httpclient.execute(httpDelete); + int status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("the returned status code is in correct", status, 404); + } finally { + httpclient.close(); + } + + } + + @Test + public void createAndRemoveArtifactToInterface() throws Exception { + CloseableHttpResponse response; + int status; + CloseableHttpClient httpclient = HttpClients.createDefault(); + + try { + // upload artifact to interface + String interfaceName = "Standard"; + String operationName = "configure"; + + String userBodyJson = createUploadArtifactBodyJson(); + String url = String.format(Urls.UPLOAD_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName); + + HttpPost httpPost = createPostAddArtifactRequeast(userBodyJson, url, true); + response = httpclient.execute(httpPost); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200); + + // get artifact uniqueId + String artifactId = getLifecycleArtifactUid(response); + + // delete artifact + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName, + artifactId); + HttpDelete httpDelete = createDeleteArtifactRequest(url); + + response = httpclient.execute(httpDelete); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200); + } finally { + httpclient.close(); + } + + } + + @Test + public void addArtifactToServiceTest() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + + try { + String jsonStr = createLoadArtifactBody(); + + String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), + config.getCatalogBePort(), defaultService1.getUniqueId()); + HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true); + CloseableHttpResponse result = httpclient.execute(httpPost); + int status = result.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, 200, status); + + String artifactId = getArtifactUid(result); + + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), + config.getCatalogBePort(), defaultService1.getUniqueId(), artifactId); + HttpDelete httpDelete = createDeleteArtifactRequest(url); + + result = httpclient.execute(httpDelete); + status = result.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 200, returned :" + status, 200, status); + } finally { + RestResponse response = ServiceRestUtils.deleteService(defaultService1.getName(), serviceVersion, + sdncUserDetails); + checkDeleteResponse(response); + httpclient.close(); + } + } + + @Test + public void addArtifactNotSupportedTypeToServiceTest() throws Exception { + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + Map json = new HashMap(); + json.put("artifactName", "install_apache.sh"); + json.put("artifactType", "SHELL11"); + json.put("description", "fff"); + json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz"); + json.put("artifactLabel", "name123"); + + String jsonStr = gson.toJson(json); + + String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), + config.getCatalogBePort(), defaultService1.getUniqueId()); + + HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true); + CloseableHttpResponse result = httpclient.execute(httpPost); + int status = result.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("response code is not 400, returned :" + status, 400, status); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name()); + + String responseString = EntityUtils.toString(result.getEntity()); + + JSONObject map = (JSONObject) jsonParser.parse(responseString); + JSONObject requestError = (JSONObject) map.get("requestError"); + JSONObject serviceException = (JSONObject) requestError.get("serviceException"); + + String msgId = (String) serviceException.get("messageId"); + AssertJUnit.assertEquals("message id did not match expacted", errorInfo.getMessageId(), msgId); + + String text = (String) serviceException.get("text"); + AssertJUnit.assertEquals("text did not match expacted", errorInfo.getMessage(), text); + + JSONArray variables = (JSONArray) serviceException.get("variables"); + String type = (String) variables.get(0); + AssertJUnit.assertEquals("variable did not match expacted", "SHELL11", type); + } finally { + RestResponse response = ServiceRestUtils.deleteService(defaultService1.getName(), serviceVersion, + sdncUserDetails); + checkDeleteResponse(response); + httpclient.close(); + } + + } + + @Test + public void addArtifactToResourceTest() throws Exception { + + ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact(); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, + resourceDetailsVFCcomp.getUniqueId()); + int status = response.getErrorCode(); + AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200, + status); + + RestResponse resourceResp = ResourceRestUtils.getResource(resourceDetailsVFCcomp.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse()); + AssertJUnit.assertNotNull(resource); + + Map artifacts = resource.getArtifacts(); + boolean isExist = false; + for (Map.Entry entry : artifacts.entrySet()) { + if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) { + isExist = true; + + } + } + AssertJUnit.assertTrue(isExist); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java new file mode 100644 index 0000000000..ff99a6bb10 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java @@ -0,0 +1,1799 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +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.ArtifactReqDetails; +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.ErrorInfo; +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; +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.general.FileUtils; +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.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.openecomp.sdc.ci.tests.utils.validation.ArtifactValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class CrudArt extends ComponentBaseTest { + + private static Logger logger = LoggerFactory.getLogger(CrudArt.class.getName()); + private static final User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + private static final String HEAT_NET_LABEL = "heatnet"; + private static final String HEAT_LABEL = "heat"; + + protected String testResourcesPath; + protected String testResourcesInstancesPath; + + protected static final String dcaeInventoryToscaFile = "toscaSampleArtifact.yml"; + protected static final String dcaeInventoryJsonFile = "jsonSampleArtifact.json"; + protected static final String dcaeInventoryPolicyFile = "emfSampleArtifact.emf"; + protected static final String dcaeInventoryDocFile = "docSampleArtifact.doc"; + protected static final String dcaeInventoryBlueprintFile = "bluePrintSampleArtifact.xml"; + protected static final String dcaeInventoryEventFile = "eventSampleArtifact.xml"; + + protected static final String heatSuccessFile = "asc_heat 0 2.yaml"; + protected static final String heatNetSuccessFile = "asc_heat_net 0 2.yaml"; + protected static final String yangFile = "addYangXmlArtifactToResource.xml"; + protected static final String jsonFile = "jsonArtifact.json"; + protected static final String invalidJsonFile = "invalidJson.json"; + protected static final String invalidYangFile = "invalidYangXml.xml"; + protected static final String otherFile = "other.txt"; + protected static final String muranoFile = "asc_heat 0 2.zip"; + protected static final String heatSuccessMiniFile = "heat_mini.yaml"; + protected static final String heatInvalidFormat = "heatInvalidFormat.yaml"; + protected static final String yamlInvalidFormat = "invalidYamlFormat.yaml"; + protected static final String heatEnvfile = "heatEnvfile.env"; + + protected ServiceReqDetails serviceDetails; + protected ResourceReqDetails vfResourceDetails; + protected ResourceReqDetails cpResourceDetails; + protected ResourceReqDetails vfcResourceDetails; + protected ResourceReqDetails vlResourceDetails; + + @Rule + public static TestName name = new TestName(); + + public CrudArt() { + super(name, CrudArt.class.getName()); + } + + @DataProvider + private static final Object[][] getDepArtByType() throws IOException, Exception { + return new Object[][] { { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_VOL.getType()) }, + { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()) }, + { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType()) }, + { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType()) }, + { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType()) } }; + } + + @DataProvider + private static final Object[][] getServiceDepArtByType() throws IOException, Exception { + return new Object[][] { { ArtifactTypeEnum.OTHER.getType() }, { ArtifactTypeEnum.YANG_XML.getType() }, }; + } + + @BeforeMethod + public void init() throws Exception { + // Set files working directory + String sourceDir = config.getResourceConfigDir(); + String workDir = "HeatDeploymentArtifacts"; + testResourcesPath = sourceDir + File.separator + workDir; + String workDirResourceInstanceArtifacts = "ResourceInstanceArtifacts"; + testResourcesInstancesPath = sourceDir + File.separator + workDirResourceInstanceArtifacts; + + // Build the components + Service serviceObj = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + serviceDetails = new ServiceReqDetails(serviceObj); + + Resource vfcResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + vfcResourceDetails = new ResourceReqDetails(vfcResourceObj); + + Resource vfResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + vfResourceDetails = new ResourceReqDetails(vfResourceObj); + + Resource cpResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true).left().value(); + cpResourceDetails = new ResourceReqDetails(cpResourceObj); + + Resource vlResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true).left().value(); + vlResourceDetails = new ResourceReqDetails(vlResourceObj); + } + + // ---------------------------------Resource + // success-------------------------------- + @Test + public void addHeatArtifactToResourceAndCertify() throws Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // certified resource + RestResponse changeResourceState = LifecycleRestUtils.certifyResource(vfResourceDetails); + int status = changeResourceState.getErrorCode(); + assertEquals("certify resource request returned status:" + status, BaseRestUtils.STATUS_CODE_SUCCESS, status); + + Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(changeResourceState.getResponse()); + Map artifactsMap = resourceJavaObject.getDeploymentArtifacts(); + boolean flag = false; + if (artifactsMap != null) { + for (Entry art : artifactsMap.entrySet()) { + if (art.getValue().getArtifactName().equals(heatArtifactDetails.getArtifactName())) { + assertTrue("expected artifact type is " + ArtifactGroupTypeEnum.DEPLOYMENT.getType() + " but was " + art.getValue().getArtifactGroupType(), art.getValue().getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT)); + flag = true; + break; + } + } + assertTrue("expected artifact not found", flag == true); + } + + } + + // ---------------------------------Resource + // success-------------------------------- + @Test + public void addDcaeInventoryToscaArtifactToResourceInstanceAndCertify() throws Exception { + String artifactFileName = dcaeInventoryToscaFile; + String artifactName = dcaeInventoryToscaFile; + String artifactLabel = "dcae inv tosca label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_TOSCA; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addDcaeInventoryJsonArtifactToResourceInstanceAndCertify() throws Exception { + String artifactFileName = dcaeInventoryJsonFile; + String artifactName = dcaeInventoryJsonFile; + String artifactLabel = "dcae inv json label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_JSON; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addDcaeInventoryPolicyArtifactToResourceInstanceAndCertify() throws Exception { + String artifactFileName = dcaeInventoryPolicyFile; + String artifactName = dcaeInventoryPolicyFile; + String artifactLabel = "dcae inv policy label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_POLICY; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addDcaeInventoryDocArtifactToResourceInstanceAndCertify() throws Exception { + String artifactFileName = dcaeInventoryDocFile; + String artifactName = dcaeInventoryDocFile; + String artifactLabel = "dcae inv doc label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_DOC; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addDcaeInventoryBluePrintArtifactToResourceInstanceAndCertify() throws Exception { + String artifactFileName = dcaeInventoryBlueprintFile; + String artifactName = dcaeInventoryBlueprintFile; + String artifactLabel = "dcae inv blueprint label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addDcaeInventoryEventArtifactToResourceInstanceAndCertify() throws Exception { + String artifactFileName = dcaeInventoryEventFile; + String artifactName = dcaeInventoryEventFile; + String artifactLabel = "dcae inv event label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_EVENT; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + private RestResponse addArtifactToResourceInstanceAndCertify(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType) throws Exception { + + // Get the resource + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + + // Certify VF + Pair changeComponentState = AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Add VF instance to service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + + // Get the VF instance + getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ComponentInstance VfInstance = service.getComponentInstances().get(0); + + // Create the artifact + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstance(artifactFileName, artifactName, artifactLabel, artifactType, VfInstance, serviceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addArtifactToResourceInstanceResponse.getResponseMessage()); + return addArtifactToResourceInstanceResponse; + } + + @Test + public void updateArtifactDescriptionToResourceInstance() throws Exception { + String artifactFileName = dcaeInventoryToscaFile; + String artifactName = dcaeInventoryToscaFile; + String artifactLabel = "dcae inv tosca label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_TOSCA; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + logger.debug("addInformationalArtifactToResource response: {}" ,addArtifactToResourceInstanceResponse.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Get the artifact from VF instance and change his description. + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ComponentInstance vfInstance = service.getComponentInstances().get(0); + Map deploymentArtifacts = vfInstance.getDeploymentArtifacts(); + ArtifactDefinition artifactDefinition = deploymentArtifacts.get("dcaeinvtoscalabel"); + artifactDefinition.setDescription("My new description"); + + // Update the artifact + RestResponse updateDeploymentArtifactToRI = ArtifactRestUtils.updateArtifactToResourceInstance(artifactDefinition, sdncDesignerDetails1, vfInstance.getUniqueId(), service.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",updateDeploymentArtifactToRI.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateDeploymentArtifactToRI.getErrorCode(), updateDeploymentArtifactToRI.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void deleteArtifactToResourceInstance() throws Exception { + String artifactFileName = dcaeInventoryToscaFile; + String artifactName = dcaeInventoryToscaFile; + String artifactLabel = "dcae inv tosca label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_TOSCA; + RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType); + logger.debug("addInformationalArtifactToResource response: {}",addArtifactToResourceInstanceResponse.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Get the artifact from VF instance and change his description. + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ComponentInstance vfInstance = service.getComponentInstances().get(0); + Map deploymentArtifacts = vfInstance.getDeploymentArtifacts(); + ArtifactDefinition artifactDefinition = deploymentArtifacts.get("dcaeinvtoscalabel"); + + // Delete the artifact + RestResponse deleteInformationalArtifactFromResource = ArtifactRestUtils.deleteArtifactFromResourceInstance(artifactDefinition, sdncDesignerDetails1, vfInstance.getUniqueId(), service.getUniqueId()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + deleteInformationalArtifactFromResource.getErrorCode(), deleteInformationalArtifactFromResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addHeatArtifactToResource() throws Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + } + + @Test + public void addHeatAndHeatNetArtifactsToResource() throws Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + + // Add HEAT + logger.debug("listFileName: {}",listFileName.toString()); + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Add HEAT_NET + String payloadNet = FileUtils.loadPayloadFile(listFileName, heatNetSuccessFile, true); + ArtifactReqDetails heatNetArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType()); + heatNetArtifactDetails.setPayload(payloadNet); + heatNetArtifactDetails.setArtifactLabel(HEAT_NET_LABEL); + + RestResponse addInformationalArtifactToResource1 = ArtifactRestUtils.uploadArtifactToPlaceholderOnResource(heatNetArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId(), HEAT_NET_LABEL); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource1.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource1.getErrorCode(), addInformationalArtifactToResource1.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(vfResourceDetails, sdncDesignerDetails1); + Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(HEAT_LABEL); + assertNotNull(artifactDefinition); + String heatEsId = artifactDefinition.getEsId(); + assertNotNull(heatEsId); + + ArtifactDefinition artifactDefinitionNet = deploymentArtifacts.get(HEAT_NET_LABEL); + assertNotNull(artifactDefinitionNet); + String heatNetEsId = artifactDefinitionNet.getEsId(); + assertNotNull(heatNetEsId); + assertFalse(heatEsId.equalsIgnoreCase(heatNetEsId)); + } + + @Test + public void addDeleteAddHeatArtifactToResource() throws Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + RestResponse deleteInformationalArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource(vfResourceDetails.getUniqueId(), heatArtifactDetails, sdncDesignerDetails1); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + deleteInformationalArtifactFromResource.getErrorCode(), deleteInformationalArtifactFromResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addYangXmlArtifactToResource() throws Exception { + + String fileName = yangFile; + String artifactName = "asc_heat 0 2.XML"; + String artifactLabel = "Label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addOtherTypeDeploymentArtifactToResource() throws Exception { + + String fileName = otherFile; + String artifactName = "other.txt"; + String artifactLabel = "Label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.OTHER; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addYangXmlArtifactSameName() throws Exception { + + String fileName = yangFile; + String artifactName = "asc_heat_0_2.XML"; + String artifactLabel = "Label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // Changing label but not name + artifactLabel = "Label1"; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is not 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == 400); + BaseValidationUtils.checkErrorResponse(addInformationalArtifactToResource, ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, new String[] { "Resource", vfResourceDetails.getName(), artifactName }); + + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addInvalidYangXmlFormat() throws Exception { + + String fileName = invalidYangFile; + String artifactName = "asc_heat_0_2.XML"; + String artifactLabel = "Label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is not 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == 400); + BaseValidationUtils.checkErrorResponse(addInformationalArtifactToResource, ActionStatus.INVALID_XML, new String[] { "YANG_XML" }); + + } + + @Test + public void addSeveralYangXmlArtifacts() throws Exception { + + // Adding 4 artifacts + String fileName = yangFile; + String artifactName = "asc_heat_0_2.XML"; + String artifactLabel = "Label"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // Changing label and name + artifactLabel = "Label1"; + artifactName = "asc_heat_0_3.XML"; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Changing label and name + artifactLabel = "Label2"; + artifactName = "asc_heat_0_4.XML"; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + + // Changing label and name + artifactLabel = "Label3"; + artifactName = "asc_heat_0_5.XML"; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 4); + } + + @Test(dataProvider = "getDepArtByType") + public void updateHeatArtifactToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + heatTypeArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // update + heatTypeArtifactDetails.setArtifactName("UPDATE.yaml"); + heatTypeArtifactDetails.setPayloadData(null); + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",updateInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToResource.getErrorCode(), updateInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + } + + @Test(dataProvider = "getDepArtByType") + public void updateHeatArtifactTimeOutToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + Resource resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1); + int actualTimeout = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getTimeout(); + assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact timout, expected " + heatTypeArtifactDetails.getTimeout() + ", but was " + actualTimeout, heatTypeArtifactDetails.getTimeout() == actualTimeout); + + // update + heatTypeArtifactDetails.setTimeout(35); + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",updateInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToResource.getErrorCode(), updateInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1); + actualTimeout = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getTimeout(); + assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact timout, expected " + heatTypeArtifactDetails.getTimeout() + ", but was " + actualTimeout, heatTypeArtifactDetails.getTimeout() == actualTimeout); + } + + @Test(dataProvider = "getDepArtByType") + public void updateHeatArtifactDescriptionToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + Resource resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1); + String actualDescription = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getDescription(); + assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact Description, expected " + heatTypeArtifactDetails.getDescription() + ", but was " + actualDescription, heatTypeArtifactDetails.getDescription().equals(actualDescription)); + + // update + heatTypeArtifactDetails.setDescription("the best description was ever"); + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",updateInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToResource.getErrorCode(), updateInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1); + actualDescription = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getDescription(); + assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact Description, expected " + heatTypeArtifactDetails.getDescription() + ", but was " + actualDescription, heatTypeArtifactDetails.getDescription().equals(actualDescription)); + } + + private Resource getResourceByResDetails(ResourceReqDetails resDetails, User userDetails) throws IOException { + RestResponse response = ResourceRestUtils.getResource(resDetails, userDetails); + assertTrue("response code on get resource not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + response.getErrorCode(), response.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + return resource; + } + + // ---------------------------------Service + // success-------------------------------- + @Test() + public void addAllTypesDepArtifactToService() throws Exception, Exception { + + // String fileName = heatSuccessFile; + // List listFileName = + // FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + // logger.debug("listFileName: {}",listFileName.toString()); + + // String payload = FileUtils.loadPayloadFile(listFileName, fileName, + // true); + ArtifactReqDetails otherArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType()); + // otherArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(otherArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + ArtifactReqDetails yangXmlArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.YANG_XML.getType()); + + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(yangXmlArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + } + + @Test(enabled = false) + public void addMuranoPkgArtifactToService() throws Exception, Exception { + + String fileName = muranoFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}" ,listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MURANO_PKG.getType()); + heatArtifactDetails.setPayload(payload); + heatArtifactDetails.setArtifactName("asc_heat 0 2.zip"); + heatArtifactDetails.setArtifactLabel("Label"); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + } + + @Test(dataProvider = "getServiceDepArtByType") + public void addHeatArtifactToServiceAndCertify(String artType) throws Exception, Exception { + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // certified service + RestResponse changeServiceState = LifecycleRestUtils.certifyService(serviceDetails); + int status = changeServiceState.getErrorCode(); + assertEquals("certify service request returned status:" + status, BaseRestUtils.STATUS_CODE_SUCCESS, status); + + Service resourceJavaObject = ResponseParser.convertServiceResponseToJavaObject(changeServiceState.getResponse()); + Map artifactsMap = resourceJavaObject.getDeploymentArtifacts(); + boolean flag = false; + if (artifactsMap != null) { + for (Entry art : artifactsMap.entrySet()) { + if (art.getValue().getArtifactName().equals(heatArtifactDetails.getArtifactName())) { + assertTrue("expected artifact type is " + ArtifactGroupTypeEnum.DEPLOYMENT.getType() + " but was " + art.getValue().getArtifactGroupType(), art.getValue().getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT)); + flag = true; + break; + } + } + assertTrue("expected artifact not found", flag == true); + } + + } + + @Test(enabled = false, dataProvider = "getServiceDepArtByType") + public void updateHeatArtifactToService(String artType) throws Exception, Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // update + heatArtifactDetails.setPayloadData(payload); + RestResponse updateInformationalArtifactToService = ArtifactRestUtils.updateInformationalArtifactOfServiceByMethod(heatArtifactDetails, serviceDetails.getUniqueId(), sdncDesignerDetails1, "POST"); + logger.debug("updateInformationalArtifactToService response: {}",updateInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToService.getErrorCode(), updateInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + } + + // --------------------------------------Resource Negative + // Tests------------------------------------- + + // TODO Andrey the method of DEPLOYMENT artifact is update and not add + @Test(dataProvider = "getServiceDepArtByType") + public void addTheSameAdditionalHeatArtifactToResource(String artType) throws Exception, Exception { + + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // add the same artifact one more time + artifactDetails.setArtifactLabel("the second artifact"); + addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList("Resource", vfResourceDetails.getName(), artifactDetails.getArtifactName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource.getResponse()); + + } + + @Test + public void addHeatArtifactTwiceSameNameToResource() throws Exception, Exception { + + String filename1 = heatSuccessFile; + // String filename2 = heatSuccessMiniFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, filename1, true); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Add HEAT_NET + String payloadNet = FileUtils.loadPayloadFile(listFileName, heatNetSuccessFile, true); + ArtifactReqDetails heatNetArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType()); + heatNetArtifactDetails.setPayload(payloadNet); + heatNetArtifactDetails.setArtifactLabel(HEAT_NET_LABEL); + heatNetArtifactDetails.setArtifactName(heatArtifactDetails.getArtifactName()); + + RestResponse addInformationalArtifactToResource1 = ArtifactRestUtils.uploadArtifactToPlaceholderOnResource(heatNetArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId(), HEAT_NET_LABEL); + logger.debug("addInformationalArtifactToResource response: {}" ,addInformationalArtifactToResource1.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource1.getErrorCode()); + + List variables = Arrays.asList("Resource", vfResourceDetails.getName(), heatNetArtifactDetails.getArtifactName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource1.getResponse()); + + } + + @Test(dataProvider = "getDepArtByType") + public void addHeatArtifactTwiceToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String filename1 = heatSuccessFile; + String filename2 = heatSuccessMiniFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, filename1, true); + heatTypeArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}" ,addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // add the second artifact + payload = FileUtils.loadPayloadFile(listFileName, heatSuccessMiniFile, true); + heatTypeArtifactDetails.setPayload(payload); + heatTypeArtifactDetails.setArtifactName(filename2); + heatTypeArtifactDetails.setArtifactLabel("the second artifact"); + + addInformationalArtifactToResource = ArtifactRestUtils.explicitAddInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList("Resource", vfResourceDetails.getName(), heatTypeArtifactDetails.getArtifactType(), heatTypeArtifactDetails.getArtifactType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource.getResponse()); + + } + + @Test(dataProvider = "getDepArtByType") + public void addHeatArtifactInvalidHeatFormatToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String fileName = heatInvalidFormat; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + heatTypeArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList(heatTypeArtifactDetails.getArtifactType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name(), variables, addInformationalArtifactToResource.getResponse()); + + } + + @Test(dataProvider = "getDepArtByType") + public void addHeatArtifactInvalidYamlFormatToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String fileName = yamlInvalidFormat; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + heatTypeArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_YAML.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList(heatTypeArtifactDetails.getArtifactType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_YAML.name(), variables, addInformationalArtifactToResource.getResponse()); + + } + + @Test(dataProvider = "getDepArtByType") + public void addHeatArtifactInvalidFileExtensionToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String fileName = yangFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + + heatTypeArtifactDetails.setPayload(payload); + heatTypeArtifactDetails.setArtifactName(fileName); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList(heatTypeArtifactDetails.getArtifactType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables, addInformationalArtifactToResource.getResponse()); + + } + + @Test(dataProvider = "getDepArtByType") + public void addHeatArtifactToResourceCertifyAndAddAdditionalHeatArtifact(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + heatTypeArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // certified resource + RestResponse changeResourceState = LifecycleRestUtils.certifyResource(vfResourceDetails); + int status = changeResourceState.getErrorCode(); + assertEquals("certify resource request returned status:" + status, BaseRestUtils.STATUS_CODE_SUCCESS, status); + + // add second HEAT artifact to the certified resource + changeResourceState = LifecycleRestUtils.changeResourceState(vfResourceDetails, sdncDesignerDetails1, LifeCycleStatesEnum.CHECKOUT); + assertTrue("expected code response on change resource state to CHECKOUT BaseRestUtils.STATUS_CODE_SUCCESS, but was " + changeResourceState.getErrorCode(), changeResourceState.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // ArtifactReqDetails heatArtifactDetails1 = + // ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatTypeArtifactDetails.setPayload(payload); + heatTypeArtifactDetails.setArtifactName(fileName); + heatTypeArtifactDetails.setArtifactLabel("the second artifact"); + + addInformationalArtifactToResource = ArtifactRestUtils.explicitAddInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList("Resource", vfResourceDetails.getName(), heatTypeArtifactDetails.getArtifactType(), heatTypeArtifactDetails.getArtifactType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource.getResponse()); + + } + + // -----------------Service Negative + // Tests-------------------------------------------------------- + + // Absolute + @Test(enabled = false) + public void addHeatArtifactTwiceToService() throws Exception, Exception { + + String fileName1 = heatSuccessFile; + String fileName2 = heatSuccessMiniFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName1, true); + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // add the second artifact + payload = FileUtils.loadPayloadFile(listFileName, fileName2, true); + + ArtifactReqDetails heatArtifactDetails1 = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType()); + heatArtifactDetails1.setPayload(payload); + heatArtifactDetails1.setArtifactName(fileName2); + heatArtifactDetails1.setArtifactLabel("the second artifact"); + + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails1, sdncDesignerDetails1, serviceDetails.getUniqueId()); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode()); + + List variables = Arrays.asList("Service", serviceDetails.getName(), ArtifactTypeEnum.OTHER.getType(), ArtifactTypeEnum.OTHER.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name(), variables, addInformationalArtifactToService.getResponse()); + + } + + // TODO Andrey Obsolete + @Test(enabled = false) + public void addHeatArtifactInvalidHeatFormatToService() throws Exception, Exception { + + String fileName = heatInvalidFormat; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode()); + + List variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name(), variables, addInformationalArtifactToService.getResponse()); + + } + + // TODO Andrey Obsolete + @Test(enabled = false) + public void addHeatArtifactInvalidYamlFormatToService() throws Exception, Exception { + + String fileName = yamlInvalidFormat; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_YAML.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode()); + + List variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_YAML.name(), variables, addInformationalArtifactToService.getResponse()); + + } + + @Test + public void addHeatArtifactInvalidFileExtensionToService() throws Exception, Exception { + + String fileName = muranoFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.YANG_XML.getType()); + heatArtifactDetails.setPayload(payload); + heatArtifactDetails.setArtifactName(fileName); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + logger.debug("addInformationalArtifactToService response: {}",addInformationalArtifactToService.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode()); + + List variables = Arrays.asList(ArtifactTypeEnum.YANG_XML.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables, addInformationalArtifactToService.getResponse()); + + } + + @Test(dataProvider = "getDepArtByType") + public void addHeatEnvArtifactToResourceNotSupportedType(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception { + + String fileName = heatEnvfile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_ENV.getType()); + heatArtifactDetails.setPayload(payload); + heatArtifactDetails.setArtifactName("asc_heat 0 2.env"); + heatArtifactDetails.setArtifactLabel(heatTypeArtifactDetails.getArtifactLabel()); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode()); + + List variables = Arrays.asList(ArtifactTypeEnum.HEAT_ENV.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addInformationalArtifactToResource.getResponse()); + } + + // TODO Andrey + @Test + public void addHeatArtifactToServiceNotSupportDeploymentArt() throws Exception, Exception { + + String fileName = heatSuccessFile; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}",listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, fileName, true); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(payload); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode()); + + List variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addInformationalArtifactToService.getResponse()); + + } + + protected RestResponse addArtifactToResourceInstance(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType, ComponentInstance componentInstance, ServiceReqDetails serviceDetails) throws Exception { + ArtifactReqDetails dcaeArtifactDetails = buildArtifactReqDetailsObject(testResourcesInstancesPath, artifactFileName, artifactName, artifactLabel, artifactType); + RestResponse addArtifactToResourceInstance = ArtifactRestUtils.addArtifactToResourceInstance(dcaeArtifactDetails, sdncDesignerDetails1, componentInstance.getUniqueId(), serviceDetails.getUniqueId()); + return addArtifactToResourceInstance; + } + + protected RestResponse addDeploymentArtifactToResource(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType) throws Exception { + ArtifactReqDetails heatArtifactDetails = buildArtifactReqDetailsObject(testResourcesPath, artifactFileName, artifactName, artifactLabel, artifactType); + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId()); + return addInformationalArtifactToResource; + } + + protected RestResponse addDeploymentArtifactToResource(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType, ResourceReqDetails resource) throws Exception { + ArtifactReqDetails heatArtifactDetails = buildArtifactReqDetailsObject(testResourcesPath, artifactFileName, artifactName, artifactLabel, artifactType); + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, resource.getUniqueId()); + return addInformationalArtifactToResource; + } + + // US672293 - Support new artifact type : BEVF_LICENSE , VENDOR_LICENSE + @Test + public void addNewArtifactsToVFResource() throws Exception { + + String fileName = yangFile; + String artifactName = "artifact1.xml"; + String artifactLabel = "Label1"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response:{}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + artifactName = "artifact2.xml"; + artifactLabel = "Label2"; + artifactType = ArtifactTypeEnum.VF_LICENSE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact4.xml"; + artifactLabel = "Label4"; + artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact5.xml"; + artifactLabel = "Label5"; + artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact6.xml"; + artifactLabel = "Label6"; + artifactType = ArtifactTypeEnum.APPC_CONFIG; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + fileName = jsonFile; + artifactName = "artifact7.json"; + artifactLabel = "Label7"; + artifactType = ArtifactTypeEnum.APPC_CONFIG; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 2); + + //MIB artifacts: SNMP_POLL, SNMP_TRAP + fileName = jsonFile; + artifactName = "artifact8.json"; + artifactLabel = "Label8"; + artifactType = ArtifactTypeEnum.SNMP_POLL; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + fileName = jsonFile; + artifactName = "artifact9.json"; + artifactLabel = "Label9"; + artifactType = ArtifactTypeEnum.SNMP_TRAP; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + //MIB artifacts: SNMP_POLL, SNMP_TRAP + fileName = jsonFile; + artifactName = "artifact8.json"; + artifactLabel = "Label8"; + artifactType = ArtifactTypeEnum.SNMP_POLL; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + fileName = jsonFile; + artifactName = "artifact9.json"; + artifactLabel = "Label9"; + artifactType = ArtifactTypeEnum.SNMP_TRAP; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactsToVFCResource() throws Exception { + + String fileName = yangFile; + String artifactName = "artifact1.xml"; + String artifactLabel = "Label1"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact2.xml"; + artifactLabel = "Label2"; + artifactType = ArtifactTypeEnum.VF_LICENSE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact4.xml"; + artifactLabel = "Label4"; + artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifac5.xml"; + artifactLabel = "Label5"; + artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactsToVfc() throws Exception { + String fileName = yangFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE; + RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}",addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactsToCp() throws Exception { + String fileName = yangFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE; + RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactsToVl() throws Exception { + String fileName = yangFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE; + RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addVfInstanceWithNewArtifactsToService() throws Exception { + String fileName = yangFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE; + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + // Certify VF + Pair changeComponentState = AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // Add VF instance to service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + // get service and verify VF instance contain the Artifacts :VF_LICENSE + // and VENDOR_LICENSE + getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ComponentInstance VfInstance = service.getComponentInstances().get(0); + ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VENDOR_LICENSE, 1); + ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VF_LICENSE, 1); + } + + @Test + public void addNotSupportedArtifactsTypeToService01() throws Exception, Exception { + // Artifact type : VF_LICENSE + ArtifactReqDetails deploymentArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.VF_LICENSE.getType()); + RestResponse addDeploymentArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(deploymentArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code eturned :" + addDeploymentArtifactToService.getErrorCode(), addDeploymentArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add("VF_LICENSE"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addDeploymentArtifactToService.getResponse()); + } + + @Test + public void addNotSupportedArtifactsTypeToService02() throws Exception, Exception { + // Artifact type : VENDOR_LICENSE + ArtifactReqDetails deploymentArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.VENDOR_LICENSE.getType()); + RestResponse addDeploymentArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(deploymentArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code eturned :" + addDeploymentArtifactToService.getErrorCode(), addDeploymentArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add("VENDOR_LICENSE"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addDeploymentArtifactToService.getResponse()); + } + + @Test + public void addInvalidFileForArtifactTypeVendorLicenseToResource() throws Exception { + String fileName = yangFile; + String NonXmlFile = heatSuccessFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE; + RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + // Artifact type VENDOR_LICENSE must be XML file + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + addDeploymentArtifactToResource = addDeploymentArtifactToResource(NonXmlFile, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code 400 returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add("VENDOR_LICENSE"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_XML.name(), variables, addDeploymentArtifactToResource.getResponse()); + // get resource and verify that file not exist within + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0); + } + + @Test + public void addInvalidFileForArtifactTypeVfLicenseToResource() throws Exception { + String fileName = yangFile; + String NonXmlFile = heatSuccessFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + // Artifact type VF_LICENSE must be XML file + artifactName = "artifact3.xml"; + artifactLabel = "Label3"; + artifactType = ArtifactTypeEnum.VF_LICENSE; + addDeploymentArtifactToResource = addDeploymentArtifactToResource(NonXmlFile, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code 400 returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add("VF_LICENSE"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_XML.name(), variables, addDeploymentArtifactToResource.getResponse()); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0); + } + + @Test + public void addVendorLicenseArtifactAlreadyExistsInResource() throws Exception { + String fileName = yangFile; + String artifactName = "artifact2.xml"; + String artifactLabel = "Label2"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VENDOR_LICENSE; + RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + // Add same file again to resource + addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage()); + assertTrue("response code is not 400, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add(artifactLabel.toLowerCase()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_EXIST.name(), variables, addDeploymentArtifactToResource.getResponse()); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + // US672294 + + @Test() + public void addVnfCatalogArtifactsToService() throws Exception, Exception { + + ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.VNF_CATALOG.getType()); + RestResponse resp = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + resp.getErrorCode(), resp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // get service and verify the Artifacts :VNF_CATALOG + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VNF_CATALOG, 1); + } + + @Test() + public void addModelInventoryProfileArtifactsToService() throws Exception, Exception { + + ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()); + RestResponse resp = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + resp.getErrorCode(), resp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // get service and verify the Artifacts :VNF_CATALOG + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, 1); + } + + @Test() + public void addModelQuerySpecArtifactsToService() throws Exception, Exception { + + ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()); + RestResponse resp = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + resp.getErrorCode(), resp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // get service and verify the Artifacts :VNF_CATALOG + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1); + } + + @Test + public void addVfInstanceWithNewArtifactsToService02() throws Exception { + + String fileName = yangFile; + String artifactName = "artifact1.xml"; + String artifactLabel = "Label1"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG; + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + fileName = yangFile; + artifactName = "artifact2.xml"; + artifactLabel = "Label2"; + artifactType = ArtifactTypeEnum.APPC_CONFIG; + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact4.xml"; + artifactLabel = "Label4"; + artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifac5.xml"; + artifactLabel = "Label5"; + artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + // Certify VF + Pair changeComponentState = AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Add VF instance to service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + + // get service and verify VF instance contain the Artifacts :VF_LICENSE + // and VENDOR_LICENSE + getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ComponentInstance VfInstance = service.getComponentInstances().get(0); + ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VNF_CATALOG, 1); + ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, 1); + ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1); + ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.APPC_CONFIG, 1); + } + + @Test + public void addAppcConfigArtifactToVfc() throws Exception { + String fileName = jsonFile; + String artifactName = "artifact7.json"; + String artifactLabel = "Label7"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG; + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add(artifactName); + variables.add("[VF]"); + variables.add("VFC (Virtual Function Component)"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE.name(), variables, addInformationalArtifactToResource.getResponse()); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0); + } + + @Test + public void addAppcConfigArtifactToCp() throws Exception { + String fileName = jsonFile; + String artifactName = "artifact7.json"; + String artifactLabel = "Label7"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG; + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add(artifactName); + variables.add("[VF]"); + variables.add("CP (Connection Point)"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE.name(), variables, addInformationalArtifactToResource.getResponse()); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0); + } + + @Test + public void addAppcConfigArtifactToVl() throws Exception { + String fileName = jsonFile; + String artifactName = "artifact7.json"; + String artifactLabel = "Label7"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG; + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add(artifactName); + variables.add("[VF]"); + variables.add("VL (Virtual Link)"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE.name(), variables, addInformationalArtifactToResource.getResponse()); + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0); + } + + @Test() + public void addAppcConfigArtifactsToService() throws Exception, Exception { + ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.APPC_CONFIG.getType()); + RestResponse addDeploymentArtifactToResource = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code 400, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add(ArtifactTypeEnum.APPC_CONFIG.toString()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addDeploymentArtifactToResource.getResponse()); + } + + @Test + public void addAppcConfigInvalidJsonToVFResourceFailed() throws Exception { + + String fileName = invalidJsonFile; + String artifactName = "invalidJson.json"; + String artifactLabel = "Label7"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + + ArrayList variables = new ArrayList<>(); + variables.add(ArtifactTypeEnum.APPC_CONFIG.toString()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_JSON.name(), variables, addInformationalArtifactToResource.getResponse()); + + RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0); + + } + + @Test + public void addNewArtifactsToCp02() throws Exception { + + String fileName = yangFile; + String artifactName = "artifact1.xml"; + String artifactLabel = "Label1"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact4.xml"; + artifactLabel = "Label4"; + artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifac5.xml"; + artifactLabel = "Label5"; + artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactsToVl02() throws Exception { + + String fileName = yangFile; + String artifactName = "artifact1.xml"; + String artifactLabel = "Label1"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact4.xml"; + artifactLabel = "Label4"; + artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifac5.xml"; + artifactLabel = "Label5"; + artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactsToVfc02() throws Exception { + + String fileName = yangFile; + String artifactName = "artifact1.xml"; + String artifactLabel = "Label1"; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG; + + RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifact4.xml"; + artifactLabel = "Label4"; + artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + + artifactName = "artifac5.xml"; + artifactLabel = "Label5"; + artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC; + + addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails); + logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1); + } + + @Test + public void addNewArtifactAlreadyExistsInService() throws Exception { + ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()); + RestResponse addDeploymentArtifactoService = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactoService.getErrorCode(), addDeploymentArtifactoService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + // get service and verify the Artifacts :VNF_CATALOG + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1); + // Add same file again to resource + addDeploymentArtifactoService = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId()); + assertTrue("response code is 400, returned :" + addDeploymentArtifactoService.getErrorCode(), addDeploymentArtifactoService.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + ArrayList variables = new ArrayList<>(); + variables.add(artDetails.getArtifactLabel().toLowerCase()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_EXIST.name(), variables, addDeploymentArtifactoService.getResponse()); + // get service and verify the Artifacts :VNF_CATALOG is still exist and + // has one occurrences + getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1); + } + + private ArtifactReqDetails buildArtifactReqDetailsObject(String filesPath, String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType) throws IOException, Exception { + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filesPath); + logger.debug("listFileName: {}", listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, artifactFileName, true); + + ArtifactReqDetails dcaeArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artifactType.getType()); + dcaeArtifactDetails.setPayload(payload); + dcaeArtifactDetails.setArtifactName(artifactName); + dcaeArtifactDetails.setArtifactLabel(artifactLabel); + return dcaeArtifactDetails; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java new file mode 100644 index 0000000000..bb2b662009 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java @@ -0,0 +1,665 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpResponseException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.codehaus.jackson.map.ObjectMapper; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactUiDownloadData; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.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.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedResourceAuditJavaObject; +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.Decoder; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +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.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.testng.internal.Yaml; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.typesafe.config.ConfigException.Null; + +import fj.data.Either; +import fj.data.List; + +public class DownloadComponentArt extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(DownloadComponentArt.class.getName()); + protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K"; + protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk"; + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + + + protected Gson gson = new Gson(); + protected JSONParser jsonParser = new JSONParser(); + + + protected String serviceVersion; + protected ResourceReqDetails resourceDetails; + protected User sdncUserDetails; + protected ServiceReqDetails serviceDetails; + + + @BeforeMethod + public void init() throws Exception{ + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + Resource resourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + Service serviceObj = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + + resourceDetails = new ResourceReqDetails(resourceObj); + serviceDetails = new ServiceReqDetails(serviceObj); + } + + @Rule + public static TestName name = new TestName(); + + public DownloadComponentArt() { + super(name, DownloadComponentArt.class.getName()); + + } + + + + // External API - Download artifact for resource + @Test + public void downloadArtifactFromResourceViaExternalAPI() throws Exception { + Resource resourceDetailsVF; + Either createdResource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetailsVF = createdResource.left().value(); + ArtifactDefinition heatArtifact = AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF, UserRoleEnum.DESIGNER, true, true).left().value(); + resourceDetails = new ResourceReqDetails(resourceDetailsVF); + + String resourceUUID = resourceDetailsVF.getUUID(); + String artifactUUID = heatArtifact.getArtifactUUID(); + + System.out.println("Resource UUID: " + resourceUUID); + System.out.println("Artifact UUID: " + artifactUUID); + + RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Resource"); + + Integer responseCode = restResponse.getErrorCode(); + Integer expectedCode = 200; + Assert.assertEquals(responseCode,expectedCode, "Response code is not correct."); + + String response = restResponse.getResponse(); + + String payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9"; + String decodedPaypload = Decoder.decode(payloadData); + + Assert.assertEquals(response, decodedPaypload, "Response deployment artifact not correct."); + + String auditAction = "DownloadArtifact"; + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName()); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + + expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); + 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); + } + + + // External API - Download artifact for resource - negative test + @Test + public void downloadArtifactFromResourceViaExternalAPINegativeTest() throws Exception { + Resource resourceDetailsVF; + Either createdResource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetailsVF = createdResource.left().value(); + ArtifactDefinition heatArtifact = AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF, UserRoleEnum.DESIGNER, true, true).left().value(); + resourceDetails = new ResourceReqDetails(resourceDetailsVF); + + String resourceUUID = resourceDetailsVF.getUUID(); + String artifactUUID = heatArtifact.getArtifactUUID(); + + System.out.println("Resource UUID: " + resourceUUID); + System.out.println("Artifact UUID: " + artifactUUID); + + RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, "dfsgfdsg324", ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Resource"); + + Integer responseCode = restResponse.getErrorCode(); + Integer expectedCode = 200; + Assert.assertEquals(responseCode,expectedCode, "Response code is not correct."); + } + + + + + + // External API - Download artifact for service - negative test + @Test + public void downloadArtifactFromServiceViaExternalAPI() throws Exception { + + Service resourceDetailsService; + Either createdResource = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetailsService = createdResource.left().value(); + + ArtifactDefinition heatArtifact = AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsService, UserRoleEnum.DESIGNER, true, true).left().value(); + + String resourceUUID = resourceDetailsService.getUUID(); + String artifactUUID = heatArtifact.getArtifactUUID(); + + System.out.println("Resource UUID: " + resourceUUID); + System.out.println("Artifact UUID: " + artifactUUID); + + RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Service"); + + Integer responseCode = restResponse.getErrorCode(); + Integer expectedCode = 200; + Assert.assertEquals(responseCode,expectedCode, "Response code is not correct."); + + String response = restResponse.getResponse(); + + String payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9"; + String decodedPaypload = Decoder.decode(payloadData); + + Assert.assertEquals(response, decodedPaypload, "Response deployment artifact not correct."); + + String auditAction = "DownloadArtifact"; + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setResourceName(resourceDetailsService.getName()); + expectedResourceAuditJavaObject.setResourceType("Service"); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + + expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); + 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); + } + + + + + + + // External API - Download ComponentInstance artifact of service - negative test + @Test + public void downloadArtifactOfComponentInstanceFromServiceViaExternalAPI() throws Exception { + + Either resourceDetailsVF_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + Component resourceDetailsVF_01 = resourceDetailsVF_01e.left().value(); + ArtifactDefinition heatArtifact = AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true).left().value(); + + resourceDetailsVF_01 = AtomicOperationUtils.changeComponentState(resourceDetailsVF_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + Service resourceDetailsService; + Either createdResource = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetailsService = createdResource.left().value(); + + + ComponentInstance resourceDetailsVF1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVF_01, resourceDetailsService, UserRoleEnum.DESIGNER, true).left().value(); + + + System.out.println("-----"); + + + String resourceUUID = resourceDetailsService.getUUID(); + String componentNormalizedName = resourceDetailsVF1ins_01.getNormalizedName(); + String artifactUUID = heatArtifact.getArtifactUUID(); + + System.out.println("Resource UUID: " + resourceUUID); + System.out.println("Component NormalizedName: " + componentNormalizedName); + System.out.println("Artifact UUID: " + artifactUUID); + + RestResponse restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceUUID, componentNormalizedName, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Service"); +// + Integer responseCode = restResponse.getErrorCode(); + Integer expectedCode = 200; + Assert.assertEquals(responseCode,expectedCode, "Response code is not correct."); + + String response = restResponse.getResponse(); + + String payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9"; + String decodedPaypload = Decoder.decode(payloadData); + + Assert.assertEquals(response, decodedPaypload, "Response deployment artifact not correct."); + + String auditAction = "DownloadArtifact"; + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setResourceName(resourceDetailsVF1ins_01.getName()); + expectedResourceAuditJavaObject.setResourceType("Service"); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + + expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); + 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); + } + + + + + + + + + + @Test + public void downloadArtifactFromResourceTest() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + String jsonBody = createUploadArtifactBodyJson(); + + String resourceId = resourceDetails.getUniqueId(); + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true); + HttpResponse response = httpclient.execute(httppost); + int status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("failed to add artifact", 200, status); + + ArtifactDefinition origArtifact = getArtifactDataFromJson(jsonBody); + addArtifactDataFromResponse(response, origArtifact); + String artifactId = origArtifact.getUniqueId(); + + url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, artifactId); + HttpGet httpGet = createGetRequest(url); + response = httpclient.execute(httpGet); + status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("failed to download artifact", 200, status); + + InputStream inputStream = response.getEntity().getContent(); + ArtifactUiDownloadData artifactUiDownloadData = getArtifactUiDownloadData(IOUtils.toString(inputStream)); + AssertJUnit.assertEquals("Downloaded payload is different from uploaded one", UPLOAD_ARTIFACT_PAYLOAD, artifactUiDownloadData.getBase64Contents()); + AssertJUnit.assertEquals("Downloaded artifact name is different from uploaded one", UPLOAD_ARTIFACT_NAME, artifactUiDownloadData.getArtifactName()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails); + String auditAction = "ArtifactDownload"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setArtifactData(AuditValidationUtils.buildArtifactDataAudit(origArtifact)); + expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId()); + expectedResourceAuditJavaObject.setPrevArtifactUuid(""); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } finally { + httpclient.close(); + } + + } + + @Test + public void downloadArtifactFromServiceTest() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + + try { + + String jsonStr = createUploadArtifactBodyJson(); + + String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceDetails.getUniqueId()); + HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true); + CloseableHttpResponse result = httpclient.execute(httpPost); + int status = result.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("failed to add artifact", 200, status); + + ArtifactDefinition origArtifact = getArtifactDataFromJson(jsonStr); + addArtifactDataFromResponse(result, origArtifact); + String artifactId = origArtifact.getUniqueId(); + + url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceDetails.getUniqueId(), artifactId); + HttpGet httpGet = createGetRequest(url); + CloseableHttpResponse response2 = httpclient.execute(httpGet); + status = response2.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("failed to download artifact", 200, status); + InputStream inputStream = response2.getEntity().getContent(); + ArtifactUiDownloadData artifactUiDownloadData = getArtifactUiDownloadData(IOUtils.toString(inputStream)); + AssertJUnit.assertEquals("Downloaded payload is different from uploaded one", UPLOAD_ARTIFACT_PAYLOAD, artifactUiDownloadData.getBase64Contents()); + AssertJUnit.assertEquals("Downloaded artifact name is different from uploaded one", UPLOAD_ARTIFACT_NAME, artifactUiDownloadData.getArtifactName()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = AuditValidationUtils.constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails); + String auditAction = "ArtifactDownload"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setArtifactData(AuditValidationUtils.buildArtifactDataAudit(origArtifact)); + expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId()); + expectedResourceAuditJavaObject.setPrevArtifactUuid(""); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } finally { +// RestResponse response = ServiceRestUtils.deleteService(serviceDetails, serviceVersion, sdncUserDetails ); +// checkDeleteResponse(response); + httpclient.close(); + } + } + + @Test + public void downloadArtifactFromResourceNotFound() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + + String resourceId = resourceDetails.getUniqueId(); + String artifactIdNotFound = "11111"; + + ArtifactDefinition origArtifact = new ArtifactDefinition(); + origArtifact.setUniqueId(artifactIdNotFound); + + String url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, artifactIdNotFound); + HttpGet httpGet = createGetRequest(url); + CloseableHttpResponse response = httpclient.execute(httpGet); + int status = response.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("expected 404 not found", 404, status); + + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails); + String auditAction = "ArtifactDownload"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("")); + expectedResourceAuditJavaObject.setArtifactData(""); + expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId()); + expectedResourceAuditJavaObject.setPrevArtifactUuid(""); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + expectedResourceAuditJavaObject.setPrevArtifactUuid(null); + } finally { + httpclient.close(); + } + + } + + @Test + public void downloadArtifactFromServiceNotFound() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + + String artifactIdNotFound = "11111"; + ArtifactDefinition origArtifact = new ArtifactDefinition(); + origArtifact.setUniqueId(artifactIdNotFound); + + String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceDetails.getUniqueId(), artifactIdNotFound); + HttpGet httpGet = createGetRequest(url); + CloseableHttpResponse response2 = httpclient.execute(httpGet); + int status = response2.getStatusLine().getStatusCode(); + AssertJUnit.assertEquals("expected 404 not found", 404, status); + + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails); + String auditAction = "ArtifactDownload"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("")); + expectedResourceAuditJavaObject.setArtifactData(""); + expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId()); + expectedResourceAuditJavaObject.setPrevArtifactUuid(""); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } finally { + httpclient.close(); + } + + } + + @Test + public void addArtifactToResourceTest() throws Exception { + + ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact(); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails, resourceDetails.getUniqueId()); + int status = response.getErrorCode(); + AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200, status); + + RestResponse resourceResp = ResourceRestUtils.getResource(resourceDetails.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse()); + AssertJUnit.assertNotNull(resource); + + Map artifacts = resource.getArtifacts(); + boolean isExist = false; + for (Map.Entry entry : artifacts.entrySet()) { + if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) { + isExist = true; + + } + } + AssertJUnit.assertTrue(isExist); + } + + + protected String createUploadArtifactBodyJson() { + Map jsonBody = new HashMap(); + jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME); + jsonBody.put("artifactDisplayName", "configure"); + jsonBody.put("artifactType", "SHELL"); + jsonBody.put("mandatory", "false"); + jsonBody.put("description", "ff"); + jsonBody.put("payloadData", UPLOAD_ARTIFACT_PAYLOAD); + jsonBody.put("artifactLabel", "configure"); + return gson.toJson(jsonBody); + } + + protected ArtifactDefinition getArtifactDataFromJson(String json) { + Gson gson = new Gson(); + JsonObject jsonElement = new JsonObject(); + jsonElement = gson.fromJson(json, jsonElement.getClass()); + ArtifactDefinition artifact = new ArtifactDefinition(); + String payload = null; + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + artifact = gson.fromJson(jsonElement, ArtifactDefinition.class); + artifact.setPayloadData(payload); + + /*atifact.setArtifactName(UPLOAD_ARTIFACT_NAME); +artifact.setArtifactDisplayName("configure"); +artifact.setArtifactType("SHELL"); +artifact.setMandatory(false); +artifact.setDescription("ff"); +artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD); +artifact.setArtifactLabel("configure");*/ + return artifact; + } + + protected HttpGet createGetRequest(String url) { + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + httpGet.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + return httpGet; + } + + protected String getArtifactUid(HttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + String artifactId = (String) responseMap.get("uniqueId"); + return artifactId; + } + + protected String getArtifactEsId(HttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + String esId = (String) responseMap.get("EsId"); + return esId; + } + + protected ArtifactDefinition addArtifactDataFromResponse(HttpResponse response, ArtifactDefinition artifact) throws HttpResponseException, IOException, ParseException { + //String responseString = new BasicResponseHandler().handleResponse(response); + HttpEntity entity = response.getEntity(); + String responseString = EntityUtils.toString(entity); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + artifact.setEsId((String)responseMap.get("esId")); + artifact.setUniqueId((String) responseMap.get("uniqueId")); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType((String) responseMap.get("artifactGroupType"))); + artifact.setTimeout(((Long) responseMap.get("timeout")).intValue()); + return artifact; + } + + protected String getLifecycleArtifactUid(CloseableHttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + responseMap = (JSONObject) responseMap.get("implementation"); + String artifactId = (String) responseMap.get("uniqueId"); + return artifactId; + } + + protected HttpDelete createDeleteArtifactRequest(String url) { + HttpDelete httpDelete = new HttpDelete(url); + httpDelete.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + httpDelete.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + return httpDelete; + } + + protected HttpPost createPostAddArtifactRequeast(String jsonBody, String url, boolean addMd5Header) throws UnsupportedEncodingException { + HttpPost httppost = new HttpPost(url); + httppost.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (addMd5Header) { + httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody)); + } + StringEntity input = new StringEntity(jsonBody); + input.setContentType("application/json"); + httppost.setEntity(input); + log.debug("Executing request {}" , httppost.getRequestLine()); + return httppost; + } + + protected String createLoadArtifactBody() { + Map json = new HashMap(); + json.put("artifactName", "install_apache2.sh"); + json.put("artifactType", "SHELL"); + json.put("description", "ddd"); + json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz"); + json.put("artifactLabel", "name123"); + + String jsonStr = gson.toJson(json); + return jsonStr; + } + + protected void checkDeleteResponse(RestResponse response) { + BaseRestUtils.checkStatusCode(response, "delete request failed", false, 204, 404); + } + + protected ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + try { + ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, ArtifactUiDownloadData.class); + return artifactUiDownloadData; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java new file mode 100644 index 0000000000..e50d5b4ef9 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java @@ -0,0 +1,192 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactUiDownloadData; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +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.ComponentInstanceReqDetails; +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.ServiceCategoriesEnum; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +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.annotations.Test; +import org.yaml.snakeyaml.Yaml; + +public class HeatEnvArtifact extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public HeatEnvArtifact() { + super(name, HeatEnvArtifact.class.getName()); + } + + @Test(enabled = true) + public void heatEnvOnResourceFormatTest() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csarHeatEnv.csar"); + assertNotNull(createdResource); + + RestResponse certifyState = LifecycleRestUtils.changeComponentState(createdResource, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + BaseRestUtils.checkSuccess(certifyState); + + Resource certifiedResource = ResponseParser.parseToObjectUsingMapper(certifyState.getResponse(), Resource.class); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId()); + + // 2 create service + RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails); + ResourceRestUtils.checkCreateResponse(createServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class); + + // 3 create vf instance in service + ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(certifiedResource); + RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service); + ResourceRestUtils.checkCreateResponse(createComponentInstance); + + RestResponse getService = ServiceRestUtils.getService(service.getUniqueId()); + BaseRestUtils.checkSuccess(getService); + service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class); + + List componentInstances = service.getComponentInstances(); + assertNotNull(componentInstances); + assertEquals(1, componentInstances.size()); + + ComponentInstance vfi = componentInstances.get(0); + Map deploymentArtifacts = vfi.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertEquals(4, deploymentArtifacts.size()); + ArtifactDefinition heatEnv = deploymentArtifacts.get("heat0env"); + assertNotNull(heatEnv); + + Map yaml = downloadComponentInstanceYamlFile(service.getUniqueId(), vfi.getUniqueId(), sdncModifierDetails, heatEnv.getUniqueId()); + assertNotNull(yaml); + Map paramters = (Map)yaml.get("parameters"); + assertNotNull(paramters); + assertEquals(8, paramters.size()); + assertEquals(null, paramters.get("param8")); + List heatParameters = heatEnv.getHeatParameters(); + heatParameters.forEach(p -> { + assertEquals(p.getCurrentValue(), paramters.get(p.getName())); + }); + } + @Test(enabled = true) + public void noHeatEnvOnResourceFormatTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csarHeatNoEnv.csar"); + assertNotNull(createdResource); + + RestResponse certifyState = LifecycleRestUtils.changeComponentState(createdResource, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + BaseRestUtils.checkSuccess(certifyState); + + Resource certifiedResource = ResponseParser.parseToObjectUsingMapper(certifyState.getResponse(), Resource.class); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId()); + + // 2 create service + RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails); + ResourceRestUtils.checkCreateResponse(createServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class); + + // 3 create vf instance in service + ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(certifiedResource); + RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service); + ResourceRestUtils.checkCreateResponse(createComponentInstance); + + RestResponse getService = ServiceRestUtils.getService(service.getUniqueId()); + BaseRestUtils.checkSuccess(getService); + service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class); + + List componentInstances = service.getComponentInstances(); + assertNotNull(componentInstances); + assertEquals(1, componentInstances.size()); + + ComponentInstance vfi = componentInstances.get(0); + Map deploymentArtifacts = vfi.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertEquals(4, deploymentArtifacts.size()); + ArtifactDefinition heatEnv = deploymentArtifacts.get("heat0env"); + assertNotNull(heatEnv); + + Map yaml = downloadComponentInstanceYamlFile(service.getUniqueId(), vfi.getUniqueId(), sdncModifierDetails, heatEnv.getUniqueId()); + assertNotNull(yaml); + Map paramters = (Map)yaml.get("parameters"); + assertNotNull(paramters); + assertEquals(8, paramters.size()); + assertEquals(null, paramters.get("param1")); + assertEquals(null, paramters.get("param2")); + assertEquals(null, paramters.get("param4")); + assertEquals(null, paramters.get("param5")); + assertEquals(null, paramters.get("param7")); + assertEquals(null, paramters.get("param8")); + List heatParameters = heatEnv.getHeatParameters(); + heatParameters.forEach(p -> { + assertEquals(p.getCurrentValue(), paramters.get(p.getName())); + }); + + } + //**************************************** + private Map downloadComponentInstanceYamlFile(String serviceUniqueId, String resourceInstanceId, User user, String artifactUniqeId) throws Exception { + RestResponse heatEnvDownloadResponse = ArtifactRestUtils.downloadResourceInstanceArtifact(serviceUniqueId, resourceInstanceId, user, artifactUniqeId); + BaseRestUtils.checkSuccess(heatEnvDownloadResponse); + + ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(heatEnvDownloadResponse.getResponse(), ArtifactUiDownloadData.class); + byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes(); + byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload); + Yaml yaml = new Yaml(); + + InputStream inputStream = new ByteArrayInputStream(decodeBase64); + + Map load = (Map) yaml.load(inputStream); + + return load; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java new file mode 100644 index 0000000000..0718fb6e5c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java @@ -0,0 +1,704 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +//import static org.junit.Assert.assertTrue; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.javatuples.Pair; +import org.junit.Rule; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.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.general.FileUtils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.ErrorValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.datastax.driver.core.Row; + +import fj.data.Either; + +public class PlaceHolderValidations extends ComponentBaseTest { + private static Logger logger = LoggerFactory.getLogger(PlaceHolderValidations.class.getName()); + private static final String heatExtension = "yaml"; + // private static final String yangXmlExtension = "xml"; + // private static final String muranoPkgExtension = "zip"; + private final String folderName = "addHeatArtifactToServiceAndSertify"; + private Resource resource; + private final int timeOut = 60; + private ArtifactReqDetails updateArtifactReqDetails = null; + protected User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + protected User sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2); + protected ResourceReqDetails resourceDetails1; + protected ResourceReqDetails resourceVF; + protected ResourceReqDetails resourceCP; + protected ResourceReqDetails resourceVL; + + protected ArtifactReqDetails heatArtifactDetails; + protected ArtifactReqDetails heatVolArtifactDetails; + protected ArtifactReqDetails heatNetArtifactDetails; + + public PlaceHolderValidations() { + super(name, PlaceHolderValidations.class.getName()); + } + + @Rule + public static TestName name = new TestName(); + + @BeforeMethod + public void init() throws IOException, Exception { + + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatNetArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType()); + heatVolArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_VOL.getType()); + Resource resourceObject = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetails1 = new ResourceReqDetails(resourceObject); + resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true) + .left().value(); + resourceVF = new ResourceReqDetails(resourceObject); + resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true) + .left().value(); + resourceCP = new ResourceReqDetails(resourceObject); + resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true) + .left().value(); + resourceVL = new ResourceReqDetails(resourceObject); + } + + @Test + public void validateDeploymentPlaceHoldersByConfig() throws IOException { + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1); + Resource resourceObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceObject.getDeploymentArtifacts(); + assertNotNull("deploymentArtifacts list is null", deploymentArtifacts); + List listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true); + assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig); + for (String resDepArtType : listOfResDepArtTypesFromConfig) { + assertNotNull("placeholder of " + resDepArtType + " type doesn't exist", + deploymentArtifacts.get(resDepArtType)); + } + } + + private void validateToscaArtifactsBeforeAndAfterSFT(ResourceReqDetails resourceDetails) + throws IOException, Exception { + RestResponse componentResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails1); + Component component = ResponseParser.convertResourceResponseToJavaObject(componentResponse.getResponse()); + Map toscaArtifacts = component.getToscaArtifacts(); + for (ArtifactDefinition artifact : toscaArtifacts.values()) { + assertNull(artifact.getEsId()); + } + + componentResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails1, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + component = ResponseParser.convertResourceResponseToJavaObject(componentResponse.getResponse()); + toscaArtifacts = component.getToscaArtifacts(); + + for (ArtifactDefinition artifact : toscaArtifacts.values()) { + assertEquals(artifact.getEsId(), artifact.getUniqueId()); + List> fields = new ArrayList(); + fields.add(new Pair("id", artifact.getEsId())); + List fetchFromTable = CassandraUtils.fetchFromTableQuery("sdcartifact", "resources", fields); + assertTrue(1 == fetchFromTable.size()); + } + } + + @Test + public void validateToscaArtifactsBeforeAndAfterSFT() throws IOException, Exception { + // TODO ADD VF and Service + validateToscaArtifactsBeforeAndAfterSFT(resourceDetails1); + validateToscaArtifactsBeforeAndAfterSFT(resourceCP); + validateToscaArtifactsBeforeAndAfterSFT(resourceVL); + } + + @Test + public void validateToscaPlaceHoldersByConfig() throws IOException, Exception { + List components = new ArrayList<>(); + RestResponse componentGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1); + components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse())); + + componentGetResponse = ResourceRestUtils.getResource(resourceCP, sdncDesignerDetails1); + components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse())); + + componentGetResponse = ResourceRestUtils.getResource(resourceVF, sdncDesignerDetails1); + components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse())); + + componentGetResponse = ResourceRestUtils.getResource(resourceVL, sdncDesignerDetails1); + components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse())); + + Service service = AtomicOperationUtils + .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + componentGetResponse = ServiceRestUtils.getService(service.getUniqueId(), + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + components.add(ResponseParser.parseToObjectUsingMapper(componentGetResponse.getResponse(), Service.class)); + + for (Component component : components) { + Map toscaArtifacts = component.getToscaArtifacts(); + assertNotNull("toscaArtifacts list is null", toscaArtifacts); + List listOfToscaArtTypesFromConfig = Utils.getListOfToscaArtLabels(true); + assertNotNull("tosca artifact types list is null", listOfToscaArtTypesFromConfig); + for (String toscaArtType : listOfToscaArtTypesFromConfig) { + assertNotNull("placeholder of " + toscaArtType + " type doesn't exist", + toscaArtifacts.get(toscaArtType)); + } + } + + } + + // test check configuration of "displayName" field for "heat" type + // deployment artifact + @Test + public void validateDeploymentPlaceHoldersDescriptionOfHeatByConfig() throws IOException { + + Map mapOfDepResArtTypesObjects = getMapOfDepResArtTypesObjects(); + assertNotNull("deployment artifact types list is null", mapOfDepResArtTypesObjects); + Object object = mapOfDepResArtTypesObjects.get("heat"); + if (object instanceof Map) { + Map map = (Map) object; + assertTrue(map.get("displayName").equals("Base HEAT Template")); + } else { + assertTrue("return object does not instance of map", false); + } + } + + @Test + public void addDepResArtEachType() throws Exception { + + String artType; + + addDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails); + RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + List listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true); + assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig); + for (String iter : listOfResDepArtTypesFromConfig) { + artType = iter; + verifyDepArtPlaceHoldersByType(artType); + } + } + + @Test + public void checkHeatParametersExistingForEachType() throws Exception { + + String artType; + + addDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails); + RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + List listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true); + assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig); + for (String iter : listOfResDepArtTypesFromConfig) { + artType = iter; + verifyDepArtPlaceHoldersByType(artType); + verifyHeatParametersExistance(artType, false); + } + } + + @Test + public void checkHeatParametersExistingForSpecificType() throws Exception { + + String artType; + + addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails); + RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + List listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true); + assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig); + for (String iter : listOfResDepArtTypesFromConfig) { + artType = iter; + if (heatArtifactDetails.getArtifactLabel().equals(iter)) { + verifyHeatParametersExistance(artType, true); + } else { + verifyHeatParametersExistance(artType, false); + } + } + } + + @Test + public void addAndDeleteDepResArtEachType() throws Exception { + + String artType; + + addDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails); + addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails); + RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + List listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true); + assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig); + for (String iter : listOfResDepArtTypesFromConfig) { + artType = iter; + verifyDepArtPlaceHoldersByType(artType); + } + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, + sdncDesignerDetails1, LifeCycleStatesEnum.CHECKIN); + assertTrue("expected response code in CHECKIN 200", restResponseResource.getErrorCode() == 200); + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, sdncDesignerDetails1, + LifeCycleStatesEnum.CHECKOUT); + assertTrue("expected response code in CHECKOUT 200", restResponseResource.getErrorCode() == 200); + + // delete all deployment artifacts + deleteDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails); + deleteDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails); + deleteDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails); + response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true); + assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig); + for (String iter : listOfResDepArtTypesFromConfig) { + artType = iter; + verifyDepArtPlaceHoldersByType(artType); + } + } + + @Test + public void addRemoveAddAgainArtifact() throws Exception { + + // get MAP before upload artifact + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + + ArtifactDefinition artifactDefinition = deploymentArtifacts.get("heat"); + + // validate place holder exist + assertNotNull(artifactDefinition); + + // add artifact + updateArtifactReqDetails = getUpdateArtifactDetails(ArtifactTypeEnum.HEAT.getType()); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource( + updateArtifactReqDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: " + + addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 200); + + ArtifactDefinition artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse()); + ArtifactDefinition artDef1 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject); + + // remove artifact + RestResponse deleteArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource( + resourceDetails1.getUniqueId(), updateArtifactReqDetails, sdncDesignerDetails1); + logger.debug( + "addInformationalArtifactToResource response: " + deleteArtifactFromResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + deleteArtifactFromResource.getErrorCode(), + deleteArtifactFromResource.getErrorCode() == 200); + + RestResponse getResourceResp = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1); + + artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(deleteArtifactFromResource.getResponse()); + assertTrue(artifactDefinitionResponseJavaObject.getArtifactName().isEmpty()); + assertTrue(artifactDefinitionResponseJavaObject.getDescription().isEmpty()); + assertTrue(artifactDefinitionResponseJavaObject.getArtifactChecksum().isEmpty()); + assertTrue(artifactDefinitionResponseJavaObject.getEsId().isEmpty()); + assertTrue(artifactDefinitionResponseJavaObject.getArtifactUUID().isEmpty()); + assertNull(artifactDefinitionResponseJavaObject.getHeatParameters()); + + // add artifact again with different user + addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: " + + addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 200); + + artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse()); + ArtifactDefinition artDef2 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject); + + assertFalse("check artifact checksum", artDef1.getArtifactChecksum().equals(artDef2.getArtifactChecksum())); + assertTrue("check artifact EsId", artDef1.getEsId().equals(artDef2.getEsId())); + assertFalse("check artifact UUID", artDef1.getArtifactUUID().equals(artDef2.getArtifactUUID())); + assertTrue("check UserIdCreator", artDef1.getUserIdCreator().equals(artDef2.getUserIdCreator())); + assertTrue("check UserIdLastUpdater", artDef1.getUserIdLastUpdater().equals(artDef2.getUserIdLastUpdater())); + } + + @Test + public void addUpdateArtifactByType() throws Exception { + + // get MAP before upload artifact + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + + ArtifactDefinition artifactDefinition = deploymentArtifacts.get("heat"); + + // validate place holder exist + assertNotNull(artifactDefinition); + + // add artifact + updateArtifactReqDetails = getUpdateArtifactDetails(ArtifactTypeEnum.HEAT.getType()); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource( + updateArtifactReqDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: " + + addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 200); + + ArtifactDefinition artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse()); + ArtifactDefinition artDef1 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject); + + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, + sdncDesignerDetails1, LifeCycleStatesEnum.CHECKIN); + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, sdncDesignerDetails2, + LifeCycleStatesEnum.CHECKOUT); + + // update with different user artifact + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setUniqueId(artifactDefinition.getUniqueId()); + heatArtifactDetails.setArtifactName("2.yaml"); + heatArtifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); + + addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails2, resourceDetails1.getUniqueId(), "heat"); + logger.debug("addInformationalArtifactToResource response: " + + addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 200); + + artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse()); + ArtifactDefinition artDef2 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject); + verifyArtDefFields(artDef1, artDef2); + + } + + @Test + public void addUpdateDeleteArtifact() throws Exception { + + // get MAP before upload artifact + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + + ArtifactDefinition artifactDefinition = deploymentArtifacts.get("heat"); + + // validate place holder exist + assertNotNull(artifactDefinition); + + updateArtifactReqDetails = getUpdateArtifactDetails(ArtifactTypeEnum.HEAT.getType()); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource( + updateArtifactReqDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId()); + logger.debug("addInformationalArtifactToResource response: " + + addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 200); + + ArtifactDefinition artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse()); + ArtifactDefinition artDef1 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject); + + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, + sdncDesignerDetails1, LifeCycleStatesEnum.CHECKIN); + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, sdncDesignerDetails2, + LifeCycleStatesEnum.CHECKOUT); + + // update with different user artifact + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setArtifactName("2.yaml"); + + addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails2, resourceDetails1.getUniqueId(), "heat"); + logger.debug("addInformationalArtifactToResource response: " + + addInformationalArtifactToResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 200); + + artifactDefinitionResponseJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse()); + ArtifactDefinition artDef2 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject); + + verifyArtDefFields(artDef1, artDef2); + + RestResponse delteArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource( + resourceDetails1.getUniqueId(), heatArtifactDetails, sdncDesignerDetails2); + logger.debug("addInformationalArtifactToResource response: {}", delteArtifactFromResource.getResponseMessage()); + assertTrue("response code is not 200, returned :" + delteArtifactFromResource.getErrorCode(), + delteArtifactFromResource.getErrorCode() == 200); + + } + + @Test + public void addHeatVolArtInvalidExtension() throws Exception { + + heatVolArtifactDetails.setArtifactName("heatVol.txt"); + RestResponse response = getResponseOnAddDeploymentArtifactByTypeToResource(resourceDetails1, + heatVolArtifactDetails); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name()); + assertEquals("Check response code after upload artifact", errorInfo.getCode(), response.getErrorCode()); + List variables = Arrays.asList(ArtifactTypeEnum.HEAT_VOL.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables, + response.getResponse()); + } + + @Test + public void addHeatNetArtInvalidExtension() throws Exception { + + heatNetArtifactDetails.setArtifactName("yaml"); + RestResponse response = getResponseOnAddDeploymentArtifactByTypeToResource(resourceDetails1, + heatNetArtifactDetails); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name()); + assertEquals("Check response code after upload artifact", errorInfo.getCode(), response.getErrorCode()); + List variables = Arrays.asList(ArtifactTypeEnum.HEAT_NET.getType()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables, + response.getResponse()); + } + + @Test + public void checkServiceSecurityTemplateInformationalArtifactsCreation() throws IOException, Exception { + + Either createServiceResponse = AtomicOperationUtils + .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true); + Map artifacts = null; + ArtifactDefinition securitytemplate = null; + if (createServiceResponse.isLeft()) { + Component component = createServiceResponse.left().value(); + artifacts = component.getArtifacts(); + securitytemplate = artifacts.get("servicesecuritytemplate"); + assertNotNull(securitytemplate); + assertEquals("Service Security Template", securitytemplate.getArtifactDisplayName()); + } else { + logger.debug("checkSecurityTemplateInformationalArtifactsCreation service creation response: " + + createServiceResponse.right().value().getResponseMessage()); + } + } + + @Test + public void checkResourceSecurityTemplateInformationalArtifactsCreation() throws IOException, Exception { + + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.CONTAINER_APPLICATION, ResourceCategoryEnum.APPLICATION_L4_BORDER, + UserRoleEnum.DESIGNER, true).left().value(); + Map artifacts = resource.getArtifacts(); + ArtifactDefinition securitytemplate = artifacts.get("resourcesecuritytemplate"); + assertNotNull(securitytemplate); + assertEquals("Resource Security Template", securitytemplate.getArtifactDisplayName()); + } + + // Benny + @Test + public void serviceSecurityTemplateInformationalArtifact() throws IOException, Exception { + String artifactPlaceHolder = "servicesecuritytemplate"; + Service service = AtomicOperationUtils + .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + Map artifacts = service.getArtifacts(); + ArtifactDefinition securitytemplate = artifacts.get(artifactPlaceHolder); + assertNotNull(securitytemplate); + assertEquals("Service Security Template", securitytemplate.getArtifactDisplayName()); + assertEquals("OTHER", securitytemplate.getArtifactType()); + assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel()); + // Get service + RestResponse getService = ServiceRestUtils.getService(service.getUniqueId(), + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getService.getErrorCode().intValue()); + service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class); + artifacts = service.getArtifacts(); + securitytemplate = artifacts.get(artifactPlaceHolder); + assertNotNull(securitytemplate); + assertEquals("Service Security Template", securitytemplate.getArtifactDisplayName()); + assertEquals("OTHER", securitytemplate.getArtifactType()); + assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel()); + } + + @Test + public void resourceSecurityTemplateInformationalArtifacts() throws IOException, Exception { + String artifactPlaceHolder = "resourcesecuritytemplate"; + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.CONTAINER_APPLICATION, ResourceCategoryEnum.APPLICATION_L4_BORDER, + UserRoleEnum.DESIGNER, true).left().value(); + Map artifacts = resource.getArtifacts(); + ArtifactDefinition securitytemplate = artifacts.get("resourcesecuritytemplate"); + assertNotNull(securitytemplate); + assertEquals("Resource Security Template", securitytemplate.getArtifactDisplayName()); + assertEquals("OTHER", securitytemplate.getArtifactType()); + assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel()); + // Get resource + RestResponse getresource = ResourceRestUtils.getResource(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + resource.getUniqueId()); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getresource.getErrorCode().intValue()); + resource = ResponseParser.parseToObjectUsingMapper(getresource.getResponse(), Resource.class); + artifacts = resource.getArtifacts(); + securitytemplate = artifacts.get(artifactPlaceHolder); + assertNotNull(securitytemplate); + assertEquals("Resource Security Template", securitytemplate.getArtifactDisplayName()); + assertEquals("OTHER", securitytemplate.getArtifactType()); + assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel()); + } + + // ================================================ + + @SuppressWarnings("unchecked") + private Map getMapOfDepResArtTypesObjects() throws FileNotFoundException { + + return (Map) Utils.parseYamlConfig("deploymentResourceArtifacts"); + + } + + private void addDeploymentArtifactByTypeToResource(ResourceReqDetails resourceReqDetails, + ArtifactReqDetails artReqDetails) throws IOException, Exception { + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(artReqDetails, + sdncDesignerDetails1, resourceReqDetails.getUniqueId()); + assertTrue("add" + artReqDetails.getArtifactLabel() + " artifact to resource request returned status:" + + response.getErrorCode(), response.getErrorCode() == 200); + } + + private RestResponse getResponseOnAddDeploymentArtifactByTypeToResource(ResourceReqDetails resourceReqDetails, + ArtifactReqDetails artReqDetails) throws IOException, Exception { + + return ArtifactRestUtils.addInformationalArtifactToResource(artReqDetails, sdncDesignerDetails1, + resourceReqDetails.getUniqueId()); + } + + private void deleteDeploymentArtifactByTypeToResource(ResourceReqDetails resourceReqDetails, + ArtifactReqDetails artReqDetails) throws IOException, Exception { + + RestResponse response = ArtifactRestUtils.deleteInformationalArtifactFromResource( + resourceReqDetails.getUniqueId(), artReqDetails, sdncDesignerDetails1); + assertTrue("delete" + artReqDetails.getArtifactLabel() + " artifact to resource request returned status:" + + response.getErrorCode(), response.getErrorCode() == 200); + } + + private void verifyDepArtPlaceHoldersByType(String artType) { + + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + assertNotNull("deployment artifact data is null", deploymentArtifacts.get(artType)); + assertNotNull("deployment artifact data is null", deploymentArtifacts.get(artType).getEsId()); + assertNotNull("deployment artifact data is null", deploymentArtifacts.get(artType).getDescription()); + assertTrue( + "deployment artifact timeout does not equal to default value " + timeOut + " expected " + timeOut + + ", actual - " + deploymentArtifacts.get(artType).getTimeout(), + deploymentArtifacts.get(artType).getTimeout() == timeOut); + assertTrue("deployment artifact label value ", + deploymentArtifacts.get(artType).getArtifactLabel().equals(artType)); + } + + private void verifyHeatParametersExistance(String artType, Boolean isNull) { + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + if (isNull) { + assertNull("heatParameters list for type " + artType + " is not null", + deploymentArtifacts.get(artType).getHeatParameters()); + } else { + assertNotNull("heatParameters list for type " + artType + " is null", + deploymentArtifacts.get(artType).getHeatParameters()); + } + } + + private void verifyArtDefFields(ArtifactDefinition artDef1, ArtifactDefinition artDef2) { + + assertFalse("check artifact checksum", artDef1.getArtifactChecksum().equals(artDef2.getArtifactChecksum())); + assertFalse("check artifact EsId", artDef1.getEsId().equals(artDef2.getEsId())); + assertFalse("check artifact UUID", artDef1.getArtifactUUID().equals(artDef2.getArtifactUUID())); + assertTrue("check UserIdCreator", artDef1.getUserIdCreator().equals(artDef2.getUserIdCreator())); + assertFalse("check UserIdLastUpdater", artDef1.getUserIdLastUpdater().equals(artDef2.getUserIdLastUpdater())); + + } + + private ArtifactDefinition fillArtDefFromResponse(ArtifactDefinition artifactDefinitionResponseJavaObject) { + ArtifactDefinition artDef = new ArtifactDefinition(); + artDef.setArtifactChecksum(artifactDefinitionResponseJavaObject.getArtifactChecksum()); + artDef.setEsId(artifactDefinitionResponseJavaObject.getEsId()); + artDef.setArtifactUUID(artifactDefinitionResponseJavaObject.getArtifactUUID()); + artDef.setUserIdCreator(artifactDefinitionResponseJavaObject.getUserIdCreator()); + artDef.setUserIdLastUpdater(artifactDefinitionResponseJavaObject.getUserIdLastUpdater()); + return artDef; + } + + private ArtifactReqDetails getUpdateArtifactDetails(String artType) throws IOException, Exception { + String ext = heatExtension; + String sourceDir = config.getResourceConfigDir(); + String testResourcesPath = sourceDir + File.separator + folderName; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + logger.debug("listFileName: {}", listFileName.toString()); + + String payload = FileUtils.loadPayloadFile(listFileName, ext, true); + ArtifactReqDetails updateArtifactReqDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType); + updateArtifactReqDetails.setPayload(payload); + updateArtifactReqDetails.setArtifactName("1.yaml"); + return updateArtifactReqDetails; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java new file mode 100644 index 0000000000..6b902dbfb8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java @@ -0,0 +1,632 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Decoder; +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.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.yaml.snakeyaml.Yaml; + +public class ValidateArtResponse extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + protected String serviceVersion; + + public ValidateArtResponse() { + super(name, ArtifactServletTest.class.getName()); + + } + + protected final String pathToFile = "heatArtifactParameters"; + protected final String heatWithValidParams = "heatWithValidParams.yaml"; + protected final String heatWithParamsMissingDefault = "heatWithParamsMissingDefault.yaml"; + protected final String heatWithParamsMissingDesc = "heatWithParamsMissingDesc.yaml"; + protected final String heatWithParamsMissingType = "heatWithParamsMissingType.yaml"; + protected final String importNoDerivedFromFile = "myComputeDerivedFromNotExists.yml"; + protected final String decodedPayload = "decodedPayload"; + protected final String encodedPayload = "encodedPayload"; + + protected Resource resourceDetailsObj; + protected ResourceReqDetails resourceDetails; + protected User sdncDesignerDetails; + + @BeforeMethod + public void init() throws Exception { + + resourceDetailsObj = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetails = new ResourceReqDetails(resourceDetailsObj); + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + } + + @Test + public void compareParamtersVsYaml() throws Exception { + + // select file to upload + + Map filePayload = selectFileToUpload(pathToFile, heatWithValidParams); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // create MAP from received JSON + + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + protected void assertnull(String string, boolean equals) { + // TODO Auto-generated method stub + + } + + public Map extractSingleParameter(Map curr) { + Map innerMap = new HashMap(); + if (curr.containsKey("description")) { + innerMap.put("description", curr.get("description")); + } + + if (curr.containsKey("defaultValue")) { + innerMap.put("default", curr.get("defaultValue")); + } else { + // System.out.println("kuku"); + } + innerMap.put("type", curr.get("type")); + return innerMap; + } + + public Map createMapFromYaml(String payload) { + ArrayList parametersList = new ArrayList(); + + Yaml yaml = new Yaml(); + + Map result = (Map) yaml.load(payload); + Map paramters = (Map) result.get("parameters"); + + for (Map.Entry entry : paramters.entrySet()) { + Map origInnerMap = (Map) entry.getValue(); + + if (origInnerMap.containsKey("label")) { + origInnerMap.remove("label"); + paramters.remove(entry); + paramters.put(entry.getKey(), origInnerMap); + } + } + return paramters; + } + + public Map> jsonToMap(RestResponse addInformationalArtifactToResource, + String section2extract, String createKeyMapBy) { + Map JsonToMap = new HashMap(); + JsonToMap = (Map) ResponseParser.parseToObject(addInformationalArtifactToResource.getResponse(), + JsonToMap.getClass()); + + List> listOfParamters = (List>) JsonToMap.get(section2extract); + Map> mapOfActualParameters = new HashMap>(); + + for (Map curr : listOfParamters) { + Map innerMap = extractSingleParameter(curr); + + mapOfActualParameters.put(curr.get(createKeyMapBy), innerMap); + } + return mapOfActualParameters; + } + + public Map selectFileToUpload(String pathToFile, String fileName) throws IOException { + String sourceDir = config.getResourceConfigDir(); + String testResourcesPath = sourceDir + File.separator + pathToFile; + String file = fileName; + Map filePayload = new HashMap(); + String payload = Decoder.readFileToString(testResourcesPath + File.separator + file); + filePayload.put(decodedPayload, payload); + filePayload.put(encodedPayload, Decoder.encode(payload.getBytes())); + + return filePayload; + } + + @Test + public void missingDescParam() throws Exception { + + // select file to upload + + Map filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingDesc); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // create MAP from received JSON + + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + @Test + public void missingDefaultParam() throws Exception { + + // select file to upload + + Map filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingDefault); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // create MAP from received JSON + + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + @Test + public void missingTypeParam() throws Exception { + + // select file to upload + + Map filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingType); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // System.out.println(addInformationalArtifactToResource); + AssertJUnit.assertTrue( + "response code is not 400, returned :" + addInformationalArtifactToResource.getErrorCode(), + addInformationalArtifactToResource.getErrorCode() == 400); + + } + + @Test + public void updateValueParam() throws Exception { + + String updateValueParam = "changed"; + + Map filePayload = selectFileToUpload(pathToFile, heatWithValidParams); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + // System.out.println(resourceGetResponse.getResponse().toString()); + String atifactUniqueId = ResponseParser + .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId"); + + ArtifactReqDetails artifacJavaObject = ResponseParser + .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse()); + List heatParameters2 = artifacJavaObject.getHeatParameters(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters2) { + heatParameterDefinition.setCurrentValue(updateValueParam); + } + artifacJavaObject.setHeatParameters(heatParameters2); + artifacJavaObject.setPayloadData(null); + + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource( + artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // verify change in update response + + ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse()); + List heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters(); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + String verify = updateValueParam; + AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue())); + } + + // verify change in getResource + + resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + deploymentArtifacts.get(heatArtifactDetails.getArtifactName()); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + String verify = updateValueParam; + AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue())); + } + + // create MAP from received JSON + + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + @Test + public void updateValueParamMissingDefault() throws Exception { + + String updateValueParam = "changed"; + + Map filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingDefault); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + // System.out.println(resourceGetResponse.getResponse().toString()); + String atifactUniqueId = ResponseParser + .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId"); + + ArtifactReqDetails artifacJavaObject = ResponseParser + .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse()); + List heatParameters2 = artifacJavaObject.getHeatParameters(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters2) { + heatParameterDefinition.setCurrentValue(updateValueParam); + } + artifacJavaObject.setHeatParameters(heatParameters2); + artifacJavaObject.setPayloadData(null); + + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource( + artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // verify change in update response + + ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse()); + List heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters(); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + String verify = updateValueParam; + AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue())); + } + + // verify change in getResource + + resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + deploymentArtifacts.get(heatArtifactDetails.getArtifactName()); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + String verify = updateValueParam; + AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue())); + } + + // create MAP from received JSON + + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + @Test + public void updateValueParamNull() throws Exception { + + String updateValueParam = null; + + Map filePayload = selectFileToUpload(pathToFile, heatWithValidParams); + + // upload HEAT file and save JSON response + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + // System.out.println(resourceGetResponse.getResponse().toString()); + String atifactUniqueId = ResponseParser + .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId"); + + ArtifactReqDetails artifacJavaObject = ResponseParser + .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse()); + List heatParameters2 = artifacJavaObject.getHeatParameters(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters2) { + heatParameterDefinition.setCurrentValue(updateValueParam); + } + artifacJavaObject.setHeatParameters(heatParameters2); + artifacJavaObject.setPayloadData(null); + + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource( + artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // verify change in update response + ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse()); + List heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters(); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + // String verify = updateValueParam; + if (heatParameterDefinition.getDefaultValue() != null) { + AssertJUnit.assertTrue( + heatParameterDefinition.getDefaultValue().equals(heatParameterDefinition.getCurrentValue())); + } else { + AssertJUnit.assertNull("verification failed", heatParameterDefinition.getCurrentValue()); + } + } + + // verify change in getResource + resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + deploymentArtifacts.get(heatArtifactDetails.getArtifactName()); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + // String verify = updateValueParam; + if (heatParameterDefinition.getDefaultValue() != null) { + AssertJUnit.assertTrue( + heatParameterDefinition.getDefaultValue().equals(heatParameterDefinition.getCurrentValue())); + } else { + AssertJUnit.assertNull("verification failed", heatParameterDefinition.getCurrentValue()); + } + } + + // create MAP from received JSON + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + @Test + public void updateValueParamEmpty() throws Exception { + + String updateValueParam = ""; + + Map filePayload = selectFileToUpload(pathToFile, heatWithValidParams); + + // upload HEAT file and save JSON response + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + // System.out.println(resourceGetResponse.getResponse().toString()); + String atifactUniqueId = ResponseParser + .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId"); + + ArtifactReqDetails artifacJavaObject = ResponseParser + .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse()); + List heatParameters2 = artifacJavaObject.getHeatParameters(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters2) { + heatParameterDefinition.setCurrentValue(updateValueParam); + } + artifacJavaObject.setHeatParameters(heatParameters2); + artifacJavaObject.setPayloadData(null); + + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource( + artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId()); + + // verify change in update response + + ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse()); + List heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters(); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + String verify = updateValueParam; + AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue())); + } + + // verify change in getResource + + resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + deploymentArtifacts.get(heatArtifactDetails.getArtifactName()); + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + String verify = updateValueParam; + AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue())); + } + + // create MAP from received JSON + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + + @Test + public void onlyValueParamPermited() throws Exception { + + Map filePayload = selectFileToUpload(pathToFile, heatWithValidParams); + + // upload HEAT file and save JSON response + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatArtifactDetails.setPayload(filePayload.get(encodedPayload)); + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId()); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + // System.out.println(resourceGetResponse.getResponse().toString()); + String atifactUniqueId = ResponseParser + .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId"); + + ArtifactReqDetails artifacJavaObject = ResponseParser + .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse()); + List heatParameters2 = artifacJavaObject.getHeatParameters(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters2) { + heatParameterDefinition.setDefaultValue("changed"); + heatParameterDefinition.setName("changed"); + heatParameterDefinition.setDescription("changed"); + heatParameterDefinition.setType("changed"); + heatParameterDefinition.setCurrentValue("changed"); + } + artifacJavaObject.setHeatParameters(heatParameters2); + artifacJavaObject.setPayloadData(null); + + RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource( + artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId()); + + resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails); + + // create MAP from received JSON + + String section2extract = "heatParameters"; + String createKeyMapBy = "name"; + Map> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource, + section2extract, createKeyMapBy); + + // Prepare map to validate JS + + Map paramters = createMapFromYaml(filePayload.get(decodedPayload)); + + // compare MAPs + + ResourceValidationUtils.compareElements(mapOfActualParameters, paramters); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java new file mode 100644 index 0000000000..dfbf035b41 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java @@ -0,0 +1,177 @@ +/*- + * ============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.ci.tests.execute.artifacts; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +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.RespJsonKeysEnum; +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.ArtifactRestUtils; +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.validation.ArtifactValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + +public class ValidateHeatArtFieldsTypes extends ComponentBaseTest { + + protected User sdncDesignerDetails; + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + + private static final String heatExtension = "yaml"; + private static final String yangXmlExtension = "xml"; + private static final String muranoPkgExtension = "zip"; + private final String folderName = "yamlFieldsValidation"; + + private final String uuidString = RespJsonKeysEnum.UUID.getRespJsonKeyName().toString(); + + public ValidateHeatArtFieldsTypes() { + super(name, ValidateHeatArtFieldsTypes.class.getName()); + } + + @Rule + public static TestName name = new TestName(); + + @Test + public void validateHeatArtFiledTypes() throws Exception { + + // get relevant resource and service + + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + resourceDetails = ElementFactory.getDefaultResource(); + + RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails); + AssertJUnit.assertTrue("create request returned status:" + response.getErrorCode(), + response.getErrorCode() == 201); + + // add artifact to resource1 + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + List listOfArtifactFromFolder = ArtifactValidationUtils.getListOfArtifactFromFolder(folderName); + for (int i = 0; i < listOfArtifactFromFolder.size(); i++) { + heatArtifactDetails = ArtifactValidationUtils.replaceDefaultArtWithArtFromList(heatArtifactDetails, + heatExtension, folderName, i); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails, + resourceDetails.getUniqueId()); + + if (heatArtifactDetails.getArtifactName().contains("bool")) { + if (heatArtifactDetails.getArtifactName().contains("negative")) { + // validate negative response + List variables = Arrays.asList("HEAT", "boolean", "city_name"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(), + variables, response.getResponse()); + } + if (heatArtifactDetails.getArtifactName().contains("positive")) { + AssertJUnit.assertTrue( + "add HEAT artifact to resource request returned status:" + response.getErrorCode() + + " fileName: " + heatArtifactDetails.getArtifactName(), + response.getErrorCode() == 200); + ArtifactDefinition artifactDefinitionJavaObject = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(response.getResponse()); + List heatParameters = artifactDefinitionJavaObject.getHeatParameters(); + String currentValue = null; + for (HeatParameterDataDefinition heatParameterDefinition : heatParameters) { + if (heatParameterDefinition.getName().equals("city_name")) { + currentValue = heatParameterDefinition.getCurrentValue(); + } + } + if (heatArtifactDetails.getArtifactName().contains("true")) { + AssertJUnit.assertTrue(currentValue.equals("true")); + } + if (heatArtifactDetails.getArtifactName().contains("false")) { + AssertJUnit.assertTrue(currentValue.equals("false")); + } + RestResponse deleteInformationalArtifactFromResource = ArtifactRestUtils + .deleteInformationalArtifactFromResource(resourceDetails.getUniqueId(), heatArtifactDetails, + sdncDesignerDetails); + AssertJUnit.assertTrue( + "delete HEAT artifact from resource request returned status:" + + deleteInformationalArtifactFromResource.getErrorCode(), + deleteInformationalArtifactFromResource.getErrorCode() == 200); + } + + } else if (heatArtifactDetails.getArtifactName().contains("number")) { + if (heatArtifactDetails.getArtifactName().contains("negative")) { + // validate negative response + List variables = Arrays.asList("HEAT", "number", "city_name"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(), + variables, response.getResponse()); + } + if (heatArtifactDetails.getArtifactName().contains("positive")) { + AssertJUnit.assertTrue( + "add HEAT artifact to resource request returned status:" + response.getErrorCode() + + " fileName: " + heatArtifactDetails.getArtifactName(), + response.getErrorCode() == 200); + } + + } else if (heatArtifactDetails.getArtifactName().contains("string")) { + if (heatArtifactDetails.getArtifactName().contains("negative")) { + // validate negative response + List variables = Arrays.asList("HEAT", "string", "city_name"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(), + variables, response.getResponse()); + } + if (heatArtifactDetails.getArtifactName().contains("positive")) { + AssertJUnit.assertTrue( + "add HEAT artifact to resource request returned status:" + response.getErrorCode() + + " fileName: " + heatArtifactDetails.getArtifactName(), + response.getErrorCode() == 200); + } + + } + + else if (heatArtifactDetails.getArtifactName().contains("unsupported")) { + + // validate negative response + List variables = Arrays.asList("HEAT", "number123"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_TYPE.name(), + variables, response.getResponse()); + + } + + else { + AssertJUnit.assertTrue( + "add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + } + } + + } + +} 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 new file mode 100644 index 0000000000..b1d04ba88d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.execute.attribute; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.swallowException; + +import java.io.File; +import java.util.function.Function; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.testng.annotations.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class ComponentInstanceAttributeTest extends ComponentBaseTest { + + public static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @Rule + public static TestName name = new TestName(); + + public ComponentInstanceAttributeTest() { + super(name, ComponentInstanceAttributeTest.class.getName()); + } + + @Test + public void testUpdateAttributeOnResourceInstance() { + // Prepare VF with vfc instance with Attributes + String testResourcesPath = config.getResourceConfigDir() + File.separator + "importToscaResourceByCreateUrl"; + final Resource vfcWithAttributes = AtomicOperationUtils + .importResource(testResourcesPath, "CPWithAttributes.yml").left().value(); + swallowException(() -> AtomicOperationUtils.changeComponentState(vfcWithAttributes, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CHECKIN, false)); + Resource vf = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, false) + .left().value(); + ComponentInstance vfcInstance = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfcWithAttributes, vf).left().value(); + + // util method to get the specific attribute from the vf + Function attributeGetter = resourceVf -> resourceVf + .getComponentInstancesAttributes().values().iterator().next().stream() + .filter(att -> att.getName().equals("private_address")).findAny().get(); + // update attribute on vfc instance + final Resource vfWithInsatncePreUpdate = swallowException( + () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER)); + ComponentInstanceProperty attributeOfRI = attributeGetter.apply(vfWithInsatncePreUpdate); + final String newAttValue = "NewValue"; + attributeOfRI.setValue(newAttValue); + String body = gson.toJson(attributeOfRI); + String url = String.format(Urls.UPDATE_ATTRIBUTE_ON_RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(ComponentTypeEnum.RESOURCE), + vf.getUniqueId(), vfcInstance.getUniqueId()); + swallowException(() -> BaseRestUtils.sendPost(url, body, UserRoleEnum.DESIGNER.getUserId(), + BaseRestUtils.acceptHeaderData)); + // Retrieve updated vf and verify attribute was updated + final Resource vfWithInsatncePostUpdate = swallowException( + () -> (Resource) AtomicOperationUtils.getCompoenntObject(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/category/CatalogDataApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java new file mode 100644 index 0000000000..9938266602 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java @@ -0,0 +1,236 @@ +/*- + * ============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.ci.tests.execute.category; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +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.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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +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.ElementFactory; +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.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class CatalogDataApiTest extends ComponentBaseTest { + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + @Rule + public static TestName name = new TestName(); + protected User user; + protected RestResponse res1; + protected RestResponse res2; + protected RestResponse svc1; + protected ResourceReqDetails resourceDetails1; + protected ResourceReqDetails resourceDetails2; + protected ServiceReqDetails svcDetails1; + + public CatalogDataApiTest() { + super(name, CatalogDataApiTest.class.getName()); + } + + @BeforeMethod + public void setUp() throws Exception { + user = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + resourceDetails1 = buildResourceDetails(user, "TestResource1"); + resourceDetails2 = buildResourceDetails(user, "TestResource2"); + svcDetails1 = buildServiceDetails("TestService1"); + + res1 = createResource(user, resourceDetails1); + AssertJUnit.assertEquals("create resorce failed", 201, res1.getErrorCode().intValue()); + resourceDetails1.setUniqueId(ResponseParser.getUniqueIdFromResponse(res1)); + resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res1)); + + res2 = createResource(user, resourceDetails2); + AssertJUnit.assertEquals("create resorce failed", 201, res2.getErrorCode().intValue()); + resourceDetails2.setUniqueId(ResponseParser.getUniqueIdFromResponse(res2)); + resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res2)); + + 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()); + } + + @AfterMethod + public void tearDown() throws Exception { + deleteResource(resourceDetails1.getUniqueId(), user.getUserId()); + deleteResource(resourceDetails2.getUniqueId(), user.getUserId()); + deleteService(svcDetails1.getUniqueId(), user); + } + + // Keep 1 + @Test + public void getCatalogData() throws Exception { + + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails1, user, "0.1", + LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("check in operation failed", 200, checkInResponse.getErrorCode().intValue()); + + RestResponse res = CatalogRestUtils.getCatalog(user.getUserId()); + 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. + AssertJUnit.assertTrue("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)); + + } + + protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception { + RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId); + + } + + protected RestResponse createResource(User user, ResourceReqDetails resourceDetails) throws Exception { + deleteResource(resourceDetails.getName(), user.getUserId()); + return ResourceRestUtils.createResource(resourceDetails, user); + } + + protected ResourceReqDetails buildResourceDetails(User user, String resourceName) { + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.0"; + String contactId = user.getUserId(); + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, + derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), + ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); + return resourceDetails; + } + + 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; + } + + protected RestResponse createService(User user, ServiceReqDetails svcDetails) throws Exception { + + Config config = Utils.getConfig(); + + Map headersMap = getHeadersMap(user); + + Gson gson = new Gson(); + String body = gson.toJson(svcDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort()); + RestResponse res = http.httpSendPost(url, body, headersMap); + // System.out.println("Create service was finished with response: + // "+res.getErrorCode()); + return res; + } + + protected Map getHeadersMap(User user) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put("USER_ID", user.getUserId()); + return headersMap; + } + + protected ServiceReqDetails buildServiceDetails(String serviceName) { + String description = "description"; + ArrayList serviceTags = new ArrayList(); + serviceTags.add("tag1"); + serviceTags.add(serviceName); + String category = ServiceCategoriesEnum.MOBILITY.getValue(); + String vendorName = "Oracle"; + String vendorRelease = "0.1"; + String contactId = "al1976"; + String icon = "myIcon"; + + ServiceReqDetails svcdetails = new ServiceReqDetails(serviceName, category, serviceTags, description, + contactId, icon); + return svcdetails; + } + + 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 headersMap = getHeadersMap(user); + RestResponse res = httpRequest.httpSendDelete(url, headersMap); + // System.out.println("Delete service was finished with response: + // "+res.getErrorCode()); + return res; + } + + public class NewObject { + private String _name; + + public String getName() { + return _name; + } + + public void setName(String name) { + this._name = name; + } + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java new file mode 100644 index 0000000000..d68f3f5582 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.execute.category; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; + +public abstract class CategoriesBaseTest extends ComponentBaseTest { + + public CategoriesBaseTest(TestName testName, String className) { + super(testName, className); + } + + protected static final String AUDIT_SERVICE_TYPE = "Service"; + protected static final String AUDIT_RESOURCE_TYPE = "Resource"; + protected static final String AUDIT_PRODUCT_TYPE = "Product"; + protected static final String GET_CATEGORY_HIERARCHY = "GetCategoryHierarchy"; + protected static User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + protected static User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + protected static User sdncDesignerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + protected static User sdncTesterUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + protected static User sdncGovernorUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + protected static User sdncOpsUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + protected static User sdncProductManagerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + protected static User sdncProductStrategistUserDetails = ElementFactory + .getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java new file mode 100644 index 0000000000..3b85c052a1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java @@ -0,0 +1,2303 @@ +/*- + * ============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.ci.tests.execute.category; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.RESOURCE_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.SERVICE_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.text.WordUtils; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.json.JSONArray; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.CategoryValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.SkipException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class CategoriesTests extends CategoriesBaseTest { + + private static final String GET_CATEGORY_HIERARCHY = "GetCategoryHierarchy"; + protected static final String ADD_CATEGORY = "AddCategory"; + protected static final String DELETE_CATEGORY = "DeleteCategory"; + + public CategoriesTests() { + super(name, CategoriesTests.class.getName()); + } + + @Rule + public static TestName name = new TestName(); + private CategoryDefinition categoryDefinition; + private List categoryList; + private List subCategoryList; + private Map> subCategoriesToDeleteMap; + + @BeforeMethod + public void init() throws Exception { + subCategoriesToDeleteMap = new HashMap>(); + DbUtils.deleteFromEsDbByPattern("_all"); + + categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName("Abcd"); + categoryList = defineCategories(); + subCategoryList = defineSubCategories(categoryList.size()); + } + + // pass + @Test + public void createServiceCategorySuccessFlow() throws Exception { + // Add New category + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + // get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); // also + // set + // catalog + // uniqeId + + } + + // pass + @Test + public void createResourceCategorySuccessFlow() throws Exception { + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get Category + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + // pass + @Test + public void createProductCategorySuccessFlow() throws Exception { + // Add Category by Product-strategist + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, + sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + + // Get Category + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void CategoryNameValidation_FirstWordStartWithAlphaNumeric_01() throws Exception { // category + // for + // service + categoryDefinition.setName("Category14AadE &&&---+++.'''###=:@@@____"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category14AadE &-+.'#=:@_"); + categoryDefinition.setNormalizedName("category14aade &-+.'#=:@_"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_FirstWordStartWithAlphaNumeric_02() throws Exception { // category + // for + // resource + categoryDefinition.setName("Category14AadE &&&---+++.'''###=:@@@____"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category14AadE &-+.'#=:@_"); + categoryDefinition.setNormalizedName("category14aade &-+.'#=:@_"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void categoryNameValidation_FirstWordStartWithAlphaNumeric_03() throws Exception { // category + // for + // resource + categoryDefinition.setName("Category14AadE &&&---+++.'''###=:@@@____"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, + sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category14AadE &-+.'#=:@_"); + categoryDefinition.setNormalizedName("category14aade &-+.'#=:@_"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + // pass + @Test + public void createServiceCategoryByNonAdminUser() throws Exception { + // Add New category + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, + sdncProductStrategistUserDetails, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION, + createCategotyRest.getErrorCode().intValue()); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails, + ActionStatus.RESTRICTED_OPERATION, STATUS_CODE_RESTRICTED_OPERATION, AUDIT_SERVICE_TYPE); + } + + // pass + @Test + public void createResourceCategoryByNonAdminUser() throws Exception { + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, + sdncProductStrategistUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION, + createCategotyRest.getErrorCode().intValue()); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails, + ActionStatus.RESTRICTED_OPERATION, STATUS_CODE_RESTRICTED_OPERATION, AUDIT_RESOURCE_TYPE); + } + + // pass + @Test + public void createProductCategoryByNonProductStrategistUser() throws Exception { + // Add New product category not by Product-Strategist + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION, + createCategotyRest.getErrorCode().intValue()); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + ActionStatus.RESTRICTED_OPERATION, STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE); + + } + + // pass + @Test + public void addCategoryByNonExistingUser() throws Exception { + User sdncAdminUserDetailsNonExisting = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncAdminUserDetailsNonExisting.setUserId("bt555h"); + // Add New category + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, + sdncAdminUserDetailsNonExisting, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION, + createCategotyRest.getErrorCode().intValue()); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY); + expectedCatrgoryAuditJavaObject.setModifier("(" + sdncAdminUserDetailsNonExisting.getUserId() + ")"); + expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName()); + expectedCatrgoryAuditJavaObject.setSubCategoryName(""); + expectedCatrgoryAuditJavaObject.setGroupingName(""); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_RESTRICTED_OPERATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY); + } + + @Test + public void addServiceCategoryAllowedcharacters_01() throws Exception { + categoryDefinition.setName("1234AbcdE&"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde&"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_02() throws Exception { + categoryDefinition.setName("1234AbcdE-"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde-"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_03() throws Exception { + categoryDefinition.setName("1234AbcdE+"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde+"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_04() throws Exception { + categoryDefinition.setName("1234AbcdE."); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde."); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_05() throws Exception { + categoryDefinition.setName("1234AbcdE'"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde'"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_06() throws Exception { + categoryDefinition.setName("1234AbcdE="); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde="); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_07() throws Exception { + categoryDefinition.setName("1234AbcdE:"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde:"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_08() throws Exception { + categoryDefinition.setName("1234AbcdE@"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde@"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_09() throws Exception { + categoryDefinition.setName("1234AbcdE_"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde_"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_10() throws Exception { + categoryDefinition.setName("1234AbcdE#"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde#"); // normalization + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_11() throws Exception { + categoryDefinition.setName("1234AbcdE d"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde d"); // normalization + categoryDefinition.setName("1234AbcdE D"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void addServiceCategoryAllowedcharacters_12() throws Exception { + categoryDefinition.setName("1234AbcdE &_=+.-'#:@ d"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("1234abcde &_=+.-'#:@ d"); // normalization + categoryDefinition.setName("1234AbcdE &_=+.-'#:@ D"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveSpaceFromBeginning() throws Exception { + categoryDefinition.setName(" Category01"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("category01"); // normalization + categoryDefinition.setName("Category01"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveSpaceFromEnd() throws Exception { + categoryDefinition.setName("Category01 "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("category01"); // normalization + categoryDefinition.setName("Category01"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraSpace() throws Exception { + categoryDefinition.setName("Category 02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("category 02"); // normalization + categoryDefinition.setName("Category 02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraAmpersand() throws Exception { + categoryDefinition.setName("Category&& &02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("category& &02"); // normalization + categoryDefinition.setName("Category& &02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraDash() throws Exception { + categoryDefinition.setName("CategorY-- --02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("CategorY- -02"); + categoryDefinition.setNormalizedName("category- -02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraPlus() throws Exception { + categoryDefinition.setName("CateGory++++ +02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("CateGory+ +02"); + categoryDefinition.setNormalizedName("category+ +02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraPeriod() throws Exception { + categoryDefinition.setName("Category.... .02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category. .02"); + categoryDefinition.setNormalizedName("category. .02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraApostrophe() throws Exception { + categoryDefinition.setName("CaTegory''' '02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("CaTegory' '02"); + categoryDefinition.setNormalizedName("category' '02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraHashtag() throws Exception { + categoryDefinition.setName("Category### #02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category# #02"); + categoryDefinition.setNormalizedName("category# #02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtrEequal() throws Exception { + categoryDefinition.setName("Category=== =02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category= =02"); + categoryDefinition.setNormalizedName("category= =02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtrColon() throws Exception { + categoryDefinition.setName("Category::: :02"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category: :02"); + categoryDefinition.setNormalizedName("category: :02"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtrAt() throws Exception { + categoryDefinition.setName("Category@@@ @a2"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category@ @a2"); + categoryDefinition.setNormalizedName("category@ @a2"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_RemoveExtraUnderscore() throws Exception { + categoryDefinition.setName("Category___ _22"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Category_ _22"); + categoryDefinition.setNormalizedName("category_ _22"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_FirstWordStartWithNumber() throws Exception { + categoryDefinition.setName("1Category one"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("1Category One"); + categoryDefinition.setNormalizedName("1category one"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_FirstWordStartWithNonAlphaNumeric() throws Exception { // The + // first + // word + // must + // start + // with + // an + // alpha-numeric + // character + // [a-Z + // A..Z, + // 0..9] + char invalidChars[] = { '&', '-', '+', '.', '\'', '#', '=', ':', '@', '_' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + categoryDefinition.setName(invalidChars[i] + "AbcD123"); + categoryDefinition.setNormalizedName((invalidChars[i] + "AbcD123").toLowerCase()); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, + sdncAdminUserDetails1, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createCategotyRest.getErrorCode().intValue()); + + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails1, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE, + "Service", "category"); + + } + } + + @Test + public void addServiceCategoryAlreadyExist_uniqueness() throws Exception { // Verify + // category + // name + // duplication + // ("uniqueness") + // as + // non-case-sensitive, + // so + // we + // don’t + // create + // duplicate + // names + // with + // upper/lower + // case + // inconsistency. + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); // also + // set + // catalog + // uniqeId + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + // Create same category name again + DbUtils.deleteFromEsDbByPattern("_all"); + CategoryDefinition categoryDataDefinition2 = new CategoryDefinition(); + categoryDataDefinition2.setName(categoryDefinition.getName()); + RestResponse addDuplicateCategoryRest = CategoryRestUtils.createCategory(categoryDataDefinition2, + sdncAdminUserDetails, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_ALREADY_EXISTS, + addDuplicateCategoryRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDataDefinition2, sdncAdminUserDetails, + ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, STATUS_CODE_ALREADY_EXISTS, AUDIT_SERVICE_TYPE, + "Service", categoryDefinition.getName()); + // Get Category and verify that category was created is not deleted + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + + } + + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_01() throws Exception { + categoryDefinition.setName("At and T"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("At & T"); + categoryDefinition.setNormalizedName("at & t"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_02() throws Exception { + categoryDefinition.setName("At and t"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("At & T"); + categoryDefinition.setNormalizedName("at & t"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_03() throws Exception { + categoryDefinition.setName("Atand T"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("atand t"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_04() throws Exception { + categoryDefinition.setName("At andT"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("at andt"); + categoryDefinition.setName("At AndT"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_05() throws Exception { + categoryDefinition.setName(" and AttT"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("and attt"); + categoryDefinition.setName("And AttT"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_06() throws Exception { + categoryDefinition.setName("AttT and "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("attt and"); + categoryDefinition.setName("AttT And"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + // Bug + @Test + public void categoryNameValidation_ReplaceAndWithAmpersand_07() throws Exception { + categoryDefinition.setName(" and a"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("and a"); + categoryDefinition.setName("And a"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationMaxLength() throws Exception { + categoryDefinition.setName("AsdfghjQ234567890@#.&:+-_"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("asdfghjq234567890@#.&:+-_"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + + } + + @Test + public void categoryNameValidationMaxLengthAfterNormalization() throws Exception { + categoryDefinition.setName(" A jQ234 @@@___ +++ At and T and and "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("A JQ234 @_ + At & T & And"); + categoryDefinition.setNormalizedName("a jq234 @_ + at & t & and"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + + } + + @Test + public void categoryNameValidationExceedMaxLengthAfterNormalization() throws Exception { + categoryDefinition.setName(" AbdfghBCVa jQ234 @@___ +++ At and T "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("abdfghbcva jq234 @_ + at&t"); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE, + "Service", "category"); + } + + @Test + public void categoryNameValidationMinLengthAfterNormalization() throws Exception { // MinLengthAfterNormalization + // = + // 4 + // characters + categoryDefinition.setName(" At and T "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("At & T"); + categoryDefinition.setNormalizedName("at & t"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationLessThanMinLengthAfterNormalization() throws Exception { + categoryDefinition.setName(" A&&&&&&&&&&&&&&&&&T "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName("a&t"); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE, + "Service", "category"); + } + + @Test + public void categoryNameValidationIsNull() throws Exception { + categoryDefinition.setName(null); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createCategotyRest.getErrorCode().intValue()); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE, + "Service", "category"); + } + + @Test + public void categoryNameValidationIsEmpty() throws Exception { + categoryDefinition.setName(""); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName(""); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE, + "Service", "category"); + } + + @Test + public void categoryNameValidationInvalidCharacters() throws Exception { + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', + '|', '\\', ',' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + // DbUtils.cleanAllAudits(); + categoryDefinition.setName("AbcD123" + invalidChars[i]); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setNormalizedName(""); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE, + "Service", "category"); + } + } + + @Test + public void categoryNameValidationSameNameDifferentResourceType() throws Exception { // same + // Catalog + // Name + // for + // service/resource/product + // is + // allowed + String name = ("Abcd"); + CategoryDefinition categoryDataDefinition1 = new CategoryDefinition(); + CategoryDefinition categoryDataDefinition2 = new CategoryDefinition(); + CategoryDefinition categoryDataDefinition3 = new CategoryDefinition(); + categoryDataDefinition1.setName(name); + categoryDataDefinition2.setName(name); + categoryDataDefinition3.setName(name); + // CREATE CATEGORY FOR SERVICE + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDataDefinition1, + sdncAdminUserDetails, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDataDefinition1.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDataDefinition1); + // get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDataDefinition1); // also + // set + // catalog + // uniqeId + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDataDefinition1, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + // CREATE CATEGORY FOR RESOURCE_COMPONENT_TYPE + DbUtils.deleteFromEsDbByPattern("_all"); + createCategotyRest = CategoryRestUtils.createCategory(categoryDataDefinition2, sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDataDefinition2.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDataDefinition2); + // Get Category + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDataDefinition2); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDataDefinition2, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + // CREATE CATEGORY FOR PRODUCT + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse addCategotyRest = CategoryRestUtils.createCategory(categoryDataDefinition3, + sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + addCategotyRest.getErrorCode().intValue()); + categoryDataDefinition3.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateCategoryResponse(addCategotyRest, categoryDataDefinition3); + + // Get Category + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDataDefinition3); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void categoryNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception { // First + // letter + // of + // key + // words + // are + // capitalized + categoryDefinition.setName("beNNy shaY michEl"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("BeNNy ShaY MichEl"); + categoryDefinition.setNormalizedName("benny shay michel"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_01() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" bank OF america "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Bank of America"); + categoryDefinition.setNormalizedName("bank of america"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_02() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName("THE america bank "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("THE America Bank"); + categoryDefinition.setNormalizedName("the america bank"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_03() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" A bank OF america "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("A Bank of America"); + categoryDefinition.setNormalizedName("a bank of america"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_04() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" bank america is A big ban "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Bank America Is a Big Ban"); + categoryDefinition.setNormalizedName("bank america is a big ban"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_05() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" aN apple comPany inC "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("AN Apple ComPany InC"); + categoryDefinition.setNormalizedName("an apple company inc"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_06() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" eat AN apple ANAN"); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Eat an Apple ANAN"); + categoryDefinition.setNormalizedName("eat an apple anan"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_07() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" united states OF americA "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("United States of AmericA"); + categoryDefinition.setNormalizedName("united states of america"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + // need to re-check + @Test + public void categoryNameValidationConjunctions_08() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" oF united states OF amer "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("OF United States of Amer"); + categoryDefinition.setNormalizedName("of united states of amer"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_09() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" to Apple TO at&T TOO "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("To Apple to At&T TOO"); + categoryDefinition.setNormalizedName("to apple to at&t too"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_10() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" eat apple AS you liiikeas "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Eat Apple as You Liiikeas"); + categoryDefinition.setNormalizedName("eat apple as you liiikeas"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_11() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" as you may want "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("As You May Want"); + categoryDefinition.setNormalizedName("as you may want"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void categoryNameValidationConjunctions_12() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" the bank OF america "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("The Bank of America"); + categoryDefinition.setNormalizedName("the bank of america"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + // need to recheck + @Test + public void categoryNameValidationConjunctions_13() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" To tel-toto "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("To Tel-toto"); + categoryDefinition.setNormalizedName("to tel-toto"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + // recheck + @Test + public void categoryNameValidationConjunctions_14() throws Exception { // Normalize + // the + // category + // name + // conjunctions + // ('of', + // 'to', + // 'for', + // 'as', + // 'a', + // 'an' + // , + // 'the') + // are + // lower + // case. + categoryDefinition.setName(" tel-aviv To la "); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_CREATED, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Tel-aviv to La"); + categoryDefinition.setNormalizedName("tel-aviv to la"); + CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition); + // Get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails, + STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE); + } + + @Test + public void createServiceCategoryHttpCspUserIdIsEmpty() throws Exception { + User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncAdminUserDetails1.setUserId(""); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Abcd"); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName()); + expectedCatrgoryAuditJavaObject.setSubCategoryName(""); + expectedCatrgoryAuditJavaObject.setGroupingName(""); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY); + } + + @Test + public void createServiceCategorHttpCspUserIdIsNull() throws Exception { + User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncAdminUserDetails1.setUserId(null); + RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createCategotyRest.getErrorCode().intValue()); + categoryDefinition.setName("Abcd"); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName()); + expectedCatrgoryAuditJavaObject.setSubCategoryName(""); + expectedCatrgoryAuditJavaObject.setGroupingName(""); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY); + } + + @Test + public void createSrvcCategoryHttpCspUserIdHeaderIsMissing() throws Exception { + RestResponse createConsumerRest = CategoryRestUtils + .createServiceCategoryHttpCspAtuUidIsMissing(categoryDefinition, sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createConsumerRest.getErrorCode().intValue()); + categoryDefinition.setName("Abcd"); + // get service category and validate that category was not added + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName()); + expectedCatrgoryAuditJavaObject.setSubCategoryName(""); + expectedCatrgoryAuditJavaObject.setGroupingName(""); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY); + } + + @Test + public void getServiceCategoryHierarchySuccessFlow() throws Exception { + + int numOfCategories = 3; + List categories = new ArrayList(); + RestResponse restResponse; + CategoryDefinition category; + String categoryName = categoryDefinition.getName(); + for (int i = 0; i < numOfCategories; i++) { + categoryDefinition.setName(categoryName + i); + restResponse = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + category = ResponseParser.parseToObject(restResponse.getResponse(), CategoryDefinition.class); + categories.add(category); + } + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + + AuditValidationUtils.GetCategoryHierarchyAuditSuccess(GET_CATEGORY_HIERARCHY, AUDIT_SERVICE_TYPE, + sdncAdminUserDetails, STATUS_CODE_SUCCESS); + for (CategoryDefinition categoryCurr : categories) { + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryCurr); + } + } + + ///////////////////////////////// US570520 ///////////////////////////////// + private List defineCategories() throws Exception { + String firstCategory = "FirstCategory"; + String secondCategory = "secondCategory"; + String thirdCategory = "ThirdCategory"; + String forthCategory = "forthCategory"; + CategoryDefinition category1 = new CategoryDefinition(categoryDefinition); + category1.setName(firstCategory); + CategoryDefinition category2 = new CategoryDefinition(categoryDefinition); + category2.setName(secondCategory); + CategoryDefinition category3 = new CategoryDefinition(categoryDefinition); + category3.setName(thirdCategory); + CategoryDefinition category4 = new CategoryDefinition(categoryDefinition); + category4.setName(forthCategory); + ArrayList categoryList = new ArrayList(); + categoryList.add(category1); + categoryList.add(category2); + categoryList.add(category3); + categoryList.add(category4); + return categoryList; + } + + @Test + public void getAllResourceCategoriesHirarchy() throws Exception { + createAndValidateCategoriesExist(RESOURCE_COMPONENT_TYPE, categoryList); + + for (int i = 0; i < categoryList.size(); i++) { + List subCategorieUniqueIdList = new ArrayList(); + for (int j = 0; j < subCategoryList.size(); j++) { + RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryList.get(j), + categoryList.get(i), sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + if (createSubCategory.getErrorCode().intValue() == STATUS_CODE_CREATED) { + String subCategoryUniqeId = ResponseParser.getUniqueIdFromResponse(createSubCategory); + subCategorieUniqueIdList.add(subCategoryUniqeId); + subCategoriesToDeleteMap.put(categoryList.get(i).getUniqueId(), subCategorieUniqueIdList); + } + } + } + + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + + for (int i = 0; i < categoryList.size(); i++) { + for (int j = 0; j < subCategoryList.size(); j++) { + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + categoryList.get(i).getUniqueId(), subCategoryList.get(j)); + } + } + + checkAuditSuccess(RESOURCE_COMPONENT_TYPE); + } + + private List defineSubCategories(int catListSize) { + List subCatList = new ArrayList(); + for (int j = 1; j <= catListSize; j++) { + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName("SubCategory" + String.valueOf(j)); + subCatList.add(subCategory); + } + return subCatList; + } + + private void createAndValidateCategoriesExist(String comp, List categoryList) throws Exception { + createCategories(comp, categoryList); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, comp); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + verifyCategoriesExist(categoryList, getAllCategoriesRest); + } + + private void verifyCategoriesExist(List categoryList, RestResponse getAllCategoriesRest) { + for (int i = 0; i < categoryList.size(); i++) { + categoryList.get(i).setName(WordUtils.capitalize(categoryList.get(i).getName())); + CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryList.get(i)); + } + } + + private void createCategories(String comp, List categoryList) throws Exception { + for (int i = 0; i < categoryList.size(); i++) { + CategoryRestUtils.createCategory(categoryList.get(i), sdncAdminUserDetails, comp); + } + } + + @Test + public void getAllServiceCategoriesHirarchy() throws Exception { + // deleteCategories(categoryList, SERVICE_COMPONENT_TYPE); + createAndValidateCategoriesExist(SERVICE_COMPONENT_TYPE, categoryList); + checkAuditSuccess(SERVICE_COMPONENT_TYPE); + // deleteCategories(categoryList, SERVICE_COMPONENT_TYPE); + } + + @Test + public void getAllResourceCategories_noAttUserHeader() throws Exception { + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(new User(), RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", 403, getAllCategoriesRest.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), + getAllCategoriesRest.getResponse()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY); + expectedCatrgoryAuditJavaObject.setModifierName(""); + expectedCatrgoryAuditJavaObject.setModifierUid(""); + expectedCatrgoryAuditJavaObject.setDetails(RESOURCE_COMPONENT_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY); + } + + @Test + public void getAllResourceCategories_userNotProvisioned() throws Exception { + User notProvisionedUser = new User(); + notProvisionedUser.setUserId("aa0001"); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(notProvisionedUser, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", 409, getAllCategoriesRest.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + getAllCategoriesRest.getResponse()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY); + expectedCatrgoryAuditJavaObject.setModifierName(""); + expectedCatrgoryAuditJavaObject.setModifierUid(notProvisionedUser.getUserId()); + expectedCatrgoryAuditJavaObject.setDetails(RESOURCE_COMPONENT_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_RESTRICTED_OPERATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY); + } + + @Test + public void getAllResourceCategories_unsupportedComponent() throws Exception { + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "comp"); + assertEquals("Check response code after get all categories hirarchy", 400, + getAllCategoriesRest.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), + new ArrayList(Arrays.asList("component type")), getAllCategoriesRest.getResponse()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.UNSUPPORTED_ERROR.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY); + expectedCatrgoryAuditJavaObject.setModifierUid(sdncAdminUserDetails.getUserId()); + expectedCatrgoryAuditJavaObject.setModifierName(sdncAdminUserDetails.getFullName()); + expectedCatrgoryAuditJavaObject.setDetails("comp"); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_INVALID_CONTENT)); + expectedCatrgoryAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, + new ArrayList(Arrays.asList("component type")))); + AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY); + } + + @Test(enabled = false) + public void getAllResourceCategories_emptyList() throws Exception { + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + JSONArray jArr = new JSONArray(getAllCategoriesRest.getResponse()); + assertTrue(jArr.length() == 0); + + checkAuditSuccess(RESOURCE_COMPONENT_TYPE); + } + + private void checkAuditSuccess(String componentType) throws Exception { + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY); + expectedCatrgoryAuditJavaObject.setModifierName(sdncAdminUserDetails.getFullName()); + expectedCatrgoryAuditJavaObject.setModifierUid(sdncAdminUserDetails.getUserId()); + expectedCatrgoryAuditJavaObject.setDetails(componentType); + expectedCatrgoryAuditJavaObject.setStatus("200"); + expectedCatrgoryAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY); + } + + @Test(enabled = false) + public void getAllServiceCategories_emptyList() throws Exception { + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + JSONArray jArr = new JSONArray(getAllCategoriesRest.getResponse()); + assertTrue(jArr.length() == 0); + + checkAuditSuccess(SERVICE_COMPONENT_TYPE); + } + + @Test(enabled = false) + public void getAllProductCategories_emptyList() throws Exception { + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + JSONArray jArr = new JSONArray(getAllCategoriesRest.getResponse()); + assertTrue(jArr.length() == 0); + + checkAuditSuccess(PRODUCT_COMPONENT_TYPE); + } + + // @Test + // public void getAllResourceCategories_generalError() throws Exception + // { + // User user = new User(); + // RestResponse getAllCategoriesRest = + // CategoryRestUtils.getAllCategories(user, SERVICE_COMPONENT_TYPE); + // assertEquals("Check response code after get Category", 500, + // getAllCategoriesRest.getErrorCode().intValue()); + // Utils.checkBodyResponseOnError(ActionStatus.GENERAL_ERROR.name(), new + // ArrayList(), getAllCategoriesRest.getResponse()); + // } + + ////////////////////////////////////////////////////////////////////////////// + + @Test + public void importCategories() throws Exception { + + String importResourceDir = config.getImportTypesConfigDir() + File.separator + "categoryTypesTest.zip"; + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("categoriesZip", new FileBody(new File(importResourceDir))); + + RestResponse importResult = CategoryRestUtils.importCategories(mpBuilder, sdncAdminUserDetails.getUserId()); + assertEquals("Check response code after Import", BaseRestUtils.STATUS_CODE_CREATED, + importResult.getErrorCode().intValue()); + + Map map = ResponseParser.parseToObjectUsingMapper(importResult.getResponse(), Map.class); + assertEquals("Check entries count", 2, map.size()); + + List> resources = (List>) map.get("resources"); + assertEquals("Check resource category entries count", 1, resources.size()); + + List> services = (List>) map.get("services"); + assertEquals("Check resource category entries count", 2, services.size()); + + RestResponse allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "resources"); + List resourceCategories = ResponseParser.parseCategories(allCategories); + for (Map resource : resources) { + boolean exist = false; + + for (CategoryDefinition categ : resourceCategories) { + if (categ.getName().equals(resource.get("name"))) { + exist = true; + break; + } + } + assertTrue("Check existance resource category " + resource.get("name"), exist); + } + + allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "services"); + List servicesCategories = ResponseParser.parseCategories(allCategories); + for (Map service : services) { + boolean exist = false; + + for (CategoryDefinition categ : servicesCategories) { + if (categ.getName().equals(service.get("name"))) { + exist = true; + break; + } + } + assertTrue("Check existance service category " + service.get("name"), exist); + } + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java new file mode 100644 index 0000000000..2f48f4fa1e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java @@ -0,0 +1,148 @@ +/*- + * ============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.ci.tests.execute.category; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +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.ci.tests.api.ComponentBaseTest; +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.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.testng.annotations.Test; + +public class ElementsApiTest extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public ElementsApiTest() { + super(name, ElementsApiTest.class.getName()); + } + + // public LCSbaseTest(TestName testName, String className) { + // super(testName, className); + // } + + // public ElementsApiTest(TestName name, String name2) { + //// super(name, name2); + // // TODO Auto-generated constructor stub + // } + + // Expected 200 Keep + @Test + public void getAllPropertyScopesSuccess() throws Exception { + RestResponse response = ResourceRestUtils.getAllPropertyScopesTowardsCatalogBe(); + String action = "Get All Property Scopes"; + int expectedCode = 200; + verifyErrorCode(response, action, expectedCode); + } + + // Expected 200 Keep + @Test + public void getAllArtifactTypes() throws Exception { + RestResponse response = ResourceRestUtils.getAllArtifactTypesTowardsCatalogBe(); + String action = "Get All Artifact Types"; + int expectedCode = 200; + verifyErrorCode(response, action, expectedCode); + } + + // Expected 200 Keep + @Test + public void getConfiguration() throws Exception { + RestResponse response = ResourceRestUtils.getConfigurationTowardsCatalogBe(); + String action = "Get All Artifact Types"; + int expectedCode = 200; + + String json = response.getResponse(); + JSONObject jsonResp = (JSONObject) JSONValue.parse(json); + + HashMap artifacts = (HashMap) jsonResp.get("artifacts"); + Long defaultHeatTimeout = (Long) jsonResp.get("defaultHeatTimeout"); + + if (defaultHeatTimeout == null) { + response.setErrorCode(500); + verifyErrorCode(response, action, expectedCode); + return; + } + + if (artifacts == null) { + response.setErrorCode(500); + verifyErrorCode(response, action, expectedCode); + return; + } + + JSONObject deploymentResources = (JSONObject) artifacts.get("deployment"); + JSONArray otherResources = (JSONArray) artifacts.get("other"); + if (deploymentResources == null || otherResources == null) { + response.setErrorCode(500); + verifyErrorCode(response, action, expectedCode); + return; + } + + JSONArray roles = (JSONArray) jsonResp.get("roles"); + if (roles == null) { + response.setErrorCode(500); + verifyErrorCode(response, action, expectedCode); + return; + } + + } + + public void verifyErrorCode(RestResponse response, String action, int expectedCode) { + assertNotNull("check response object is not null after " + action, response); + assertNotNull("check error code exists in response after " + action, response.getErrorCode()); + assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue()); + } + + @Test(enabled = false) + public void getAllCategoriesSuccess() throws Exception { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + RestResponse response = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + String action = "Get All Categories"; + int expectedCode = 200; + verifyErrorCode(response, action, expectedCode); + } + + @Test(enabled = false) + public void getAllTagSuccess() throws Exception { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + RestResponse response = ResourceRestUtils.getAllTagsTowardsCatalogBe(); + String action = "Get All Categories"; + int expectedCode = 200; + verifyErrorCode(response, action, expectedCode); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java new file mode 100644 index 0000000000..f6b6113b99 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java @@ -0,0 +1,2007 @@ +/*- + * ============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.ci.tests.execute.category; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.RESOURCE_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.SERVICE_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.CategoryValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.SkipException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class GroupingTest extends CategoriesBaseTest { + + protected static final String ADD_GROUPING = "AddGrouping"; + protected static final String CATEGORY = "category"; + protected static final String SUB_CATEGORY = "sub-category"; + protected static final String GROUPING = "grouping"; + + public GroupingTest() { + super(name, GroupingTest.class.getName()); + } + + @Rule + public static TestName name = new TestName(); + + private CategoryDefinition productCategoryDefinition; + private CategoryDefinition productCategoryDefinition2; + + private SubCategoryDefinition productSubCategoryDefinition; + private SubCategoryDefinition productSubCategoryDefinition2; + private SubCategoryDefinition productSubCategoryDefinition3; + + private GroupingDefinition productGroupingDefinition; + private GroupingDefinition productGroupingDefinition2; + private GroupingDefinition productGroupingDefinition3; + + @BeforeMethod + public void init() throws Exception { + + // Category setup + productCategoryDefinition = new CategoryDefinition(); + productCategoryDefinition.setName("Category1"); + productCategoryDefinition2 = new CategoryDefinition(); + productCategoryDefinition2.setName("Category2"); + + // Subcategory setup + productSubCategoryDefinition = new SubCategoryDefinition(); + productSubCategoryDefinition.setName("SubCategory1"); + + productSubCategoryDefinition2 = new SubCategoryDefinition(); + productSubCategoryDefinition2.setName("SubCategory2"); + + productSubCategoryDefinition3 = new SubCategoryDefinition(); + productSubCategoryDefinition3.setName("SubCategory1"); + + // Group setup + productGroupingDefinition = new GroupingDefinition(); + productGroupingDefinition.setName("Grouping1"); + + productGroupingDefinition2 = new GroupingDefinition(); + productGroupingDefinition2.setName("Grouping2"); + + productGroupingDefinition3 = new GroupingDefinition(); + productGroupingDefinition3.setName("Grouping1"); + + // Init product category + RestResponse createCategory = CategoryRestUtils.createCategory(productCategoryDefinition, + sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + CategoryDefinition category = ResponseParser.parseToObject(createCategory.getResponse(), + CategoryDefinition.class); + assertEquals("Check category name after creating category ", productCategoryDefinition.getName(), + category.getName()); + productCategoryDefinition = category; + + // Init product category1 + createCategory = CategoryRestUtils.createCategory(productCategoryDefinition2, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class); + assertEquals("Check category name after creating category ", productCategoryDefinition2.getName(), + category.getName()); + productCategoryDefinition2 = category; + + // Init product productSubCategoryDefinition to + // productCategoryDefinition + RestResponse createSubCategory = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createSubCategory.getErrorCode().intValue()); + SubCategoryDefinition subCategory = ResponseParser.parseToObject(createSubCategory.getResponse(), + SubCategoryDefinition.class); + assertEquals("Check category name after creating category ", productSubCategoryDefinition.getName(), + subCategory.getName()); + productSubCategoryDefinition = subCategory; + productCategoryDefinition.addSubCategory(productSubCategoryDefinition); + + // Init product productSubCategoryDefinition1 to + // productCategoryDefinition + createSubCategory = CategoryRestUtils.createSubCategory(productSubCategoryDefinition2, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createSubCategory.getErrorCode().intValue()); + subCategory = ResponseParser.parseToObject(createSubCategory.getResponse(), SubCategoryDefinition.class); + assertEquals("Check category name after creating category ", productSubCategoryDefinition2.getName(), + subCategory.getName()); + productSubCategoryDefinition2 = subCategory; + productCategoryDefinition.addSubCategory(productSubCategoryDefinition2); + + // Init product productSubCategoryDefinition3 to + // productCategoryDefinition2 + createSubCategory = CategoryRestUtils.createSubCategory(productSubCategoryDefinition3, + productCategoryDefinition2, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createSubCategory.getErrorCode().intValue()); + subCategory = ResponseParser.parseToObject(createSubCategory.getResponse(), SubCategoryDefinition.class); + assertEquals("Check category name after creating category ", productSubCategoryDefinition3.getName(), + subCategory.getName()); + productSubCategoryDefinition3 = subCategory; + productCategoryDefinition2.addSubCategory(productSubCategoryDefinition3); + } + + @Test + public void createProductGroupCategorySuccess() throws Exception { + createGroupingSuccess(productGroupingDefinition, productSubCategoryDefinition, productCategoryDefinition, + sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE, AUDIT_PRODUCT_TYPE); + } + + private void createGroupingSuccess(GroupingDefinition groupingDefinition, + SubCategoryDefinition subCategoryDefinition, CategoryDefinition categoryDefinition, + User sdncProductStrategistUserDetails, String productComponentType, String auditType) throws Exception { + + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition, subCategoryDefinition, + categoryDefinition, sdncProductStrategistUserDetails, productComponentType); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("grouping1"); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + productComponentType); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, categoryDefinition.getUniqueId(), + subCategoryDefinition.getUniqueId(), groupingDefinition); + + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, categoryDefinition, subCategoryDefinition, + groupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, auditType); + } + + //// Benny + + @Test + public void createProductGroupByProductStrategist() throws Exception { + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("grouping1"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void createProductGroupAlreadyExistInSameCategorySubCategory() throws Exception { + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("grouping1"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + // Create Same Group already exist on same Category/SubCategory + DbUtils.deleteFromEsDbByPattern("_all"); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_ALREADY_EXISTS, + createGroupingRest.getErrorCode().intValue()); + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, STATUS_CODE_ALREADY_EXISTS, AUDIT_PRODUCT_TYPE, + AUDIT_PRODUCT_TYPE, productGroupingDefinition.getName(), productSubCategoryDefinition.getName()); + } + + @Test + public void createProductGroupUnderSameCategoryButDifferentSubCategory() throws Exception { + // Setting : Category-A, Sub-category-B , group : aBcd (display-Name : + // ABcd, normalized: abcd)  [A, B, ABcd] + // Action : Category-A, Sub-category-C, group : abcD (display-Name : + // ABcd, normalized: abcd)  [A, C, ABcd] + productGroupingDefinition.setName("ABCd"); + productGroupingDefinition2.setName("abcD"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + DbUtils.deleteFromEsDbByPattern("_all"); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition2, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition2.setName("ABCd"); + productGroupingDefinition2.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, + productSubCategoryDefinition2, productGroupingDefinition2, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition2.getUniqueId(), + productGroupingDefinition2); + } + + @Test + public void createProductGroupUnderSameSubCategoryButDifferentCategory() throws Exception { + // Setting : Category-A, Sub-category-B , group : aBcd (display-Name : + // ABcd, normalized: abcd)  [A, B, ABcd] + // : Category-A, Sub-category-C, group : abcD (display-Name : ABcd, + // normalized: abcd)  [A, C, ABcd] + // : Category-K, Sub-category-B, group : abcD (display-Name : ABcd, + // normalized: abcd)  [K, B, ABcd] + productGroupingDefinition.setName("ABCd"); + productGroupingDefinition2.setName("abcD"); + productGroupingDefinition3.setName("aBCd"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + DbUtils.deleteFromEsDbByPattern("_all"); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition2, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition2.setName("ABCd"); + productGroupingDefinition2.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, + productSubCategoryDefinition2, productGroupingDefinition2, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + DbUtils.deleteFromEsDbByPattern("_all"); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition3, productSubCategoryDefinition3, + productCategoryDefinition2, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition3.setName("ABCd"); + productGroupingDefinition3.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition3); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition2, + productSubCategoryDefinition3, productGroupingDefinition3, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition2.getUniqueId(), + productGroupingDefinition2); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition2.getUniqueId(), productSubCategoryDefinition3.getUniqueId(), + productGroupingDefinition3); + + } + + @Test + public void createProductGroupsOnSameCategorySubCategory() throws Exception { + // Setting : Category-A, Sub-category-B , group : ABcd (display-Name : + // ABcd, normalized: abcd) [A ,B, ABcd] + // Action : Category-A, Sub-category-B, group : ZXcv (display-Name : + // ZXcv, normalized: zxcv) [A, B, ZXcv] + productGroupingDefinition.setName("ABcd"); + productGroupingDefinition2.setName("ZXcv"); + productGroupingDefinition2.setNormalizedName("zxcv"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + DbUtils.deleteFromEsDbByPattern("_all"); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition2, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition2); + } + + @Test + public void createProductGroupUnderDifferentCategory() throws Exception { + // Setting : Category-A, Sub-category-B , group : aBcd (display-Name : + // ABcd, normalized: abcd) [A ,B, ABcd] + // Action : Category-K, Sub-category-B, group : abcD (display-Name : + // ABcd, normalized: abcd) [K, B, ABcd] + // productGroupingDefinition.setName("ABCd"); + productGroupingDefinition.setName("ABcD"); + productGroupingDefinition2.setName("abcD"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("abcd"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + DbUtils.deleteFromEsDbByPattern("_all"); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition3, + productCategoryDefinition2, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition2.setNormalizedName("abcd"); + productGroupingDefinition2.setName("ABcD"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2); + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition2, + productSubCategoryDefinition3, productGroupingDefinition2, sdncProductStrategistUserDetails, + STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition2.getUniqueId(), productSubCategoryDefinition3.getUniqueId(), + productGroupingDefinition2); + } + + /////////// + @Test + public void createProductGroupByNonProductStrategist() throws Exception { + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_RESTRICTED_OPERATION, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId()); + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncAdminUserDetails, ActionStatus.RESTRICTED_OPERATION, + STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE); + } + + // @Ignore("DE176245") + @Test + public void createProductGroupForNonExistingComponentType() throws Exception { + String nonSupportedComponentType = "NonExistingComponentType"; // instead + // resource/product + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + nonSupportedComponentType); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId()); + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, nonSupportedComponentType); + } + + // @Ignore("DE176245") + @Test + public void createResourceGroup() throws Exception { + // Resource doesn't have group + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId()); + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE); + } + + // @Ignore("DE176245") + @Test + public void createServiceGroup() throws Exception { + // Service doesn't have group + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId()); + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE); + } + + @Test + public void createProductGroupForNonExistingCategory() throws Exception { + + CategoryDefinition productCategoryDefinition100 = new CategoryDefinition(); + productCategoryDefinition100.setName("category.nonexistingCategory"); + productCategoryDefinition100.setUniqueId("category.nonexistingCategory"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition100, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_NOT_FOUND, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId()); + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition100, + productSubCategoryDefinition, productGroupingDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, STATUS_CODE_NOT_FOUND, AUDIT_PRODUCT_TYPE, + PRODUCT_COMPONENT_TYPE, CATEGORY, ""); + } + + @Test + public void createProductGroupForNonExistingSunCategory() throws Exception { + throw new SkipException( + "Skipping - failed in audit validation expected \"products\" actual result was \"product\" "); + // SubCategoryDefinition productSubCategoryDefinition100 = new + // SubCategoryDefinition(); + // productSubCategoryDefinition100.setUniqueId("category.nonexistingSubCategory"); + // RestResponse createGroupingRest = + // CategoryRestUtils.createGrouping(productGroupingDefinition, + // productSubCategoryDefinition100, productCategoryDefinition, + // sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + // assertEquals("Check response code after create Sub category", + // STATUS_CODE_NOT_FOUND, createGroupingRest.getErrorCode().intValue()); + // RestResponse getAllCategoriesRest = + // CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + // PRODUCT_COMPONENT_TYPE); + // assertEquals("Check response code after get all categories ", + // STATUS_CODE_SUCCESS, getAllCategoriesRest.getErrorCode().intValue()); + // CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + // productCategoryDefinition.getUniqueId(), + // productSubCategoryDefinition.getUniqueId(), + // productGroupingDefinition); + // //Audit validation + // productSubCategoryDefinition100.setName(productSubCategoryDefinition100.getUniqueId()); + // AuditValidationUtils.groupingAuditFailure(ADD_GROUPING , + // productCategoryDefinition, productSubCategoryDefinition100, + // productGroupingDefinition, sdncProductStrategistUserDetails, + // ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, + // STATUS_CODE_NOT_FOUND,AUDIT_PRODUCT_TYPE, PRODUCT_COMPONENT_TYPE, + // SUB_CATEGORY, ""); + } + + @Test + public void ProductGroupAllowedcharacters_01() throws Exception { + productGroupingDefinition.setName("1234AbcdE-"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde-"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_02() throws Exception { + productGroupingDefinition.setName("1234AbcdE+"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde+"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_03() throws Exception { + productGroupingDefinition.setName("1234AbcdE&"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde&"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_04() throws Exception { + productGroupingDefinition.setName("1234AbcdE-"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde-"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_05() throws Exception { + productGroupingDefinition.setName("1234AbcdE+"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde+"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_06() throws Exception { + productGroupingDefinition.setName("1234AbcdE."); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde."); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_07() throws Exception { + productGroupingDefinition.setName("1234AbcdE'"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde'"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_08() throws Exception { + productGroupingDefinition.setName("1234AbcdE="); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde="); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_09() throws Exception { + productGroupingDefinition.setName("1234AbcdE:"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde:"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_10() throws Exception { + productGroupingDefinition.setName("1234AbcdE@"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde@"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_11() throws Exception { + productGroupingDefinition.setName("1234AbcdE_"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde_"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_12() throws Exception { + productGroupingDefinition.setName("1234AbcdE#"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("1234abcde#"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void ProductGroupAllowedcharacters_13() throws Exception { + productGroupingDefinition.setName("1234AbcdE d"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("1234AbcdE D"); + productGroupingDefinition.setNormalizedName("1234abcde d"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveSpaceFromBeginning() throws Exception { + productGroupingDefinition.setName(" Category01"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("category01"); + productGroupingDefinition.setName("Category01"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveSpaceFromEnd() throws Exception { + productGroupingDefinition.setName("Category01 "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("category01"); + productGroupingDefinition.setName("Category01"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraSpace() throws Exception { + productGroupingDefinition.setName("Category 02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("category 02"); + productGroupingDefinition.setName("Category 02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraAmpersand() throws Exception { + productGroupingDefinition.setName("Category&& &02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("category& &02"); + productGroupingDefinition.setName("Category& &02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraDash() throws Exception { + productGroupingDefinition.setName("CategorY-- --02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("category- -02"); + productGroupingDefinition.setName("CategorY- -02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraPlus() throws Exception { + productGroupingDefinition.setName("CateGory++++ +02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("CateGory+ +02"); + productGroupingDefinition.setNormalizedName("category+ +02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraPeriod() throws Exception { + productGroupingDefinition.setName("Category.... .02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Category. .02"); + productGroupingDefinition.setNormalizedName("category. .02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraApostrophe() throws Exception { + productGroupingDefinition.setName("CaTegory''' '02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("CaTegory' '02"); + productGroupingDefinition.setNormalizedName("category' '02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraHashtag() throws Exception { + productGroupingDefinition.setName("Category### #02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Category# #02"); + productGroupingDefinition.setNormalizedName("category# #02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtrEequal() throws Exception { + productGroupingDefinition.setName("Category=== =02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Category= =02"); + productGroupingDefinition.setNormalizedName("category= =02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtrColon() throws Exception { + productGroupingDefinition.setName("Category::: :02"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Category: :02"); + productGroupingDefinition.setNormalizedName("category: :02"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtrAt() throws Exception { + productGroupingDefinition.setName("Category@@@ @a2"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Category@ @a2"); + productGroupingDefinition.setNormalizedName("category@ @a2"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_RemoveExtraUnderscore() throws Exception { + productGroupingDefinition.setName("Category___ _22"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Category_ _22"); + productGroupingDefinition.setNormalizedName("category_ _22"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_FirstWordStartWithNumber() throws Exception { + productGroupingDefinition.setName("1Category one"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("1Category One"); + productGroupingDefinition.setNormalizedName("1category one"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_FirstWordStartWithNonAlphaNumeric() throws Exception { // The + // first + // word + // must + // start + // with + // an + // alpha-numeric + // character + // [a-Z + // A..Z, + // 0..9] + char invalidChars[] = { '&', '-', '+', '.', '\'', '#', '=', ':', '@', '_' }; + RestResponse createGroupingRest; + RestResponse getAllCategoriesRest; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + productGroupingDefinition.setName(invalidChars[i] + "AbcD123"); + productGroupingDefinition.setNormalizedName((invalidChars[i] + "AbcD123").toLowerCase()); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + } + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_01() throws Exception { + productGroupingDefinition.setName("At and T"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("At & T"); + productGroupingDefinition.setNormalizedName("at & t"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_02() throws Exception { + productGroupingDefinition.setName("At and t"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("At & T"); + productGroupingDefinition.setNormalizedName("at & t"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_03() throws Exception { + productGroupingDefinition.setName("Atand T"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("atand t"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_04() throws Exception { + productGroupingDefinition.setName("At andT"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("at andt"); + productGroupingDefinition.setName("At AndT"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_05() throws Exception { + productGroupingDefinition.setName(" and AttT"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("and attt"); + productGroupingDefinition.setName("And AttT"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_06() throws Exception { + productGroupingDefinition.setName("AttT and "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("attt and"); + productGroupingDefinition.setName("AttT And"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidation_ReplaceAndWithAmpersand_07() throws Exception { + productGroupingDefinition.setName(" and a"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("and a"); + productGroupingDefinition.setName("And a"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationMaxLength() throws Exception { + productGroupingDefinition.setName("AsdfghjQ234567890@#.&:+-_"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("asdfghjq234567890@#.&:+-_"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationMaxLengthAfterNormalization() throws Exception { + productGroupingDefinition.setName(" A jQ234 @@@___ +++ At and T and and "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("a jq234 @_ + at & t & and"); + productGroupingDefinition.setName("A JQ234 @_ + At & T & And"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationExceedMaxLengthAfterNormalization() throws Exception { + productGroupingDefinition.setName(" AbdfghBCVa jQ234 @@___ +++ At and T "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("abdfghbcva jq234 @_ + at&t"); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE, + AUDIT_PRODUCT_TYPE, GROUPING); + } + + @Test + public void groupNameValidationMinLengthAfterNormalization() throws Exception { + productGroupingDefinition.setName(" At&&&&&&&&&&&&t "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("at&t"); + productGroupingDefinition.setName("At&t"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationLessThanMinLengthAfterNormalization() throws Exception { + productGroupingDefinition.setName(" A&&&&&&&&&&&&T "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("a&t"); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE, + AUDIT_PRODUCT_TYPE, GROUPING); + } + + @Test + public void groupNameValidationIsEmpty() throws Exception { + productGroupingDefinition.setName(""); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName(""); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE, + AUDIT_PRODUCT_TYPE, GROUPING); + } + + @Test + public void groupNameValidationInvalidCharacters() throws Exception { + RestResponse createGroupingRest; + RestResponse getAllCategoriesRest; + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', + '|', '\\', ',' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + productGroupingDefinition.setName("AbcD123" + invalidChars[i]); + createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName(""); + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, + productSubCategoryDefinition, productGroupingDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE, + AUDIT_PRODUCT_TYPE, GROUPING); + } + } + + @Test + public void groupNameValidationConjunctions_01() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" bank OF america "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setNormalizedName("bank of america"); + productGroupingDefinition.setName("Bank of America"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_02() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName("THE america bank "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("THE America Bank"); + productGroupingDefinition.setNormalizedName("the america bank"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_03() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" A bank OF america "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("A Bank of America"); + productGroupingDefinition.setNormalizedName("a bank of america"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_04() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" bank america is A big ban "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Bank America Is a Big Ban"); + productGroupingDefinition.setNormalizedName("bank america is a big ban"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_05() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" aN apple comPany inC "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("AN Apple ComPany InC"); + productGroupingDefinition.setNormalizedName("an apple company inc"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_06() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" eat AN apple ANAN"); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Eat an Apple ANAN"); + productGroupingDefinition.setNormalizedName("eat an apple anan"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_07() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" united states OF americA "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("United States of AmericA"); + productGroupingDefinition.setNormalizedName("united states of america"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_08() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" oF united states OF amer "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("OF United States of Amer"); + productGroupingDefinition.setNormalizedName("of united states of amer"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_09() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" to Apple TO at&T TOO "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("To Apple to At&T TOO"); + productGroupingDefinition.setNormalizedName("to apple to at&t too"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_10() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" eat apple AS you liiikeas "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Eat Apple as You Liiikeas"); + productGroupingDefinition.setNormalizedName("eat apple as you liiikeas"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_11() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" as you may want "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("As You May Want"); + productGroupingDefinition.setNormalizedName("as you may want"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_12() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" the bank OF america "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("The Bank of America"); + productGroupingDefinition.setNormalizedName("the bank of america"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_13() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" To tel-toto "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("To Tel-toto"); + productGroupingDefinition.setNormalizedName("to tel-toto"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void groupNameValidationConjunctions_14() throws Exception { + // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as', + // 'a', 'an' , 'the') are lower case. + productGroupingDefinition.setName(" tel-aviv To la "); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create product group", STATUS_CODE_CREATED, + createGroupingRest.getErrorCode().intValue()); + productGroupingDefinition.setName("Tel-aviv to La"); + productGroupingDefinition.setNormalizedName("tel-aviv to la"); + CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition, + productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE); + } + + @Test + public void createProductGroupHttpCspUserIdIsEmpty() throws Exception { + User sdncPS = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + sdncPS.setUserId(""); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncPS, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_GROUPING); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(productCategoryDefinition.getUniqueId()); + expectedCatrgoryAuditJavaObject.setSubCategoryName(productSubCategoryDefinition.getUniqueId()); + expectedCatrgoryAuditJavaObject.setGroupingName(productGroupingDefinition.getName()); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_PRODUCT_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_GROUPING); + } + + @Test + public void createProductGroupHttpCspUserIdIsNull() throws Exception { + User sdncPS = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + sdncPS.setUserId(null); + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, + productSubCategoryDefinition, productCategoryDefinition, sdncPS, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createGroupingRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(), + productGroupingDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_GROUPING); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(productCategoryDefinition.getUniqueId()); + expectedCatrgoryAuditJavaObject.setSubCategoryName(productSubCategoryDefinition.getUniqueId()); + expectedCatrgoryAuditJavaObject.setGroupingName(productGroupingDefinition.getName()); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_PRODUCT_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_GROUPING); + } + + //////////////////////////////////////////////// + /////////////////////////////////////////////// + @Test + public void getProductCategoryHierarchySuccessFlow() throws Exception { + throw new SkipException( + "Skipping - failed in audit validation expected \"products\" actual result was \"product\" "); + // int numOfGrouping = 3; + // List groupingList = new ArrayList<>(); + // RestResponse restResponse; + // GroupingDefinition grouping; + // String groupingName = productGroupingDefinition.getName(); + // for (int i = 0; i < numOfGrouping; i++) { + // productGroupingDefinition.setName(groupingName+i); + // restResponse = + // CategoryRestUtils.createGrouping(productGroupingDefinition, + // productSubCategoryDefinition, productCategoryDefinition, + // sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + // grouping = ResponseParser.parseToObject(restResponse.getResponse(), + // GroupingDefinition.class); + // groupingList.add(grouping); + // } + // RestResponse getAllCategoriesRest = + // CategoryRestUtils.getAllCategories(sdncProductStrategistUserDetails, + // PRODUCT_COMPONENT_TYPE); + // assertEquals("Check response code after get all categories ", + // STATUS_CODE_SUCCESS, getAllCategoriesRest.getErrorCode().intValue()); + // AuditValidationUtils.GetCategoryHierarchyAuditSuccess(GET_CATEGORY_HIERARCHY, + // AUDIT_PRODUCT_TYPE, sdncProductStrategistUserDetails, + // STATUS_CODE_SUCCESS); + // + // for (GroupingDefinition group : groupingList) { + // CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, + // productCategoryDefinition.getUniqueId(), + // productSubCategoryDefinition.getUniqueId(), group); + // } + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java new file mode 100644 index 0000000000..dcc3172d59 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java @@ -0,0 +1,1908 @@ +/*- + * ============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.ci.tests.execute.category; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.RESOURCE_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.SERVICE_COMPONENT_TYPE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.CategoryValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class SubCategoriesTest extends ComponentBaseTest { + + protected static final String ADD_SUB_CATEGORY = "AddSubCategory"; + protected static final String CATEGORY = "category"; + protected static final String SUB_CATEGORY = "sub-category"; + + protected static final String AUDIT_SERVICE_TYPE = "Service"; + protected static final String AUDIT_RESOURCE_TYPE = "Resource"; + protected static final String AUDIT_PRODUCT_TYPE = "Product"; + protected static final String GET_CATEGORY_HIERARCHY = "GetCategoryHierarchy"; + protected static User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + protected static User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + protected static User sdncDesignerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + protected static User sdncTesterUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + protected static User sdncGovernorUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + protected static User sdncOpsUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + protected static User sdncProductManagerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + protected static User sdncProductStrategistUserDetails = ElementFactory + .getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + + public SubCategoriesTest() { + super(name, SubCategoriesTest.class.getName()); + } + + @Rule + public static TestName name = new TestName(); + + private CategoryDefinition resourceCategoryDefinition; + private CategoryDefinition resourceCategoryDefinition1; + private CategoryDefinition serviceCategoryDefinition; + private CategoryDefinition productCategoryDefinition; + private CategoryDefinition productCategoryDefinition1; + private CategoryDefinition resourceCategoryDefinition100; + private CategoryDefinition productCategoryDefinition200; + + private SubCategoryDefinition resourceSubCategoryDefinition; + private SubCategoryDefinition resourceSubCategoryDefinition1; + private SubCategoryDefinition serviceSubCategoryDefinition; + private SubCategoryDefinition productSubCategoryDefinition; + private SubCategoryDefinition productSubCategoryDefinition1; + + @BeforeMethod + public void init() throws Exception { + + // Category setup + resourceCategoryDefinition = new CategoryDefinition(); + resourceCategoryDefinition1 = new CategoryDefinition(); + serviceCategoryDefinition = new CategoryDefinition(); + productCategoryDefinition = new CategoryDefinition(); + productCategoryDefinition1 = new CategoryDefinition(); + resourceCategoryDefinition100 = new CategoryDefinition(); // for + // negative + // tests + productCategoryDefinition200 = new CategoryDefinition(); // for negative + // tests + + resourceCategoryDefinition.setName("Category1"); + resourceCategoryDefinition1.setName("Category2"); + serviceCategoryDefinition.setName("Category1"); + productCategoryDefinition.setName("Category2"); + productCategoryDefinition1.setName("Category3"); + resourceCategoryDefinition100.setName("Category100"); + productCategoryDefinition200.setName("Category100"); + + // Subcategory setup + resourceSubCategoryDefinition = new SubCategoryDefinition(); + resourceSubCategoryDefinition1 = new SubCategoryDefinition(); + serviceSubCategoryDefinition = new SubCategoryDefinition(); + productSubCategoryDefinition = new SubCategoryDefinition(); + productSubCategoryDefinition1 = new SubCategoryDefinition(); + + resourceSubCategoryDefinition.setName("Resource-subcat"); + // Service sub - for negative testing since it's not allowed + serviceSubCategoryDefinition.setName("Service-subcat"); + productSubCategoryDefinition.setName("Product-subcat"); + + // Init resource category + RestResponse createCategory = CategoryRestUtils.createCategory(resourceCategoryDefinition, sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + CategoryDefinition category = ResponseParser.parseToObject(createCategory.getResponse(), + CategoryDefinition.class); + assertEquals("Check category name after creating category ", resourceCategoryDefinition.getName(), + category.getName()); + resourceCategoryDefinition = category; + + // Init resource category1 + createCategory = CategoryRestUtils.createCategory(resourceCategoryDefinition1, sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class); + assertEquals("Check category name after creating category ", resourceCategoryDefinition1.getName(), + category.getName()); + resourceCategoryDefinition1 = category; + + // Init service category + createCategory = CategoryRestUtils.createCategory(serviceCategoryDefinition, sdncAdminUserDetails, + SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class); + assertEquals("Check category name after creating category ", serviceCategoryDefinition.getName(), + category.getName()); + serviceCategoryDefinition = category; + + // Init product category + createCategory = CategoryRestUtils.createCategory(productCategoryDefinition, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class); + assertEquals("Check category name after creating category ", productCategoryDefinition.getName(), + category.getName()); + productCategoryDefinition = category; + + // Init product category1 + createCategory = CategoryRestUtils.createCategory(productCategoryDefinition1, sdncProductStrategistUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create category", STATUS_CODE_CREATED, + createCategory.getErrorCode().intValue()); + category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class); + assertEquals("Check category name after creating category ", productCategoryDefinition1.getName(), + category.getName()); + productCategoryDefinition1 = category; + + } + + @Test + public void createResourceSubCategorySuccess() throws Exception { + createSubCategorySuccess(resourceCategoryDefinition, resourceSubCategoryDefinition, sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE, AUDIT_RESOURCE_TYPE); + } + + @Test + public void createProductSubCategorySuccess() throws Exception { + createSubCategorySuccess(productCategoryDefinition, productSubCategoryDefinition, + sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE, AUDIT_PRODUCT_TYPE); + } + + @Test + public void createProductSubCategoryTwoCategoriesCaseInsensitive() throws Exception { + String componentType = PRODUCT_COMPONENT_TYPE; + String auditType = AUDIT_PRODUCT_TYPE; + User user = sdncProductStrategistUserDetails; + // Create product sub Category2-->Product-subcat + createSubCategorySuccess(productCategoryDefinition, productSubCategoryDefinition, user, componentType, + auditType); + DbUtils.deleteFromEsDbByPattern("_all"); + + // Create product sub Category3-->PRoDUCT-SUBcat + // Should be created Category3-->Product-subcat + productSubCategoryDefinition1.setName("PRoDUCT-SUBcat"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition1, + productCategoryDefinition1, user, componentType); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(user, componentType); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + productSubCategoryDefinition1.setName(productSubCategoryDefinition.getName()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition1.getUniqueId(), productSubCategoryDefinition1); + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition1, + productSubCategoryDefinition1, user, STATUS_CODE_CREATED, auditType); + } + + // Benny + @Test + public void createResourceSubCategoryAlreadyExistInDifferentResourceCategory() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + DbUtils.deleteFromEsDbByPattern("_all"); + resourceSubCategoryDefinition1.setName("ResourcE-subCat"); + createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition1, + resourceCategoryDefinition1, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + resourceSubCategoryDefinition1.setName(resourceSubCategoryDefinition.getName()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition1.getUniqueId(), resourceSubCategoryDefinition1); // also + // set + // catalog + // uniqeId + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition1, + resourceSubCategoryDefinition1, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void createProductSubCategoryAlreadyExistInDifferentProductCategory() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, + AUDIT_PRODUCT_TYPE); + DbUtils.deleteFromEsDbByPattern("_all"); + productSubCategoryDefinition1.setName("PRoDUCT-SUBcat"); + createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition1, + productCategoryDefinition1, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + productSubCategoryDefinition1.setName(productSubCategoryDefinition.getName()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition1.getUniqueId(), productSubCategoryDefinition1); // also + // set + // catalog + // uniqeId + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition1, + productSubCategoryDefinition1, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, + AUDIT_PRODUCT_TYPE); + } + + @Test + public void createResourceSubCategoryAlreadyExistInCategory() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + DbUtils.deleteFromEsDbByPattern("_all"); + resourceSubCategoryDefinition1.setName("ResourcE-subCat"); + createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition1, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_ALREADY_EXISTS, + createSubCategoryRest.getErrorCode().intValue()); + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition1, sdncAdminUserDetails, + ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, STATUS_CODE_ALREADY_EXISTS, + AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, resourceSubCategoryDefinition1.getName(), + resourceCategoryDefinition.getName()); + } + + @Test + public void createProductSubCategoryAlreadyExistInCategory() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, + AUDIT_PRODUCT_TYPE); + DbUtils.deleteFromEsDbByPattern("_all"); + productSubCategoryDefinition1.setName("ProducT-subCat"); + createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition1, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_ALREADY_EXISTS, + createSubCategoryRest.getErrorCode().intValue()); + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition1, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, STATUS_CODE_ALREADY_EXISTS, AUDIT_PRODUCT_TYPE, + AUDIT_PRODUCT_TYPE, productSubCategoryDefinition1.getName(), productCategoryDefinition.getName()); + } + + @Test + public void addSameNormalizedSubCategoryNameForRecourceAndProductCategory() throws Exception { + // add sub-categoty name "SubCaT" to resource category + // add sub-categoty name "SUbcAt" to product category + resourceSubCategoryDefinition.setName("SubCaT"); // normalized 'subcat' + productSubCategoryDefinition.setName("SUbcAt"); // normalized 'subcat' + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + + DbUtils.deleteFromEsDbByPattern("_all"); + createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, + AUDIT_PRODUCT_TYPE); + } + + @Test + public void createResourceSubCategoryByNonAdminUser() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncTesterUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION, + STATUS_CODE_RESTRICTED_OPERATION, AUDIT_RESOURCE_TYPE); + } + + @Test + public void createResourceSubCategoryByProducStrategistUser() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncProductStrategistUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncProductStrategistUserDetails, ActionStatus.RESTRICTED_OPERATION, + STATUS_CODE_RESTRICTED_OPERATION, AUDIT_RESOURCE_TYPE); + } + + @Test + public void createProductSubCategoryByNonProducStrategistUser() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncDesignerUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION, + STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE); + } + + @Test + public void createProductSubCategoryByAdminUser() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.RESTRICTED_OPERATION, + STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE); + } + + // @Ignore("DE176245") + @Test + public void createResourceSubCategoryForNonExistingComponentType() throws Exception { + String nonSupportedComponentType = "NonExistingComponentType"; // instead + // resource/product + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, nonSupportedComponentType); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, nonSupportedComponentType); + } + + // @Ignore("DE176245") + @Test + public void createProductSubCategoryForNonExistingComponentType() throws Exception { + String nonSupportedComponentType = "NonExistingComponentType"; // instead + // resource/product + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, nonSupportedComponentType); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, nonSupportedComponentType); + } + + @Test + public void createServiceSubCategoryByAdmin() throws Exception { + // Service doesn't have sub-category + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE); + } + + @Test + public void createServiceSubCategoryByProductStrategist() throws Exception { + // Service doesn't have sub-category + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition, sdncProductStrategistUserDetails, SERVICE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + productCategoryDefinition.getUniqueId(), productSubCategoryDefinition); + // Audit validation + productCategoryDefinition.setName(productCategoryDefinition.getUniqueId()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition, + productSubCategoryDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT, + STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE); + } + + @Test + public void createResourceSubCategoryForNonExistingCategory() throws Exception { + resourceCategoryDefinition100.setUniqueId(resourceCategoryDefinition100.getName()); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition100, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_NOT_FOUND, + createSubCategoryRest.getErrorCode().intValue()); + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition100, + resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, + STATUS_CODE_NOT_FOUND, AUDIT_RESOURCE_TYPE, RESOURCE_COMPONENT_TYPE, CATEGORY, ""); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition100.getUniqueId(), resourceSubCategoryDefinition); + } + + @Test + public void createProductSubCategoryForNonExistingCategory() throws Exception { + productCategoryDefinition200.setUniqueId(productCategoryDefinition200.getName()); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition, + productCategoryDefinition200, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_NOT_FOUND, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + PRODUCT_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + productCategoryDefinition200.getUniqueId(), productSubCategoryDefinition); + // Audit validation // need to change ActionStatus + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition200, + productSubCategoryDefinition, sdncProductStrategistUserDetails, + ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, STATUS_CODE_NOT_FOUND, AUDIT_PRODUCT_TYPE, + PRODUCT_COMPONENT_TYPE, CATEGORY, ""); + } + + // pass + @Test + public void subCategoryAllowedcharacters_01() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE-"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); // also + // set + // catalog + // uniqeId + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + // pass + @Test + public void subCategoryAllowedcharacters_02() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE+"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_03() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE&"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_04() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE."); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_05() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE'"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_06() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE="); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_07() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE:"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_08() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE@"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_09() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE_"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_10() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE#"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_11() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE d"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("1234AbcdE D"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryAllowedcharacters_12() throws Exception { + resourceSubCategoryDefinition.setName("1234AbcdE &_=+.-'#:@ d"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("1234AbcdE &_=+.-'#:@ D"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveSpaceFromBeginning() throws Exception { + resourceSubCategoryDefinition.setName(" Category01"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category01"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveSpaceFromEnd() throws Exception { + resourceSubCategoryDefinition.setName("Category01 "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category01"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraSpace() throws Exception { + resourceSubCategoryDefinition.setName("Category 02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category 02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraAmpersand() throws Exception { + resourceSubCategoryDefinition.setName("Category&& &02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category& &02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraDash() throws Exception { + resourceSubCategoryDefinition.setName("CategorY-- --02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("CategorY- -02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraPlus() throws Exception { + resourceSubCategoryDefinition.setName("CateGory++++ +02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("CateGory+ +02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraPeriod() throws Exception { + resourceSubCategoryDefinition.setName("Category.... .02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category. .02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraApostrophe() throws Exception { + resourceSubCategoryDefinition.setName("CaTegory''' '02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("CaTegory' '02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraHashtag() throws Exception { + resourceSubCategoryDefinition.setName("Category### #02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category# #02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtrEequal() throws Exception { + resourceSubCategoryDefinition.setName("Category=== =02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category= =02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtrColon() throws Exception { + resourceSubCategoryDefinition.setName("Category::: :02"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category: :02"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtrAt() throws Exception { + resourceSubCategoryDefinition.setName("Category@@@ @a2"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category@ @a2"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryRemoveExtraUnderscore() throws Exception { + resourceSubCategoryDefinition.setName("Category___ _22"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Category_ _22"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryFirstWordStartWithNumber() throws Exception { + resourceSubCategoryDefinition.setName("1Category one"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("1Category One"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + // Bug + // Desc= + // DESC=SVC4556: Error: InvalidResourcesub-categorynameformat., + // @Ignore + @Test + public void subCategoryFirstWordStartWithNonAlphaNumeric() throws Exception { + // The first word must start with an alpha-numeric character [a-Z A..Z, + // 0..9] + char invalidChars[] = { '&', '-', '+', '.', '\'', '#', '=', ':', '@', '_' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + resourceSubCategoryDefinition.setName(invalidChars[i] + "AbcD123"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, + AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY); + + } + } + + @Test + public void subCategoryReplaceAndWithAmpersand_01() throws Exception { + resourceSubCategoryDefinition.setName("At and T"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("At & T"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryReplaceAndWithAmpersand_02() throws Exception { + resourceSubCategoryDefinition.setName("At and t"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("At & T"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryReplaceAndWithAmpersand_03() throws Exception { + resourceSubCategoryDefinition.setName("Atand T"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryReplaceAndWithAmpersand_04() throws Exception { + resourceSubCategoryDefinition.setName("At andT"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("At AndT"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryReplaceAndWithAmpersand_05() throws Exception { + resourceSubCategoryDefinition.setName(" and AttT"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("And AttT"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryReplaceAndWithAmpersand_06() throws Exception { + resourceSubCategoryDefinition.setName("AttT and "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("AttT And"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryReplaceAndWithAmpersand_07() throws Exception { + resourceSubCategoryDefinition.setName(" and a"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("And a"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationMaxLength() throws Exception { + resourceSubCategoryDefinition.setName("AsdfghjQ234567890@#.&:+-_"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationMaxLengthAfterNormalization() throws Exception { + resourceSubCategoryDefinition.setName(" A jQ234 @@@___ +++ At and T and and "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("A JQ234 @_ + At & T & And"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + // bug : + // Desc= + @Test + public void subCategoryNameValidationExceedMaxLengthAfterNormalization() throws Exception { + resourceSubCategoryDefinition.setName(" AbdfghBCVa jQ234 @@___ +++ At and T "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, + STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY); + } + + @Test + public void subCategoryNameValidationMinLengthAfterNormalization() throws Exception { + resourceSubCategoryDefinition.setName(" AT&&&&&&&&&T "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("AT&T"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + // bug + // Desc= + @Test + public void subCategoryNameValidationLessThanMinLengthAfterNormalization() throws Exception { + resourceSubCategoryDefinition.setName(" A&&&T "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, + STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY); + } + + @Test + public void subCategoryNameIsEmpty() throws Exception { + resourceSubCategoryDefinition.setName(""); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, + STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY); + } + + // bug + // Desc= + @Test + public void subCategoryNameValidationInvalidCharacters() throws Exception { + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', + '|', '\\', ',' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + resourceSubCategoryDefinition.setName("AbcD123" + invalidChars[i]); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, + AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY); + } + } + + @Test + public void subCategoryNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception { + resourceSubCategoryDefinition.setName("beNNy shaY michEl"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("BeNNy ShaY MichEl"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_01() throws Exception { + resourceSubCategoryDefinition.setName(" bank OF america "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Bank of America"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_02() throws Exception { + resourceSubCategoryDefinition.setName("THE america bank "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("THE America Bank"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_03() throws Exception { + resourceSubCategoryDefinition.setName(" A bank OF america "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("A Bank of America"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_04() throws Exception { + resourceSubCategoryDefinition.setName(" bank america is A big ban "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Bank America Is a Big Ban"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_05() throws Exception { + resourceSubCategoryDefinition.setName(" aN apple comPany inC "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("AN Apple ComPany InC"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_06() throws Exception { + resourceSubCategoryDefinition.setName(" eat AN apple ANAN"); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Eat an Apple ANAN"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_07() throws Exception { + resourceSubCategoryDefinition.setName(" united states OF americA "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("United States of AmericA"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_08() throws Exception { + resourceSubCategoryDefinition.setName(" oF united states OF amer "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("OF United States of Amer"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_09() throws Exception { + resourceSubCategoryDefinition.setName(" to Apple TO at&T TOO "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("To Apple to At&T TOO"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_10() throws Exception { + resourceSubCategoryDefinition.setName(" eat apple AS you liiikeas "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Eat Apple as You Liiikeas"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_11() throws Exception { + resourceSubCategoryDefinition.setName(" as you may want "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("As You May Want"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_12() throws Exception { + resourceSubCategoryDefinition.setName(" the bank OF america "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("The Bank of America"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_13() throws Exception { + resourceSubCategoryDefinition.setName(" To tel-toto "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("To Tel-toto"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void subCategoryNameValidationConjunctions_14() throws Exception { + resourceSubCategoryDefinition.setName(" tel-aviv To la "); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + resourceSubCategoryDefinition.setName("Tel-aviv to La"); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition); + + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition, + resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE); + } + + @Test + public void createSubCategoryHttpCspUserIdHeaderIsMissing() throws Exception { + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategoryHttpCspAtuUidIsMissing( + resourceSubCategoryDefinition, resourceCategoryDefinition, sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_MISSING_INFORMATION, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_SUB_CATEGORY); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(resourceCategoryDefinition.getUniqueId()); + // String subCategoryName = (resourceSubCategoryDefinition != null ? + // resourceSubCategoryDefinition.getName() : Constants.EMPTY_STRING); + expectedCatrgoryAuditJavaObject.setSubCategoryName(resourceSubCategoryDefinition.getName()); + // String groupingName = (groupingDefinition != null ? + // groupingDefinition.getName() : Constants.EMPTY_STRING); + expectedCatrgoryAuditJavaObject.setGroupingName(""); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_RESOURCE_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_SUB_CATEGORY); + } + + @Test + public void createSubCategoryHttpCspUserIdIsEmpty() throws Exception { + User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncAdminUserDetails1.setUserId(""); + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails1, RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after create Sub category", STATUS_CODE_MISSING_INFORMATION, + createSubCategoryRest.getErrorCode().intValue()); + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(ADD_SUB_CATEGORY); + expectedCatrgoryAuditJavaObject.setModifier(""); + expectedCatrgoryAuditJavaObject.setCategoryName(resourceCategoryDefinition.getUniqueId()); + // String subCategoryName = (resourceSubCategoryDefinition != null ? + // resourceSubCategoryDefinition.getName() : Constants.EMPTY_STRING); + expectedCatrgoryAuditJavaObject.setSubCategoryName(resourceSubCategoryDefinition.getName()); + // String groupingName = (groupingDefinition != null ? + // groupingDefinition.getName() : Constants.EMPTY_STRING); + expectedCatrgoryAuditJavaObject.setGroupingName(""); + expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_RESOURCE_TYPE); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_SUB_CATEGORY); + } + + //////////////////////////////////////////////////////////// + private void createSubCategorySuccess(CategoryDefinition categoryDefinition, + SubCategoryDefinition subCategoryDefinition, User sdncAdminUserDetails, String componentType, + String auditType) throws Exception { + + RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(subCategoryDefinition, + categoryDefinition, sdncAdminUserDetails, componentType); + assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED, + createSubCategoryRest.getErrorCode().intValue()); + CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, subCategoryDefinition); + // Audit validation + AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, categoryDefinition, subCategoryDefinition, + sdncAdminUserDetails, STATUS_CODE_CREATED, auditType); + // get service category and validate that category added as defined + // (also set catalog uniqeId) + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, componentType); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + categoryDefinition.getUniqueId(), subCategoryDefinition); // also + // set + // catalog + // uniqeId + } + + @Test + public void getResourceCategoryHierarchySuccessFlow() throws Exception { + int numOfSubCategories = 3; + List subCategories = new ArrayList(); + RestResponse restResponse; + SubCategoryDefinition subCategory; + String subName = resourceSubCategoryDefinition.getName(); + for (int i = 0; i < numOfSubCategories; i++) { + resourceSubCategoryDefinition.setName(subName + i); + restResponse = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition, + resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE); + subCategory = ResponseParser.parseToObject(restResponse.getResponse(), SubCategoryDefinition.class); + subCategories.add(subCategory); + } + RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, + RESOURCE_COMPONENT_TYPE); + assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS, + getAllCategoriesRest.getErrorCode().intValue()); + AuditValidationUtils.GetCategoryHierarchyAuditSuccess(GET_CATEGORY_HIERARCHY, AUDIT_RESOURCE_TYPE, + sdncAdminUserDetails, STATUS_CODE_SUCCESS); + for (SubCategoryDefinition sub : subCategories) { + CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest, + resourceCategoryDefinition.getUniqueId(), sub); + } + } + +} 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 new file mode 100644 index 0000000000..8a5fe91065 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java @@ -0,0 +1,104 @@ +/*- + * ============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.ci.tests.execute.devCI; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.utils.CsarParserUtils; +import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils; +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory; +//import org.openecomp.sdc.toscaparser.api.Metadata; +import org.openecomp.sdc.toscaparser.api.Capability; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.openecomp.sdc.toscaparser.api.common.JToscaException; +import org.testng.annotations.Test; + +public class AndreyTest { + + 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"); + + toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path); + System.out.println("listTypeHeatMetaDefinition start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); + List 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 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())); + } + + + @Test + public void distributionTest() throws SdcToscaParserException, JToscaException, IOException { + //String serviceName = import and create().getName(); + //getServiceObject(); + //parseServiceObject(); + + + + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + long startTime = System.currentTimeMillis(); + long estimatedTime = System.currentTimeMillis() - startTime; + System.out.println("Time to init factory " + estimatedTime); + String fileStr1 = "src//test//resources//CI//csars//service-ServiceFdnt-csar-0904-2.csar";//ToscaParserStubsTest.class.getClassLoader().getResource("csars/service-ServiceFdnt-csar-0904-2.csar").getFile(); + File file1 = new File(fileStr1); + String name = file1.getName(); + String absolutePath = file1.getAbsolutePath(); + ISdcCsarHelper fdntCsarHelper = factory.getSdcCsarHelper(file1.getAbsolutePath()); + + List serviceVfList = fdntCsarHelper.getServiceVfList(); + serviceVfList.size(); + for (NodeTemplate nodeTemplate : serviceVfList) { + ArrayList requirements = nodeTemplate.getRequirements(); + requirements.size(); + LinkedHashMap capabilities = nodeTemplate.getCapabilities(); + ArrayList requirements2 = nodeTemplate.getRequirements(); + + System.out.println(nodeTemplate.getName()); + } + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ArtifactFromCsar.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ArtifactFromCsar.java new file mode 100644 index 0000000000..c3346952b2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ArtifactFromCsar.java @@ -0,0 +1,301 @@ +/*- + * ============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.ci.tests.execute.devCI; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.utils.CsarParserUtils; + +public class ArtifactFromCsar { + + + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + String zipFile = "C:\\Users\\rp955r\\Documents\\InTesting\\resource-CivfonboardedFdnt2f792348-csar.csar"; + +// Map combinedMap = combineHeatArtifacstWithFolderArtifacsToMap(zipFile); + + Map vfcArtifacts = ArtifactFromCsar.getVFCArtifacts(zipFile); + + System.out.println("1234o"); + } + + public static Map combineHeatArtifacstWithFolderArtifacsToMap(String pathToCsar) throws Exception { + return combineHeatArtifacstWithFolderArtifacsToMap(pathToCsar, "output"); + } + + public static Map combineHeatArtifacstWithFolderArtifacsToMap(String pathToCsar, String outputCsar) throws Exception { + File csarFile = new File(pathToCsar); + + + File dir = new File(csarFile.getParent() + File.separator + outputCsar); + dir.mkdir(); + if(!dir.exists()) { + } + + String outputFolder = dir.getPath(); + unZip(pathToCsar, outputFolder); + File directory = new File(outputFolder + File.separator + "Artifacts" + File.separator ); + + Map artifactsMap = combineHeatArtifacstWithFolderArtifacsToMap(getMapArtifactFromFolderStructure(directory), getDeploymentArtifactListFromHeatMeta(csarFile, directory)); + FileUtils.cleanDirectory(new File(outputFolder)); + + return artifactsMap; + } + + public static Map getVFCArtifacts(String pathToCsar) throws Exception{ + String outputFolder = unzipCsarFile(pathToCsar); + File directory = new File(outputFolder + File.separator + "Artifacts" + File.separator ); + Map artifactsMap = getMapArtifactFromFolderStructure(directory); + cleanFolders(outputFolder); + + return artifactsMap; + } + + private static Map combineHeatArtifacstWithFolderArtifacsToMap(Map map, List rlist) { + if(map.get("Deployment") != null) { + rlist.addAll((Collection) map.get("Deployment")); + } + map.put("Deployment", rlist); + return map; + } + + private static List getDeploymentArtifactListFromHeatMeta(File pathToCsar, File directory) throws Exception { + List artifactList = new LinkedList(); + + List listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(pathToCsar); + + for(TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition){ + for(GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()){ + artifactList.addAll(groupHeatMetaDefinition.getArtifactList()); + } + } + + List listArtifactWithTypesByList = getListArtifactWithTypesByList(directory, artifactList); + return listArtifactWithTypesByList; +// return artifactList; + + } + + private static Map getMapArtifactFromFolderStructure(File pathToArtifactFolder) throws IOException { + + Map map = new HashMap(); + + + final Path dir = Paths.get(pathToArtifactFolder.getPath()); + final DirectoryStream dirStream = Files.newDirectoryStream(dir); + + dirStream.forEach(currFile -> { + File file = currFile.toFile(); + if (file.isDirectory()) { + System.out.println(file.getName()); + if(file.getName().toLowerCase().equals("deployment") || file.getName().toLowerCase().equals("informational")) { + map.put(file.getName(), getListArtifactWithTypes(file)); + } else { + try { + map.put(file.getName(), getMapArtifactFromFolderStructure(file)); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + }); + + dirStream.close(); + + + +// +// File[] fileList = pathToArtifactFolder.listFiles(); +// for(File file: fileList) { +// if (file.isDirectory()) { +// +// System.out.println(file.getName()); +// if(file.getName().equals("Deployment") || file.getName().equals("Informational")) { +// map.put(file.getName(), getListArtifactWithTypes(file)); +// } else { +// map.put(file.getName(), getMapArtifactFromFolderStructure(file)); +// } +// } +// } + return map; + } + + + + private static List getListArtifactWithTypes(File folderPath) { + List artifactList = new LinkedList(); + + File[] fileList = folderPath.listFiles(); + + for(File file: fileList) { + File[] artifacts = file.listFiles(); + + for(File artifact: artifacts) { +// HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition = new HeatMetaFirstLevelDefinition(file.getName(), artifact.getName()); + HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition = new HeatMetaFirstLevelDefinition(artifact.getName(), file.getName(), crunchifyGetMd5ForFile(artifact)); + artifactList.add(heatMetaFirstLevelDefinition); + } + } + + return artifactList; + } + + private static List getListArtifactWithTypesByList(File folderPath, List artifactLogicList) { + + + File[] fileList = folderPath.listFiles(); + + + + for (HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition : artifactLogicList) { + + String fileName = heatMetaFirstLevelDefinition.getFileName(); + + for (File fileFromFolder : fileList) { + if ( fileFromFolder.getName().equals(fileName)){ + heatMetaFirstLevelDefinition.setCheckSum(crunchifyGetMd5ForFile(fileFromFolder)); + } + + } + } + + return artifactLogicList; + } + + public static String crunchifyGetMd5ForFile(File crunchifyFile) { + String crunchifyValue = null; + FileInputStream crunchifyInputStream = null; + try { + crunchifyInputStream = new FileInputStream(crunchifyFile); + + // md5Hex converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. + // The returned array will be double the length of the passed array, as it takes two characters to represent any given byte. + crunchifyValue = DigestUtils.md5Hex(IOUtils.toByteArray(crunchifyInputStream)); + } catch (IOException e) { + e.printStackTrace(); + } finally { + IOUtils.closeQuietly(crunchifyInputStream); + } + return crunchifyValue; + } + + public static void unZip(String zipFile, String outputFolder) { + byte[] buffer = new byte[1024]; + + try{ + File folder = new File(outputFolder); + + if(!folder.exists()){ + folder.mkdir(); + } + + ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); + ZipEntry ze = zis.getNextEntry(); + + while(ze!=null){ + + String fileName = ze.getName(); + File newFile = new File(outputFolder + File.separator + fileName); + + if(ze.isDirectory()) { + newFile.mkdir(); + ze = zis.getNextEntry(); + continue; + } + + new File(newFile.getParent()).mkdirs(); + FileOutputStream fos = new FileOutputStream(newFile); + + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + + fos.close(); + ze = zis.getNextEntry(); + } + + zis.closeEntry(); + zis.close(); + + } catch (IOException ex) { + ex.printStackTrace(); + } + + } + + private static void cleanFolders(String outputFolder) throws IOException { + System.gc(); + FileUtils.cleanDirectory(new File(outputFolder)); + FileUtils.deleteDirectory(new File(outputFolder)); + } + + private static String unzipCsarFile(String pathToCsar) { + File csarFile = new File(pathToCsar); + + + File dir = new File(csarFile.getParent() + File.separator + "output-" + UUID.randomUUID()); + if(!dir.exists()) { + dir.mkdirs(); + } + + String outputFolder = dir.getPath(); + ArtifactFromCsar.unZip(pathToCsar, outputFolder); + return outputFolder; + } + + public static String[] getArtifactNamesFromCsar(String path, String csarFile) throws Exception { + Map combinedMap = combineHeatArtifacstWithFolderArtifacsToMap(path + csarFile); + LinkedList deploymentArtifacts = ((LinkedList) combinedMap.get("Deployment")); + List artifactNamesList = deploymentArtifacts.stream().map(e -> e.getFileName()).collect(Collectors.toList()); + Object[] artifactNamesObjectArr = artifactNamesList.toArray(); + String[] artifactNamesFromFile = Arrays.copyOf(artifactNamesObjectArr, artifactNamesObjectArr.length, String[].class); + return artifactNamesFromFile; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java new file mode 100644 index 0000000000..f66fd670f6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java @@ -0,0 +1,362 @@ +/*- + * ============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.ci.tests.execute.devCI; + +import static org.testng.AssertJUnit.assertTrue; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.imports.ImportCsarResourceTest; +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.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.validation.CsarValidationUtils; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class ImportCsarUpdate extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public ImportCsarUpdate() { + super(name, ImportCsarUpdate.class.getName()); + } + + @DataProvider(name = "happyArts") + public Object[][] getHappyArtifacts() { + + return new Object[][] { { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet2" }, + { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet" }, + { "happy_VF_RI2_G2_two_identical_artifacts_under_heatBaseheatVolheatNet" }, + { "happy_VF_RI2_G2_two_different_artifacts_under_nested" }, + { "happy_VF_RI2_G2_two_indentical_nested_under_different_groups" }, + { "happy_VF_RI2_G2_two_different_nested_under_different_groups" }, + { "happy_VF_RI2_G2_two_different_nested_under_same_group" }, + + }; + } + + @DataProvider(name = "negativeArts") + public Object[][] getNegativeArtifacts() { + + return new Object[][] { + + { "negative_VF_RI2_G2_same_heatVol_different_groups" }, + { "negative_VF_RI2_G2_same_heatBase_different_envs" }, + { "negative_VF_RI2_G2_heatBaseHeatVolHeatNet_under_nested" }, + { "negative_VF_RI2_G2_two_indentical_artifacts_under_nested" }, + { "negative_VF_RI2_G2_nested_under_nested" }, { "negative_VF_RI2_G2_same_heatVol_different_groups" }, }; + } + + @BeforeTest + public void resumeOrigCsarBefore() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig.csar", "importCsar_2Gartifacts.csar"); + + } + + @AfterTest + public void resumeOrigCsarAfter() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig.csar", "importCsar_2Gartifacts.csar"); + + } + + @Test + public void updateVFsearchByCsarIdCheckInState() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils + .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true) + .getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar"); + + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + + @Test + public void updateVFsearchByCsarIdCheckInState_checkSum() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils + .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true) + .getLeft(); + + // User sdncModifierDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // RestResponse copyRes = + // ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,"updateImportCsar_2Gartifacts_topologyChanged.csar","importCsar_2Gartifacts.csar"); + + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + + @Test + public void updateVFsearchByCsarIdCheckOutState() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + // Component resourceObject = + // AtomicOperationUtils.changeComponentState(resourceFirstImport, + // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar"); + + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + + @Test + public void updateVFsearchByCsarIdCertifyStat() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils + .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true) + .getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar"); + + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + + @Test + public void updateVFsearchByCsarStartCertifaicationState() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils.changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar"); + + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + + @Test + public void updateVFsearchBySystemNameCheckInState() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils + .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true) + .getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar"); + + resourceDetails.setName("hardcodedNameChanged"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + + @Test + public void updateVFsearchBySystemNameCertifyState() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils + .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true) + .getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar"); + + resourceDetails.setName("hardcodedNameChanged"); + resourceDetails.setCsarUUID("importCsar_2Gartifacts"); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + } + + @Test + public void updateVFsearchBySystemNameCsarIdNotExist() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("hardcodedName"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + Component resourceObject = AtomicOperationUtils + .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true) + .getLeft(); + // User sdncModifierDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // RestResponse copyRes = + // ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,"updateImportCsar_2Gartifacts_topologyChanged.csar","importCsar_2Gartifacts.csar"); + ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource(); + resourceDetails2.setName("hardcodedName"); + resourceDetails2.setCsarUUID("importCsar_2Gartifacts"); + resourceDetails2.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails2, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + // Validation Part + + resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java new file mode 100644 index 0000000000..5ed71e53b0 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java @@ -0,0 +1,108 @@ +/*- + * ============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.ci.tests.execute.devCI; + +import static org.testng.AssertJUnit.assertTrue; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +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.AtomicOperationUtils; +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.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class ImportCsarValidateArtifacts extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public ImportCsarValidateArtifacts() { + super(name, ImportCsarValidateArtifacts.class.getName()); + } + + @DataProvider(name = "happyArts") + public Object[][] getHappyArtifacts() { + + return new Object[][] { { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet2" }, + { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet" }, + { "happy_VF_RI2_G2_two_identical_artifacts_under_heatBaseheatVolheatNet" }, + { "happy_VF_RI2_G2_two_different_artifacts_under_nested" }, + { "happy_VF_RI2_G2_two_indentical_nested_under_different_groups" }, + { "happy_VF_RI2_G2_two_different_nested_under_different_groups" }, + { "happy_VF_RI2_G2_two_different_nested_under_same_group" }, + + }; + } + + @DataProvider(name = "negativeArts") + public Object[][] getNegativeArtifacts() { + + return new Object[][] { + + { "negative_VF_RI2_G2_same_heatVol_different_groups" }, + { "negative_VF_RI2_G2_same_heatBase_different_envs" }, + { "negative_VF_RI2_G2_heatBaseHeatVolHeatNet_under_nested" }, + { "negative_VF_RI2_G2_two_indentical_artifacts_under_nested" }, + { "negative_VF_RI2_G2_nested_under_nested" }, { "negative_VF_RI2_G2_same_heatVol_different_groups" }, }; + } + + @Test(dataProvider = "happyArts") + public void createResourceFromCsarArtsHappy(String artifactName) throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(artifactName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + CsarValidationUtils.validateCsarVfArtifact(artifactName, resource); + + } + + @Test(dataProvider = "negativeArts") + public void createResourceFromCsarArtsNegative(String artifactName) throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(artifactName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + assertTrue(createResource.getErrorCode() != 201 && createResource.getErrorCode() != 500); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java new file mode 100644 index 0000000000..64df976c09 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java @@ -0,0 +1,580 @@ +/*- + * ============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.ci.tests.execute.devCI; + +import static org.testng.AssertJUnit.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.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.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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.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.validation.CsarValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +public class ToscaGroupInsideVF extends ComponentBaseTest { + private static Logger logger = LoggerFactory.getLogger(ToscaGroupInsideVF.class.getName()); + + @Rule + public static TestName name = new TestName(); + + public ToscaGroupInsideVF() { + super(name, ToscaGroupInsideVF.class.getName()); + } + + /*@Test + public void createResourceFromCsarArts() throws Exception { + + // String csar = getCsar(); + // parseCsar(csar); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("VF_RI2_G6_withArtifacts"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + Component resourceObject = AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Resource vfManual = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true) + .left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, vfManual, UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.changeComponentState(vfManual, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true) + .getLeft(); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils + .addComponentInstanceToComponentContainer(resourceObject, service, UserRoleEnum.DESIGNER, true).left() + .value(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(vfManual, service, UserRoleEnum.DESIGNER, true) + .left().value(); + AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + AtomicOperationUtils + .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true) + .getLeft(); + AtomicOperationUtils + .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CANCELCERTIFICATION, true) + .getLeft(); + AtomicOperationUtils + .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true) + .getLeft(); + + } + + @Test + public void soferTest() throws Exception { + + // String csar = getCsar(); + // parseCsar(csar); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("sofer"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + } + + @Test + public void createVFwith2VLs() throws Exception { + + // String csar = getCsar(); + // parseCsar(csar); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("VSPPackage"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + Component resourceObject = AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Resource vfManual = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true) + .left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, vfManual, UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.changeComponentState(vfManual, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true) + .getLeft(); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils + .addComponentInstanceToComponentContainer(resourceObject, service, UserRoleEnum.DESIGNER, true).left() + .value(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(vfManual, service, UserRoleEnum.DESIGNER, true) + .left().value(); + AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + AtomicOperationUtils + .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true) + .getLeft(); + AtomicOperationUtils + .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CANCELCERTIFICATION, true) + .getLeft(); + AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true) + .getLeft(); + + } + + @Test // (enabled = false) + public void createResourceFromCsarHappy() throws Exception { + // String csarUUID = "VF_RI2_G2_withArtifacts"; + String csarUUID = "VF_RI2_G1_Invalid"; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + } + + @Test // (enabled = false) + public void createResourceFromCsarWithProperty() throws Exception { + String csarUUID = "VF_RI2_G4_withArtifacts"; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + } + + @Test // (enabled = false) + public void UpdateCsarWithNonExistingResourceInstanceFail() throws Exception { + + // String csarUUID = "VF_RI2_G1-RI_NotExist"; + // String csarUUID = "nested3"; + + // String csarUUID = "VF_RI2_G1_Invalid_WithArtifacts"; + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + String csarUUID = "VF_RI2_G4_withArtifacts.csar"; + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifactsRI_FAIL.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails.setName(resource.getName()); + // resourceDetails.setVendorName("Govnuk"); + // resourceDetails.setDescription("Other"); + RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource2); + Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class); + + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource); + + // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2); + // ToscaDefinition toscaDefinition2 = + // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2); + // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2, + // resource2); + + // Csar csar = parserTocsarObject(csarUUID); + // validateCsarVsResourceObj(csar, resource); + // csar.node_types(); + + } + + @Test // (enabled = false) + public void UpdateCsarWithSameCsarDifferentMetadata() throws Exception { + + // User sdncModifierDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // RestResponse copyRes = + // copyCsarRest(sdncModifierDetails,"VF_RI2_G4_withArtifacts_a.csar","VF_RI2_G4_withArtifacts.csar"); + // BaseRestUtils.checkSuccess(copyRes); + String csarUUID = "VF_RI2_G4_withArtifacts.csar"; + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + resourceDetails.setName(resource.getName()); + resourceDetails.setVendorName("Govnuk"); + resourceDetails.setDescription("Other"); + RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource2); + Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class); + + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource); + + // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2); + // ToscaDefinition toscaDefinition2 = + // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2); + // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2, + // resource2); + + // Csar csar = parserTocsarObject(csarUUID); + // validateCsarVsResourceObj(csar, resource); + // csar.node_types(); + + } + + @Test // (enabled = false) + public void UpdateCsarWithSameCsar() throws Exception { + + // User sdncModifierDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // RestResponse copyRes = + // copyCsarRest(sdncModifierDetails,"VF_RI2_G4_withArtifacts_a.csar","VF_RI2_G4_withArtifacts.csar"); + // BaseRestUtils.checkSuccess(copyRes); + String csarUUID = "VF_RI2_G4_withArtifacts.csar"; + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + resourceDetails.setName(resource.getName()); + RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource2); + Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class); + + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource); + + // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2); + // ToscaDefinition toscaDefinition2 = + // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2); + // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2, + // resource2); + + // Csar csar = parserTocsarObject(csarUUID); + // validateCsarVsResourceObj(csar, resource); + // csar.node_types(); + + } + + @Test // (enabled = false) + public void UpdateCsarCertifiedVfWithSameCsar() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + String csarUUID = "VF_RI2_G4_withArtifacts.csar"; + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + Pair changeComponentState = AtomicOperationUtils.changeComponentState(resource, + UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + resource = (Resource) changeComponentState.getLeft(); + + resourceDetails.setName(resource.getName()); + RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource2); + Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class); + + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource); + + // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2); + // ToscaDefinition toscaDefinition2 = + // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2); + // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2, + // resource2); + + // Csar csar = parserTocsarObject(csarUUID); + // validateCsarVsResourceObj(csar, resource); + // csar.node_types(); + + } + + @Test // (enabled = false) + public void UpdateCsarDifferentTosca() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + String csarUUID = "VF_RI2_G4_withArtifacts.csar"; + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifactsUpdated.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails.setName(resource.getName()); + RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource2); + Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class); + + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource); + + // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2); + // ToscaDefinition toscaDefinition2 = + // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2); + // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2, + // resource2); + + // Csar csar = parserTocsarObject(csarUUID); + // validateCsarVsResourceObj(csar, resource); + // csar.node_types(); + + } + + @Test // (enabled = false) + public void UpdateCsarDifferentToscaAndArtifacts() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + String csarUUID = "VF_RI2_G4_withArtifacts.csar"; + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_UpdateToscaAndArtifacts.csar", + "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails.setName(resource.getName()); + RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource2); + Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class); + + CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource); + ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource); + + // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2); + // ToscaDefinition toscaDefinition2 = + // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2); + // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2, + // resource2); + + // Csar csar = parserTocsarObject(csarUUID); + // validateCsarVsResourceObj(csar, resource); + // csar.node_types(); + + } + + @Test // (enabled = false) + public void migration() throws Exception { + String csarUUID = "VF_RI2_G4_withArtifacts"; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setName("Resource1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + + resourceDetails.setName("Resource2"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + resourceDetails.setName("Resource3"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + resourceDetails.setName("Resource4"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + resourceDetails.setName("Resource5"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + resourceDetails.setName("Resource6"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true) + .getLeft(); + + resourceDetails.setName("Resource7"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils + .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true) + .getLeft(); + + logger.debug("7 VF resources were created"); + + } + + public static RestResponse copyCsarRest(User sdncModifierDetails, String sourceCsarUuid, String targetCsarUuid) + throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.COPY_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), + sourceCsarUuid, targetCsarUuid); + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse copyCsarResponse = http.httpSendPost(url, "dummy", headersMap); + if (copyCsarResponse.getErrorCode() != 200) { + return null; + } + return copyCsarResponse; + + } + + private static Map prepareHeadersMap(String userId) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + return headersMap; + } + + public static void main(String[] args) throws Exception { + // String csarUUID = "VF_RI2_G4_withArtifacts"; + String csarUUID = "node_types"; + ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID); + }*/ +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java new file mode 100644 index 0000000000..7acf1206e7 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java @@ -0,0 +1,96 @@ +/*- + * ============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.ci.tests.execute.devCI; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.DistributionNotificationStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.DistributionValidationUtils; +import org.openecomp.sdc.externalApis.CRUDExternalAPI; +import org.testng.annotations.Test; + +import fj.data.Either; + +public class test1 extends ComponentBaseTest{ + + @Rule + public static TestName name = new TestName(); + + public test1() { + super(name, CRUDExternalAPI.class.getName()); + + } + + @Test() + public void uploadArtifactOnServiceViaExternalAPI() throws Exception { + Config config = Utils.getConfig(); + + Service service = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_QUERY_SPEC, service, UserRoleEnum.DESIGNER, true, true); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + if(config.getIsDistributionClientRunning()){ + List distributionStatusList = Arrays.asList(DistributionNotificationStatusEnum.DOWNLOAD_OK.toString(), DistributionNotificationStatusEnum.DEPLOY_OK.toString(), DistributionNotificationStatusEnum.NOTIFIED.toString()); + DistributionValidationUtils.validateDistributedArtifactsByAudit(service, distributionStatusList); + } + } + + + public static Map addVNF_ModuleDeploymentArtifactToMap(Service service, Map distributionArtifactMap){ + + + return distributionArtifactMap; + } + + public Component getComponentInTargetLifeCycleState(String componentType, UserRoleEnum creatorUser, LifeCycleStatesEnum targetLifeCycleState) throws Exception { + Component component = null; + + if(componentType.toLowerCase().equals("vf")) { + Either createdResource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, creatorUser, true); + component = createdResource.left().value(); + component = AtomicOperationUtils.changeComponentState(component, creatorUser, targetLifeCycleState, true).getLeft(); + } else { + Either createdResource = AtomicOperationUtils.createDefaultService(creatorUser, true); + component = createdResource.left().value(); + component = AtomicOperationUtils.changeComponentState(component, creatorUser, targetLifeCycleState, true).getLeft(); + } + + return component; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java new file mode 100644 index 0000000000..b4a9bb87ce --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java @@ -0,0 +1,186 @@ +/*- + * ============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.ci.tests.execute.distribution; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +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.datatypes.ArtifactReqDetails; +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.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils; +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.util.ValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class AuthanticationTests extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + protected User sdncUserDetails; + + protected static final String AUTH_SUCCESS = "AUTH_SUCCESS"; + + protected static final String AUTH_REQUIRED = "AUTH_REQUIRED"; + + // user ci password 123456 + // protected final String authorizationHeader = "Basic Y2k6MTIzNDU2"; + // user ci password 123456 + protected final String USER = "ci"; + protected final String PASSWORD = "123456"; + protected final String SALT = "2a1f887d607d4515d4066fe0f5452a50"; + protected final String HASHED_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"; + protected User sdncAdminUserDetails; + protected ConsumerDataDefinition consumerDataDefinition; + + public AuthanticationTests() { + super(name, AuthanticationTests.class.getName()); + } + + @DataProvider + private final Object[][] getServiceDepArtType() throws IOException, Exception { + return new Object[][] { { ArtifactTypeEnum.YANG_XML.getType() }, { ArtifactTypeEnum.OTHER.getType() } }; + } + + @BeforeMethod + public void setup() throws Exception { + resourceDetails = ElementFactory.getDefaultResource(); + serviceDetails = ElementFactory.getDefaultService(); + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + createComponents(); + consumerDataDefinition = createConsumer(); + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + ; + + RestResponse createResponse = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncAdminUserDetails); + BaseRestUtils.checkCreateResponse(createResponse); + + } + + @AfterMethod + public void tearDown() throws Exception { + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + ; + + } + + protected ConsumerDataDefinition createConsumer() { + ConsumerDataDefinition consumer = new ConsumerDataDefinition(); + consumer.setConsumerName(USER); + consumer.setConsumerSalt(SALT); + consumer.setConsumerPassword(HASHED_PASSWORD); + return consumer; + + } + + protected void createComponents() throws Exception { + RestResponse response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + ServiceRestUtils.checkCreateResponse(response); + } + + @Test(dataProvider = "getServiceDepArtType", description = "mumu") + public void downloadServiceArtifactSuccessWithAutantication(String serviceDepArtType) throws Exception { + String serviceUniqueId = serviceDetails.getUniqueId(); + + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(serviceDepArtType); + + RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, + sdncUserDetails, serviceUniqueId, ArtifactRestUtils.calculateChecksum(artifactDetails)); + AssertJUnit.assertEquals("Check response code after adding interface artifact", 200, + addArtifactResponse.getErrorCode().intValue()); + + String artifactName = ValidationUtils.normalizeFileName(artifactDetails.getArtifactName()); + // Thread.sleep(5000); + Map authorizationHeaders = BaseRestUtils.addAuthorizeHeader(USER, PASSWORD); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, artifactDetails, + sdncUserDetails, authorizationHeaders); + AssertJUnit.assertEquals("Check response code after download resource", 200, + restResponse.getErrorCode().intValue()); + + List contDispHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_DISPOSITION_HEADER); + AssertJUnit.assertNotNull(contDispHeaderList); + AssertJUnit.assertEquals("Check content disposition header", + new StringBuilder().append("attachment; filename=\"").append(artifactName).append("\"").toString(), + contDispHeaderList.get(0)); + + String downloadUrl = ArtifactRestUtils + .getPartialUrlByArtifactName(serviceDetails, serviceDetails.getVersion(), artifactName).substring(6); + + ExpectedAuthenticationAudit expectedAuthenticationAudit = new ExpectedAuthenticationAudit(downloadUrl, USER, + AuditingActionEnum.AUTH_REQUEST.getName(), AUTH_SUCCESS); + AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit); + } + + @Test(dataProvider = "getServiceDepArtType") + public void downloadServiceArtifactWithOutAutantication(String serviceDepArtType) throws Exception { + String serviceUniqueId = serviceDetails.getUniqueId(); + + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(serviceDepArtType); + + RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, + sdncUserDetails, serviceUniqueId, ArtifactRestUtils.calculateChecksum(artifactDetails)); + assertEquals("Check response code after adding interface artifact", 200, + addArtifactResponse.getErrorCode().intValue()); + + Map authorizationHeaders = new HashMap(); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, artifactDetails, + sdncUserDetails, authorizationHeaders); + assertEquals("Check response code after download resource failure", 401, + restResponse.getErrorCode().intValue()); + + String downloadUrl = ArtifactRestUtils.getPartialUrlByArtifactName(serviceDetails, serviceDetails.getVersion(), + artifactDetails.getArtifactName()).substring(6); + ExpectedAuthenticationAudit expectedAuthenticationAudit = new ExpectedAuthenticationAudit(downloadUrl, "", + AuditingActionEnum.AUTH_REQUEST.getName(), AUTH_REQUIRED); + AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java new file mode 100644 index 0000000000..7ba705fc7d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java @@ -0,0 +1,537 @@ +/*- + * ============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.ci.tests.execute.distribution; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipInputStream; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Resource; +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.ArtifactReqDetails; +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.NormativeTypesEnum; +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.expected.ExpectedDistDownloadAudit; +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.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.ConsumerRestUtils; +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.util.GeneralUtility; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class DistributionDownloadArtifactTest extends ComponentBaseTest { + + protected static ResourceReqDetails resourceDetails; + protected static User designerUser; + protected static User adminUser; + protected static String resourceBaseVersion; + // user ci password 123456 + protected final String authorizationHeader = "Basic Y2k6MTIzNDU2"; + protected ConsumerDataDefinition consumerDataDefinition; + + @Rule + public static TestName name = new TestName(); + protected static String artifactInterfaceType; + protected static String artifactOperationName; + + protected static ServiceReqDetails serviceDetails; + protected static String serviceBaseVersion; + protected static String serviceUniqueId; + protected final String USER = "ci"; + protected final String PASSWORD = "123456"; + protected final String SALT = "2a1f887d607d4515d4066fe0f5452a50"; + protected final String HASHED_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"; + + public DistributionDownloadArtifactTest() { + super(name, DistributionDownloadArtifactTest.class.getName()); + } + + // @BeforeClass + // public static void InitBeforeTest() throws Exception + // { + // + // + // resourceBaseVersion = "0.1"; + // serviceBaseVersion = "0.1"; + // designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // resourceDetails = + // ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + // NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, + // adminUser); + // serviceDetails = ElementFactory.getDefaultService(); + // serviceUniqueId = "svc_" + serviceDetails.getName().toLowerCase() + "." + + // serviceBaseVersion; + // artifactInterfaceType = "standard"; + // artifactOperationName = "start"; + // } + + @BeforeMethod + public void setup() throws Exception { + + resourceBaseVersion = "0.1"; + serviceBaseVersion = "0.1"; + designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + resourceDetails = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, adminUser); + serviceDetails = ElementFactory.getDefaultService(); + serviceUniqueId = "svc_" + serviceDetails.getName().toLowerCase() + "." + serviceBaseVersion; + artifactInterfaceType = "standard"; + artifactOperationName = "start"; + consumerDataDefinition = createConsumer(); + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, adminUser); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + + RestResponse createResponse = ConsumerRestUtils.createConsumer(consumerDataDefinition, adminUser); + BaseRestUtils.checkCreateResponse(createResponse); + } + + @Test + public void downloadResourceArtifactSuccess() throws Exception { + // Create service + RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser); + AssertJUnit.assertEquals("Check response code after creating resource", 201, + serviceResponse.getErrorCode().intValue()); + + // Create resource + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser); + AssertJUnit.assertEquals("Check response code after creating resource", 201, + createResource.getErrorCode().intValue()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse()); + + ArtifactReqDetails artifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + // Setting the name to be with space + artifactDetails.setArtifactName("test artifact file.yaml"); + // artifactDetails.set(ArtifactRestUtils.calculateChecksum(artifactDetails)); + + RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, + designerUser, resource.getUniqueId(), ArtifactRestUtils.calculateChecksum(artifactDetails)); + AssertJUnit.assertEquals("Check response code after adding interface artifact", 200, + addArtifactResponse.getErrorCode().intValue()); + + // Getting expected artifact checksum + ArtifactDefinition artifactResp = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addArtifactResponse.getResponse()); + String expectedPayloadChecksum = artifactResp.getArtifactChecksum(); + + Config config = Utils.getConfig(); + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion, + ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), + artifactResp.getArtifactName())); + // String fullUrlFormatted = + // String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL, + // config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl); + // String consumerId = "dummy.ecomp"; + + ResourceReqDetails resourceInfo = new ResourceReqDetails(); + resourceInfo.setName(resource.getName()); + resourceInfo.setVersion(resource.getVersion()); + + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resourceInfo, + artifactDetails, designerUser, authorizationHeaders); + // RestResponse restResponse = + // artifactUtils.downloadResourceArtifact(designerUser,fullUrlFormatted, + // consumerId,true); + AssertJUnit.assertEquals("Check response code after download resource", 200, + restResponse.getErrorCode().intValue()); + + // Validating headers + // content disposition + List contDispHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_DISPOSITION_HEADER); + AssertJUnit.assertNotNull(contDispHeaderList); + AssertJUnit + .assertEquals( + "Check content disposition header", new StringBuilder().append("attachment; filename=\"") + .append(artifactResp.getArtifactName()).append("\"").toString(), + contDispHeaderList.get(0)); + + // content type + List contTypeHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_TYPE_HEADER); + AssertJUnit.assertNotNull(contTypeHeaderList); + AssertJUnit.assertEquals("Check content type", "application/octet-stream", contTypeHeaderList.get(0)); + + String actualContents = restResponse.getResponse(); + + // Contents - comparing decoded content + AssertJUnit.assertEquals(artifactDetails.getPayload(), Base64.encodeBase64String(actualContents.getBytes())); + + // validating checksum + String actualPayloadChecksum = GeneralUtility.calculateMD5ByByteArray(actualContents.getBytes()); + AssertJUnit.assertEquals(expectedPayloadChecksum, actualPayloadChecksum); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, + BaseRestUtils.ecomp, relativeUrl, "200", "OK"); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + protected void download_serviceNameNotFound_inner(String serviceName, String serviceVersion, String resourceName, + String resourceVersion) throws Exception { + Config config = Utils.getConfig(); + String artifactName = "kuku"; + ArtifactReqDetails artifact = new ArtifactReqDetails(); + artifact.setArtifactName(artifactName); + String relativeUrl; + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + ServiceReqDetails serviceInfo = new ServiceReqDetails(); + serviceInfo.setName(serviceName); + serviceInfo.setVersion(serviceVersion); + RestResponse restResponse = null; + if (resourceName != null) { + ResourceReqDetails resourceDetailes = new ResourceReqDetails(); + resourceDetailes.setName(resourceName); + resourceDetailes.setVersion(resourceVersion); + relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceName), serviceVersion, + ValidationUtils.convertToSystemName(resourceName), resourceVersion, artifactName)); + restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceInfo, resourceDetailes, artifact, + designerUser, authorizationHeaders); + } else { + relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceName), serviceVersion, artifactName)); + restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceInfo, artifact, designerUser, + authorizationHeaders); + } + + // RestResponse restResponse = + // artifactUtils.downloadResourceArtifact(designerUser,fullUrlFormatted, + // consumerId,true); + AssertJUnit.assertEquals("Check response code after download resource", 404, + restResponse.getErrorCode().intValue()); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, + BaseRestUtils.ecomp, relativeUrl, "404", "SVC4503: Error: Requested '" + + ValidationUtils.convertToSystemName(serviceName) + "' service was not found."); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + protected void download_serviceVersionNotFound_inner(String serviceName, String serviceVersion, String resourceName, + String resourceVersion) throws Exception { + Config config = Utils.getConfig(); + String artifactName = "kuku"; + String relativeUrl; + ArtifactReqDetails artifact = new ArtifactReqDetails(); + artifact.setArtifactName(artifactName); + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + ServiceReqDetails serviceInfo = new ServiceReqDetails(); + serviceInfo.setName(serviceName); + serviceInfo.setVersion(serviceVersion); + RestResponse restResponse = null; + if (resourceName != null) { + ResourceReqDetails resourceDetailes = new ResourceReqDetails(); + resourceDetailes.setName(resourceName); + resourceDetailes.setVersion(resourceVersion); + relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceName), serviceVersion, + ValidationUtils.convertToSystemName(resourceName), resourceVersion, artifactName)); + restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceInfo, resourceDetailes, artifact, + designerUser, authorizationHeaders); + } else { + relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceName), serviceVersion, artifactName)); + restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceInfo, artifact, designerUser, + authorizationHeaders); + } + // String fullUrlFormatted = + // String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL, + // config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl); + // String consumerId = "dummy.ecomp"; + + // RestResponse restResponse = + // artifactUtils.downloadResourceArtifact(designerUser,fullUrlFormatted, + // consumerId,true); + AssertJUnit.assertEquals("Check response code after download resource", 404, + restResponse.getErrorCode().intValue()); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, + BaseRestUtils.ecomp, relativeUrl, "404", + "SVC4504: Error: Service version " + serviceVersion + " was not found."); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + protected String encodeUrlForDownload(String url) { + return url.replaceAll(" ", "%20"); + } + + protected ConsumerDataDefinition createConsumer() { + ConsumerDataDefinition consumer = new ConsumerDataDefinition(); + consumer.setConsumerName(USER); + consumer.setConsumerSalt(SALT); + consumer.setConsumerPassword(HASHED_PASSWORD); + return consumer; + + } + + @Test(enabled = false) + public void downloadServiceArtifactSuccess() throws Exception { + // Create service + RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser); + assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue()); + serviceUniqueId = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse()) + .getUniqueId(); + + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType("MURANO_PKG"); + + RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, + designerUser, serviceUniqueId, ArtifactRestUtils.calculateMD5Header(artifactDetails)); + assertEquals("Check response code after adding interface artifact", 200, + addArtifactResponse.getErrorCode().intValue()); + + // Getting expected artifact checksum + + // ArtifactResJavaObject artifactResp = + // artifactUtils.parseInformationalArtifactResp(addArtifactResponse); + String expectedPayloadChecksum = ResponseParser + .convertArtifactDefinitionResponseToJavaObject(addArtifactResponse.getResponse()).getArtifactChecksum(); + + String artifactName = ValidationUtils.normalizeFileName(artifactDetails.getArtifactName()); + + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion, artifactName)); + + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, artifactDetails, + designerUser, authorizationHeaders); + assertEquals("Check response code after download resource", 200, restResponse.getErrorCode().intValue()); + + // Validating headers + // content disposition + List contDispHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_DISPOSITION_HEADER); + assertNotNull(contDispHeaderList); + assertEquals("Check content disposition header", + new StringBuilder().append("attachment; filename=\"").append(artifactName).append("\"").toString(), + contDispHeaderList.get(0)); + + // content type + List contTypeHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_TYPE_HEADER); + assertNotNull(contTypeHeaderList); + assertEquals("Check content type", "application/octet-stream", contTypeHeaderList.get(0)); + + String actualContents = restResponse.getResponse(); + + assertEquals(artifactDetails.getPayload(), Base64.encodeBase64String(actualContents.getBytes())); + + // validating checksum + byte[] bytes = actualContents.getBytes(); + String actualPayloadChecksum = GeneralUtility.calculateMD5ByByteArray(bytes); + assertEquals(expectedPayloadChecksum, actualPayloadChecksum); + + // validating valid zip + InputStream is = new ByteArrayInputStream(bytes); + InputStream zis = new ZipInputStream(is); + zis.close(); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, + ResourceRestUtils.ecomp, encodeUrlForDownload(relativeUrl), "200", "OK"); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + @Test + public void downloadResourceArtifact_NoConsumerId() throws Exception { + + String artifactName = "kuku"; + ArtifactReqDetails artifact = new ArtifactReqDetails(); + artifact.setArtifactName(artifactName); + ResourceReqDetails resource = new ResourceReqDetails(); + resource.setName("notExisting"); + resource.setVersion("0.1"); + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion, + ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), artifactName)); + serviceDetails.setVersion("0.1"); + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resource, artifact, + designerUser, authorizationHeaders, false); + assertEquals("Check response code after download resource", 400, restResponse.getErrorCode().intValue()); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, "", + relativeUrl, "400", "POL5001: Error: Missing 'X-ECOMP-InstanceID' HTTP header."); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + @Test + public void downloadResourceArtifact_ResourceNameNotFound() throws Exception { + + String artifactName = "kuku"; + ArtifactReqDetails artifact = new ArtifactReqDetails(); + artifact.setArtifactName(artifactName); + ResourceReqDetails resource = new ResourceReqDetails(); + resource.setName("notExisting"); + resource.setVersion("0.1"); + serviceDetails.setVersion("0.1"); + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(), + ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), artifactName)); + + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resource, artifact, + designerUser, authorizationHeaders); + + assertEquals("Check response code after download resource", 404, restResponse.getErrorCode().intValue()); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, + BaseRestUtils.ecomp, relativeUrl, "404", + "SVC4063: Error: Requested 'Notexisting' resource was not found."); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + @Test + public void downloadResourceArtifact_ResourceVersionNotFound() throws Exception { + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser); + assertEquals("Check response code after creating resource", 201, createResource.getErrorCode().intValue()); + + Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse()); + ResourceReqDetails resourceDetailes = new ResourceReqDetails(); + resourceDetailes.setName(resource.getName()); + resourceDetailes.setVersion("0.2"); + + serviceDetails.setVersion("0.1"); + + String artifactName = "kuku"; + ArtifactReqDetails artifact = new ArtifactReqDetails(); + artifact.setArtifactName(artifactName); + + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion, + ValidationUtils.convertToSystemName(resourceDetailes.getName()), resourceDetailes.getVersion(), + artifactName)); + + Map authorizationHeaders = new HashMap(); + authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resourceDetailes, + artifact, designerUser, authorizationHeaders); + assertEquals("Check response code after download resource", 404, restResponse.getErrorCode().intValue()); + + // validate audit + String auditAction = "DArtifactDownload"; + + ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, + BaseRestUtils.ecomp, relativeUrl, "404", "SVC4504: Error: Resource version 0.2 was not found."); + AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction); + } + + @Test + public void downloadResourceArtifact_ServiceNameNotFound() throws Exception { + // Create resource + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser); + assertEquals("Check response code after creating resource", 201, createResource.getErrorCode().intValue()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse()); + download_serviceNameNotFound_inner("notExistingServiceName", serviceBaseVersion, resource.getName(), + resource.getVersion()); + + } + + @Test + public void downloadResourceArtifact_ServiceVersionNotFound() throws Exception { + // Create resource + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser); + assertEquals("Check response code after creating resource", 201, createResource.getErrorCode().intValue()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse()); + + // Create service + RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser); + assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue()); + serviceUniqueId = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse()) + .getUniqueId(); + + download_serviceVersionNotFound_inner(serviceDetails.getName(), "0.3", resource.getName(), + resource.getVersion()); + } + + @Test + public void downloadServiceArtifact_ServiceNameNotFound() throws Exception { + download_serviceNameNotFound_inner("notExistingServiceName", serviceBaseVersion, null, null); + + } + + @Test + public void downloadServiceArtifact_ServiceVersionNotFound() throws Exception { + + // Create service + RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser); + assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue()); + serviceUniqueId = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse()) + .getUniqueId(); + + download_serviceVersionNotFound_inner(serviceDetails.getName(), "0.2", null, null); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java new file mode 100644 index 0000000000..80b70d675e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java @@ -0,0 +1,385 @@ +/*- + * ============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.ci.tests.execute.externalapi; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +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.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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.NormativeTypesEnum; +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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class DownloadArtifactsTest extends ComponentBaseTest { + @Rule + public static TestName name = new TestName(); + + Gson gson = new Gson(); + + public DownloadArtifactsTest() { + super(name, DownloadArtifactsTest.class.getName()); + } + + private User sdncDesignerDetails; + private User sdncAdminDetails; + private ImportReqDetails resourceDetailsVF_01; + private ResourceReqDetails resourceDetailsVF_02; + private ResourceReqDetails resourceDetailsVF_03; + private ResourceReqDetails resourceDetailsCP_01; + private ServiceReqDetails serviceDetails_01; + private ServiceReqDetails serviceDetails_02; + public static String rootPath = System.getProperty("user.dir"); + + @BeforeMethod(alwaysRun = true) + public void before() throws Exception { + init(); + createComponents(); + } + + private void createComponents() throws Exception { + createAtomicResource(resourceDetailsCP_01); + importVfWithArtifacts(resourceDetailsVF_01); + createVF(resourceDetailsVF_03); + createVF(resourceDetailsVF_02); + createService(serviceDetails_01); + } + + public void init() { + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + resourceDetailsVF_01 = ElementFactory.getDefaultImportResourceByType("VF100", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + resourceDetailsVF_02 = ElementFactory.getDefaultResourceByType("VF200", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + resourceDetailsVF_03 = ElementFactory.getDefaultResourceByType("VF300", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("CP100", NormativeTypesEnum.PORT, + ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.CP.toString()); + serviceDetails_01 = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY, + sdncDesignerDetails.getUserId()); + serviceDetails_02 = ElementFactory.getDefaultService("newtestservice2", ServiceCategoriesEnum.MOBILITY, + sdncDesignerDetails.getUserId()); + } + + @Test + public void downloadResourceInstanceArtifactsFromServiceTest() throws Exception { + Service service = createServiceWithRIsWithArtifacts(); + Map deploymentArtifacts; + List resourceInstances = service.getComponentInstances(); + for (ComponentInstance ri : resourceInstances) { + deploymentArtifacts = ri.getDeploymentArtifacts(); + for (ArtifactDefinition artifact : deploymentArtifacts.values()) { + assertNotNull(downloadResourceInstanceArtifact(service, ri, artifact)); + } + } + } + + @Test + public void downloadServiceArtifactsTest() throws Exception { + Service service = createServiceWithArtifacts(); + Map deploymentArtifacts = service.getDeploymentArtifacts(); + for (ArtifactDefinition artifact : deploymentArtifacts.values()) { + assertNotNull(downloadServiceArtifact(service, artifact)); + } + + } + + private Service createServiceWithArtifacts() throws Exception { + + ArtifactReqDetails otherArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType()); + + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService( + otherArtifactDetails, sdncDesignerDetails, serviceDetails_01.getUniqueId()); + assertTrue( + "response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + + addInformationalArtifactToService.getErrorCode(), + addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + ArtifactReqDetails yangXmlArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.YANG_XML.getType()); + + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(yangXmlArtifactDetails, + sdncDesignerDetails, serviceDetails_01.getUniqueId()); + assertTrue( + "response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + + addInformationalArtifactToService.getErrorCode(), + addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + RestResponse createServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + return ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()); + } + + private RestResponse downloadResourceInstanceArtifact(Service service, ComponentInstance ri, + ArtifactDefinition artifact) throws Exception { + String url = String.format(Urls.GET_DOWNLOAD_SERVICE_RI_ARTIFACT, "localhost", "8080", service.getUUID(), + ri.getUniqueId(), artifact.getArtifactUUID()); + String userId = sdncDesignerDetails.getUserId(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY="); + headersMap.put("X-ECOMP-InstanceID", "test"); + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + sendAuthorizationRequest(); + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null + && response.getResponse().getBytes().length == 0) { + return null; + } + return response; + } + + private RestResponse downloadServiceArtifact(Service service, ArtifactDefinition artifact) throws Exception { + String url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT, "localhost", "8080", service.getUUID(), + artifact.getArtifactUUID()); + String userId = sdncDesignerDetails.getUserId(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY="); + headersMap.put("X-ECOMP-InstanceID", "test"); + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + sendAuthorizationRequest(); + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null + && response.getResponse().getBytes().length == 0) { + return null; + } + return response; + + } + + private RestResponse sendAuthorizationRequest() throws IOException { + String url = String.format(Urls.POST_AUTHORIZATION, "localhost", "8080"); + String userId = sdncAdminDetails.getUserId(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, + "{\"consumerName\":\"test\",\"consumerPassword\":\"0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b\",\"consumerSalt\":\"2a1f887d607d4515d4066fe0f5452a50\"}", + headersMap); + if (response.getErrorCode() != 201) { + return null; + } + return response; + } + + private Service createServiceWithRIsWithArtifacts() throws Exception { + serviceDetails_02.setUniqueId(serviceDetails_01.getUniqueId()); + createTreeCheckedinVFInstances(); + LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncDesignerDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01, + sdncDesignerDetails); + RestResponse updateServiceResp = ServiceRestUtils.updateService(serviceDetails_02, sdncDesignerDetails); + ServiceRestUtils.checkSuccess(updateServiceResp); + getComponentAndValidateRIs(serviceDetails_01, 5, 0); + + return ResponseParser.convertServiceResponseToJavaObject(updateServiceResp.getResponse()); + } + + private void createTreeCheckedinVFInstances() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createSecondVFInstResp); + RestResponse createThirdVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_03, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createThirdVFInstResp); + } + + private Component getComponentAndValidateRIs(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; + } + + private void createVFInstanceAndAtomicResourceInstanceWithoutCheckin(ResourceReqDetails vf, + ResourceReqDetails atomicResource, User user) throws Exception { + RestResponse createVFInstance = createVFInstance(serviceDetails_01, vf, user); + ResourceRestUtils.checkCreateResponse(createVFInstance); + RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, atomicResource, user); + ResourceRestUtils.checkCreateResponse(atomicInstanceForService); + } + + private RestResponse createCheckedinVFInstance(ServiceReqDetails containerDetails, + ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + changeResourceLifecycleState(compInstOriginDetails, modifier.getUserId(), LifeCycleStatesEnum.CHECKIN); + return createVFInstance(containerDetails, compInstOriginDetails, modifier); + } + + private RestResponse createVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, + User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, + true); + } + + private RestResponse createAtomicInstanceForService(ServiceReqDetails containerDetails, + ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, + true); + } + + private RestResponse createComponentInstance(ComponentReqDetails containerDetails, + ComponentReqDetails compInstOriginDetails, User modifier, ComponentTypeEnum containerComponentTypeEnum, + boolean isHighestLevel) throws IOException, Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(compInstOriginDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum); + return createResourceInstanceResponse; + } + + private void changeResourceLifecycleState(ResourceReqDetails resourceDetails, String userUserId, + LifeCycleStatesEnum lifeCycleStates) throws Exception { + RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, userUserId, lifeCycleStates); + LifecycleRestUtils.checkLCS_Response(response); + } + + private void createAtomicResource(ResourceReqDetails resourceDetails) throws Exception { + RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceResponse); + + } + + private void createVF(ResourceReqDetails resourceDetails) throws Exception { + createVF(resourceDetails, sdncDesignerDetails); + + } + + private void createVF(ResourceReqDetails resourceDetails, User sdncModifier) throws Exception { + RestResponse createVfResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifier); + ResourceRestUtils.checkCreateResponse(createVfResponse); + } + + private void createService(ServiceReqDetails serviceDetails) throws Exception { + createService(serviceDetails, sdncDesignerDetails); + } + + private void createService(ServiceReqDetails serviceDetails, User sdncModifier) throws Exception { + RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifier); + ResourceRestUtils.checkCreateResponse(createServiceResponse); + } + + private void importVfWithArtifacts(ImportReqDetails resourceDetailsVF_01) throws Exception { + String payloadName = "VF_RI2_G4_withArtifacts.csar"; + Path path = Paths.get(rootPath + "/src/main/resources/ci/VF_RI2_G4_withArtifacts.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetailsVF_01.setPayloadData(payloadData); + + resourceDetailsVF_01.setPayloadName(payloadName); + resourceDetailsVF_01.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetailsVF_01, sdncDesignerDetails); + BaseRestUtils.checkCreateResponse(createResource); + } + +} 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 new file mode 100644 index 0000000000..c52ee470cf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java @@ -0,0 +1,442 @@ +/*- + * ============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========================================================= + */ + +//US505653 +package org.openecomp.sdc.ci.tests.execute.general; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +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.ComponentInstanceReqDetails; +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.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit; +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.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class BasicHttpAuthenticationTest extends ComponentBaseTest { + + protected static final String AUTH_FAILED_INVALID_AUTHENTICATION_HEADER = "AUTH_FAILED_INVALID_AUTHENTICATION_HEADER"; + + protected static final String AUTH_SUCCESS = "AUTH_SUCCESS"; + + protected static final String AUTH_FAILED_INVALID_PASSWORD = "AUTH_FAILED_INVALID_PASSWORD"; + + protected static final String AUTH_FAILED_USER_NOT_FOUND = "AUTH_FAILED_USER_NOT_FOUND"; + + protected static final String AUTH_REQUIRED = "AUTH_REQUIRED"; + + protected static final String WWW_AUTHENTICATE = "WWW-Authenticate"; + + // user ci password 123456 + // protected final String authorizationHeader = "Basic Y2k6MTIzNDU2"; + // user ci password 123456 + protected final String USER = "ci"; + + protected final String PASSWORD = "123456"; + + protected final String SALT = "2a1f887d607d4515d4066fe0f5452a50"; + + protected final String HASHED_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"; + + protected User sdncAdminUserDetails; + + protected ConsumerDataDefinition consumerDataDefinition; + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + protected User sdncUserDetails; + + protected ArtifactReqDetails deploymentArtifact; + + protected ExpectedAuthenticationAudit expectedAuthenticationAudit; + + protected final String auditAction = "HttpAuthentication"; + + protected String expectedDownloadServiceUrl; + protected String expectedDownloadResourceUrl; + protected ComponentInstanceReqDetails componentInstanceReqDetails; + + @Rule + public static TestName name = new TestName(); + + public BasicHttpAuthenticationTest() { + super(name, BasicHttpAuthenticationTest.class.getName()); + } + + @BeforeMethod + public void init() throws Exception { + + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + Resource resourceObject = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetails = new ResourceReqDetails(resourceObject); + Service serviceObject = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + serviceDetails = new ServiceReqDetails(serviceObject); + + deploymentArtifact = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(deploymentArtifact, + sdncUserDetails, resourceDetails.getUniqueId()); + AssertJUnit.assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + // certified resource + response = LifecycleRestUtils.certifyResource(resourceDetails); + AssertJUnit.assertTrue("certify resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + // add resource instance with HEAT deployment artifact to the service + componentInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(componentInstanceReqDetails, sdncUserDetails, + serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + AssertJUnit.assertTrue("response code is not 201, returned: " + response.getErrorCode(), + response.getErrorCode() == 201); + expectedAuthenticationAudit = new ExpectedAuthenticationAudit(); + + // RestResponse addDeploymentArtifactResponse = + // ArtifactRestUtils.addInformationalArtifactToService(deploymentArtifact, + // sdncUserDetails, serviceDetails.getUniqueId()); + // assertEquals("didn't succeed to upload deployment artifact", 200, + // addDeploymentArtifactResponse.getErrorCode().intValue()); + // + // downloadUrl = + // String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, + // ValidationUtils.convertToSystemName(serviceDetails.getServiceName()), + // serviceDetails.getVersion(), + // ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName())); + + expectedDownloadResourceUrl = String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, + ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(), + ValidationUtils.convertToSystemName(resourceDetails.getName()), resourceDetails.getVersion(), + ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName())); + 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("/sdc/".length(), + expectedDownloadServiceUrl.length()); + + sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + consumerDataDefinition = createConsumer(); + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + ; + + RestResponse createResponse = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncAdminUserDetails); + BaseRestUtils.checkCreateResponse(createResponse); + + } + + @AfterMethod + public void tearDown() throws Exception { + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + ; + } + + @Test + public void sendAuthenticatedRequestTest_success() throws Exception, Exception { + DbUtils.cleanAllAudits(); + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(USER, PASSWORD); + // RestResponse restResponse = + // ArtifactRestUtils.downloadServiceArtifact(serviceDetails, + // deploymentArtifact, sdncUserDetails, authorizationHeader); + RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resourceDetails, + deploymentArtifact, sdncUserDetails, authorizationHeader); + AssertJUnit.assertEquals("Check response code after download artifact", 200, + restResponse.getErrorCode().intValue()); + AssertJUnit.assertFalse(restResponse.getHeaderFields().containsKey(HttpHeaderEnum.WWW_AUTHENTICATE.getValue())); + + validateAuditAuthentication(USER, AUTH_SUCCESS, ComponentTypeEnum.RESOURCE); + + } + + protected void validateAuditAuthentication(String userName, String AuthStatus, ComponentTypeEnum compType) + throws Exception { + if (compType.equals(ComponentTypeEnum.RESOURCE)) { + expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadResourceUrl, userName, + auditAction, AuthStatus); + } else { + expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadServiceUrl, userName, + auditAction, AuthStatus); + } + AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit); + } + + protected ConsumerDataDefinition createConsumer() { + ConsumerDataDefinition consumer = new ConsumerDataDefinition(); + consumer.setConsumerName(USER); + consumer.setConsumerSalt(SALT); + consumer.setConsumerPassword(HASHED_PASSWORD); + return consumer; + + } + + @Test + public void sendAuthenticatedRequestWithoutHeadersTest() throws Exception, Exception { + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, new HashMap()); + assertEquals("Check response code after download artifact", 401, restResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_REQUIRED.name(), new ArrayList(), + restResponse.getResponse()); + assertTrue(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE)); + List 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\"")); + + validateAuditAuthentication("", AUTH_REQUIRED, ComponentTypeEnum.SERVICE); + } + + @Test + public void sendAuthenticatedRequestTest_userIsNotProvsioned() throws Exception, Exception { + String userName = "shay"; + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(userName, "123456"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList(), + restResponse.getResponse()); + assertFalse(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE)); + + validateAuditAuthentication(userName, AUTH_FAILED_USER_NOT_FOUND, ComponentTypeEnum.SERVICE); + } + + @Test + public void sendAuthenticatedRequestTest_userIsNull() throws Exception, Exception { + String userName = ""; + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(userName, "123456"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList(), + restResponse.getResponse()); + assertFalse(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE)); + + validateAuditAuthentication(userName, AUTH_FAILED_USER_NOT_FOUND, ComponentTypeEnum.SERVICE); + } + + @Test + public void sendAuthenticatedRequestTest_passwordIsNull() throws Exception, Exception { + String userName = "ci"; + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(userName, ""); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList(), + restResponse.getResponse()); + assertFalse(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE)); + + validateAuditAuthentication(userName, AUTH_FAILED_INVALID_PASSWORD, ComponentTypeEnum.SERVICE); + } + + @Test + public void sendAuthenticatedRequestTest_passowrdIsNotValidated() throws Exception, Exception { + String userCi = "ci"; + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(userCi, "98765"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList(), + restResponse.getResponse()); + assertFalse(restResponse.getHeaderFields().containsKey(HttpHeaderEnum.WWW_AUTHENTICATE.getValue())); + + validateAuditAuthentication(userCi, AUTH_FAILED_INVALID_PASSWORD, ComponentTypeEnum.SERVICE); + } + + @Test + public void sendAuthenticatedRequestTest_InvalidHeader() throws Exception, Exception { + String userCredentials = USER + ":" + PASSWORD; + byte[] encodeBase64 = Base64.encodeBase64(userCredentials.getBytes()); + String encodedUserCredentials = new String(encodeBase64); + Map authorizationHeader = new HashMap(); + authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 400, restResponse.getErrorCode().intValue()); + assertFalse(restResponse.getHeaderFields().containsKey(HttpHeaderEnum.WWW_AUTHENTICATE.getValue())); + + validateAuditAuthentication("", AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, ComponentTypeEnum.SERVICE); + } + + @Test(enabled = false) + public void sendTwoAuthenticatedRequestsTest() throws Exception, Exception { + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(USER, PASSWORD); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + + RestResponse secondRestResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after second download artifact", 200, + secondRestResponse.getErrorCode().intValue()); + } + + @Test(enabled = false) + public void sendAuthenticatedRequestTest_userValidation_1() throws Exception, Exception { + + ConsumerDataDefinition consumer = new ConsumerDataDefinition(); + consumer.setConsumerName("cI2468"); + consumer.setConsumerPassword(HASHED_PASSWORD); + consumer.setConsumerSalt(SALT); + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + + RestResponse createResponse = ConsumerRestUtils.createConsumer(consumer, sdncAdminUserDetails); + BaseRestUtils.checkCreateResponse(createResponse); + + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(consumer.getConsumerName(), + PASSWORD); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + + deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + } + + // ECOMP Consumer Name - UTF-8 string up to 255 characters containing the + // following characters : ( maybe to limit 4-64 chars ? ) + // Lowercase characters {a-z} + // Uppercase characters {A-Z} + // Numbers {0-9} + // Dash {-}; this character is not supported as the first character in the + // user name + // Period {.}; this character is not supported as the first character in the + // user name + // Underscore {_} + // @Ignore("add manually user:password 24-!68:123456 to + // users-configuration.yaml in runtime") + @Test(enabled = false) + public void sendAuthenticatedRequestTest_userValidation_2() throws Exception, Exception { + ConsumerDataDefinition consumer = new ConsumerDataDefinition(); + consumer.setConsumerName("24-!68"); + consumer.setConsumerPassword(HASHED_PASSWORD); + consumer.setConsumerSalt(SALT); + RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + + RestResponse createResponse = ConsumerRestUtils.createConsumer(consumer, sdncAdminUserDetails); + BaseRestUtils.checkCreateResponse(createResponse); + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader(consumer.getConsumerName(), + PASSWORD); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + + deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails); + BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200); + } + + // this is invalide becouse we do not use the : any more + // @Ignore("can't exectue, yaml file does not allow to enter more then one + // colon continuously (\":\") ") + @Test(enabled = false) + public void sendAuthenticatedRequestTest_userValidation_3() throws Exception, Exception { + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader("a:", "123456"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + } + + // + // * ECOMP Consumer Password - expected to be SHA-2 256 encrypted value ( + // SALT + "real" password ) => maximal length 256 bytes = 32 characters + // Before storing/comparing please convert upper case letter to lower. + // The "normalized" encrypted password should match the following format : + // [a-z0-9] + // @Ignore("add manually user:password 2468:123:456 to + // users-configuration.yaml in runtime") + @Test(enabled = false) + public void sendAuthenticatedRequestTest_passwordValidation_1() throws Exception, Exception { + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader("A1", "123:456"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + } + + // * ECOMP Consumer Password - expected to be SHA-2 256 encrypted value ( + // SALT + "real" password ) => maximal length 256 bytes = 32 characters + // Before storing/comparing please convert upper case letter to lower. + // The "normalized" encrypted password should match the following format : + // [a-z0-9] + @Test(enabled = false) + // @Ignore("add manually user:password 2468:Sq123a456B to + // users-configuration.yaml in runtime") + public void sendAuthenticatedRequestTest_passwordValidation_2() throws Exception, Exception { + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader("B2", "Sq123a456B"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + } + + // * ECOMP Consumer Password - expected to be SHA-2 256 encrypted value ( + // SALT + "real" password ) => maximal length 256 bytes = 32 characters + // Before storing/comparing please convert upper case letter to lower. + // The "normalized" encrypted password should match the following format : + // [a-z0-9] + @Test + // @Ignore("add C3:111T-0-*# to file") + public void sendAuthenticatedRequestTest_passwordValidation_3() throws Exception, Exception { + Map authorizationHeader = BaseRestUtils.addAuthorizeHeader("C3", "111T-0-*#"); + RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, + sdncUserDetails, authorizationHeader); + assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java new file mode 100644 index 0000000000..e4f7d396be --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java @@ -0,0 +1,53 @@ +/*- + * ============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.ci.tests.execute.general; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + +public class FeProxyTest extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public FeProxyTest() { + super(name, FeProxyTest.class.getName()); + } + + @Test + public void testFeProxy() throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + RestResponse allCategoriesTowardsFe = CategoryRestUtils.getAllCategoriesTowardsFe(defaultUser, + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + AssertJUnit.assertEquals("Check response code after get categories towards FE", 200, + allCategoriesTowardsFe.getErrorCode().intValue()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java new file mode 100644 index 0000000000..9ef8f147be --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java @@ -0,0 +1,1420 @@ +/*- + * ============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.ci.tests.execute.general; + +import static org.testng.AssertJUnit.assertEquals; + +import java.util.HashMap; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedEcomConsumerAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class ManageEcompConsumerCredentials extends ComponentBaseTest { + + protected static final String ADD_ECOMP_USER_CREDENTIALS = "AddECOMPUserCredentials"; + protected static final String DELETE_ECOMP_USER_CREDENTIALS = "DeleteECOMPUserCredentials"; + protected static final String GET_ECOMP_USER_CREDENTIALS = "GetECOMPUserCredentials"; + + public static final String contentTypeHeaderData = "application/json"; + public static final String acceptHeaderData = "application/json"; + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_SUCSESS_CREATED = 201; + public static final int STATUS_CODE_SUCCESS_DELETE_GET = 200; + public static final int STATUS_CODE_INVALID_CONTENT = 400; + public static final int STATUS_CODE_MISSING_DATA = 400; + public static final int STATUS_CODE_MISSING_INFORMATION = 403; + public static final int STATUS_CODE_RESTRICTED_ACCESS = 403; + + public static final int STATUS_CODE_NOT_FOUND = 404; + public static final int STATUS_CODE_RESTRICTED_OPERATION = 409; + + protected static Gson gson = new Gson(); + protected ConsumerDataDefinition consumerDataDefinition; + protected User sdncAdminUserDetails; + protected User sdncDesignerUserDetails; + protected User sdncTesterUserDetails; + protected User sdncGovernorUserDetails; + protected User sdncOpsUserDetails; + + public ManageEcompConsumerCredentials() { + super(name, ManageEcompConsumerCredentials.class.getName()); + } + + @Rule + public static TestName name = new TestName(); + + protected String salt = "123456789012345678901234567890ab"; + protected String password = "123456789012345678901234567890ab123456789012345678901234567890ab"; + protected String ecompUser = "benny"; + + protected Long consumerDetailsLastupdatedtime; + + @BeforeMethod + public void init() throws Exception { + sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncDesignerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncTesterUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncGovernorUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + sdncOpsUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + + consumerDataDefinition = new ConsumerDataDefinition(); + consumerDataDefinition.setConsumerName(ecompUser); + consumerDataDefinition.setConsumerPassword(password); + consumerDataDefinition.setConsumerSalt(salt); + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + + } + + // US563681 manage ECOMP consumer credentials - DELETE/GET + @Test + public void deleteEcompCredentialsMethodDelete() throws Exception { + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + AssertJUnit.assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + AssertJUnit.assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + // DbUtils.deleteFromEsDbByPattern("_all"); + DbUtils.cleanAllAudits(); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + AssertJUnit.assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS_DELETE_GET, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCCESS_DELETE_GET); + // Get Consumer to verify that consumer user does not exist + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + AssertJUnit.assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + } + + //// US561728 CREATE ECOMP consumer credentials + @Test + public void createEcompCredentialsMethodPost() throws Exception { + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + // Validate actual consumerData to returned from response + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + } + + @Test(enabled = false) + public void createEcompCredentialsUserAlreayExist() throws Exception { + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + + // Create consumer which already exists with different password and Salt + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerPassword("zxcvb"); + consumerDataDefinition.setConsumerSalt("1234567890qwertyuiop1234567890as"); + createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer with new data + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsByDesigner() throws Exception { // HttpCspUserId + // header + // contains + // Designer + // UserId + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncDesignerUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION); + } + + @Test + public void createEcompCredentialsByTester() throws Exception { // HttpCspUserId + // header + // contains + // Tester + // UserId + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncTesterUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION); + } + + @Test + public void createEcompCredentialsByOps() throws Exception { // HttpCspUserId + // header + // contains + // OPS + // UserId + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncOpsUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncOpsUserDetails, ActionStatus.RESTRICTED_OPERATION); + } + + @Test + public void createEcompCredentialsByGovernor() throws Exception { // HttpCspUserId + // header + // contains + // Governor + // UserId + // Create + // Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncGovernorUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncGovernorUserDetails, ActionStatus.RESTRICTED_OPERATION); + } + + @Test + public void createEcompCredentialsByNoExistingIUser() throws Exception { + User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + noSdncUserDetails.setRole("blabla"); + noSdncUserDetails.setUserId("bt750h"); + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, noSdncUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser( + consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase() + + "," + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("")); + expectedEcomConsumerAuditJavaObject.setModifier("(" + noSdncUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + // user name + @Test + public void createEcompCredentialsUserNameIsNull() throws Exception { + consumerDataDefinition.setConsumerName(null); // SVC4528 + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA, + createConsumerRest.getErrorCode().intValue()); + // verify taht consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerSalt().toLowerCase() + "," + + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer name")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsUserNameIsEmpty() throws Exception { + consumerDataDefinition.setConsumerName(""); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerSalt().toLowerCase() + "," + + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer name")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsUserNameIsNotUTF8() throws Exception { + consumerDataDefinition.setConsumerName("בני"); // SVC4528 + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void createEcompCredentialsUserNameMaxLength() throws Exception { + consumerDataDefinition.setConsumerName( + "_ABCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.-"); // SVC4528 + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Validate actual consumerData to returned from response + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsUserNameExceedMaxLength() throws Exception { + consumerDataDefinition.setConsumerName( + "_ABCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.--"); // SVC4528 + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.EXCEEDS_LIMIT, "Consumer name", "255"); + } + + @Test + public void createEcompCredentialsUserNameLastCharIsDash() throws Exception { // allowed + consumerDataDefinition.setConsumerName("ABCD34567890pf34567890poiutrew-"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject , Validate actual consumerData + // to returned from response + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsUserNameLastCharIsPeriod() throws Exception { + consumerDataDefinition.setConsumerName("ABCD34567890pf34567890poiutrew."); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject , Validate actual consumerData + // to returned from response + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsUserNameLastCharIsUnderscore() throws Exception { + consumerDataDefinition.setConsumerName("ABCD34567890pf34567890poiutrew_"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject , Validate actual consumerData + // to returned from response + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsUserNameFirstCharIsUnderscore() throws Exception { + consumerDataDefinition.setConsumerName("_ABCD34567890pf34567890poiutre"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject , Validate actual consumerData + // to returned from response + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsUserNameFirstCharIsPeriod() throws Exception { + consumerDataDefinition.setConsumerName(".ABCD34567890pf34567890poiutre"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer name"); + } + + @Test + public void createEcompCredentialsUserNameFirstCharIsDash() throws Exception { // Not + // allowed + consumerDataDefinition.setConsumerName("-ABCD34567890pf34567890poiutre"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer name"); + } + + /// Password + @Test + public void createEcompCredentialsPasswordIsNull() throws Exception { + consumerDataDefinition.setConsumerPassword(null); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA, + createConsumerRest.getErrorCode().intValue()); + // verify taht consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerSalt().toLowerCase()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer password")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsPasswordIsEmpty() throws Exception { + consumerDataDefinition.setConsumerPassword(""); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA, + createConsumerRest.getErrorCode().intValue()); + // verify taht consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerSalt().toLowerCase()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer password")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsPasswordMaxLength() throws Exception { // password + // must + // be + // 64 + // chars + consumerDataDefinition.setConsumerPassword("123456789012345678901234567890ab123456789012345678901234567890ab"); + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + // Validate actual consumerData to returned from response + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + // Delete Consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsPasswordExceeedMaxLength() throws Exception { // password + // must + // be + // 64 + // chars + consumerDataDefinition.setConsumerPassword("123456789012345678901234567890ab123456789012345678901234567890ab1"); + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_LENGTH, "Consumer password", "64"); + } + + @Test + public void createEcompCredentiaPasswordValid() throws Exception { + // Password Contains lowercase/uppercase characters and numbers - + // convert upper case letter to lower + consumerDataDefinition.setConsumerPassword("ABCabc1234567890POImnb12345678901234567890POIUzxcvbNMASDFGhjkl12"); + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + + } + + //// Salt + @Test + public void createEcompCredentialsSaltIsNull() throws Exception { + // Length must be 32 characters + consumerDataDefinition.setConsumerSalt(null); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerPassword().toLowerCase()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + + } + + @Test + public void createEcompCredentialsSaltIsEmpty() throws Exception { + consumerDataDefinition.setConsumerSalt(""); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerPassword().toLowerCase()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsSaltLengthLessThan32() throws Exception { + consumerDataDefinition.setConsumerSalt("123456789012345678901234567890a"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_LENGTH, "Consumer salt"); + + } + + // Bug + @Test + public void createEcompCredentialsSaltLengthMoreThan32() throws Exception { // Length + // must + // be + // 32 + // characters + // - + // SVC4529 + // "Error: + // Invalid + // Content. + // %1 + // exceeds + // limit + // of + // %2 + // characters." + consumerDataDefinition.setConsumerSalt("123456789012345678901234567890abc"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_LENGTH, "Consumer salt"); + + } + + @Test + public void createEcompCredentialsSaltUppercaseCharacters() throws Exception { + // Contains uppercase characters– exception invalid content + consumerDataDefinition.setConsumerSalt("123456789012345678901234567890AB"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // verify that consumer didn't created + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT_PARAM.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt")); + expectedEcomConsumerAuditJavaObject + .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + // USER_ID (USER_ID is taken from USER_ID header) + + @Test + public void createEcompCredentialsHttpCspUserIdIsEmpty() throws Exception { + // USER_ID is taken from USER_ID header + sdncAdminUserDetails.setUserId(""); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt")); + expectedEcomConsumerAuditJavaObject.setModifier(""); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsHttpCspUserIdIsNull() throws Exception { // USER_ID + // is + // taken + // from + // USER_ID + // header + sdncAdminUserDetails.setUserId(null); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt")); + expectedEcomConsumerAuditJavaObject.setModifier(""); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + @Test + public void createEcompCredentialsHttpCspUserIdHeaderIsMissing() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumerHttpCspAtuUidIsMissing(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + "," + + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt")); + expectedEcomConsumerAuditJavaObject.setModifier(""); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + ADD_ECOMP_USER_CREDENTIALS); + } + + // add USER_ID in json body + @Test + public void createEcompCredentiaJsonBodyContainLastModfierAtuid() throws Exception { + // Add USER_ID (not admin) to json - we will ignore and create the user + HashMap jsonMap = new HashMap(); + jsonMap.put("consumerName", "benny"); + jsonMap.put("consumerPassword", "123456789012345678901234567890ab123456789012345678901234567890ab"); + jsonMap.put("consumerSalt", "123456789012345678901234567890ab"); + jsonMap.put("lastModfierAtuid", "cs0008"); // designer + Gson gson = new Gson(); + ConsumerDataDefinition consumer = gson.fromJson(jsonMap.toString(), ConsumerDataDefinition.class); + + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumer, sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Validate actual consumerData to returned from response + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumer, getConsumerDataObject); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumer, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumer, sdncAdminUserDetails, + STATUS_CODE_SUCSESS_CREATED); + // Delete consumer + ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails); + } + + @Test + public void createEcompCredentialsUserNameNotAllowedCharacters() throws Exception { + char invalidChars[] = { '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/', + '"', ':', '}', ']', '[', '{', '|', '\\', ' ', '\t', '\n' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerName(invalidChars[i] + "ABCdef123"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer name"); + } + } + + @Test + public void createEcompCredentialsPasswordIsInvalid() throws Exception { + char invalidChars[] = { '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/', + '"', ':', '}', ']', '[', '{', '|', '\\', ' ', '\t', '\n' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerPassword( + "ABC" + invalidChars[i] + "ABCabc1234567890POImnb12345678901234567890POIUzxcvbNMASDFGhj"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer password"); + } + } + + @Test + public void createEcompCredentialsSaltNotAllowedCharacters() throws Exception { // Salt + // must + // be + // 32 + // chars + char invalidChars[] = { '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/', + '"', ':', '}', ']', '[', '{', '|', '\\', ' ', '\t', '\n' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerSalt(invalidChars[i] + "1234567890123456789012345678901"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer salt"); + } + } + + @Test + public void createEcompCredentialsPasswordEncoded() throws Exception { + consumerDataDefinition.setConsumerPassword("0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + // Validate actual consumerData to returned from response + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED); + } + + // + + @Test + public void deleteEcompUserAlreayDeleted() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete ECOMP consumer + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS_DELETE_GET, + deleteConsumerRest.getErrorCode().intValue()); + // Try to delete ECOMP consumer already deleted + DbUtils.deleteFromEsDbByPattern("_all"); + deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + } + + @Test + public void deleteEcompUserByTester() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncTesterUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Verify that consumer is not deleted + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void deleteEcompUserByOps() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncOpsUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncOpsUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Verify that consumer is not deleted + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void deleteEcompUserByGovernor() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncGovernorUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncGovernorUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Verify that consumer is not deleted + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void deleteEcompUserByDesigner() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncDesignerUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Verify that consumer is not deleted + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void deleteEcompUserByNoExistingIUser() throws Exception { + User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + noSdncUserDetails.setRole("blabla"); + noSdncUserDetails.setUserId("bt750h"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, noSdncUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_ACCESS, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("")); + expectedEcomConsumerAuditJavaObject.setModifier("(" + noSdncUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + DELETE_ECOMP_USER_CREDENTIALS); + // Verify that consumer is not deleted + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void deleteEcompCredentialsUserDoesNotExist() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + + } + + @Test + public void deleteEcompCredentialsUserNameIsNull() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerName(null); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + } + + @Test + public void deleteEcompCredentialsUserNameMaxLength() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerName( + "_BCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.--"); // SVC4528 + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + } + + @Test + public void deleteEcompCredentialsUserNameExceedMaxLength() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerName( + "_XXXBCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.--"); // SVC4528 + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + } + + @Test + public void deleteEcompCredentialsHttpCspUserIdHeaderIsMissing() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse createConsumerRest = ConsumerRestUtils.deleteConsumerHttpCspAtuUidIsMissing(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION, + createConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(DELETE_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc()); + expectedEcomConsumerAuditJavaObject.setModifier(""); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + DELETE_ECOMP_USER_CREDENTIALS); + } + + @Test + public void deleteEcompCredentialsNameIsUpperCase() throws Exception { + consumerDataDefinition.setConsumerName("benny"); + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete consumer + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerName("BENNY"); + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + deleteConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + // Get Consumer to verify that consumer user was not deleted + consumerDataDefinition.setConsumerName("benny"); + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + } + + @Test + public void getEcompCredentialsMethodGet() throws Exception { + // Create Consumer + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + // Validate actual consumerData to returned from response + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + DbUtils.deleteFromEsDbByPattern("_all"); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCCESS_DELETE_GET); + // Delete consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void getEcompUserAlreayDeleted() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + // Delete ECOMP consumer + RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS_DELETE_GET, + deleteConsumerRest.getErrorCode().intValue()); + DbUtils.deleteFromEsDbByPattern("_all"); + // Try to get ECOMP consumer already deleted + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + } + + @Test + public void getEcompUserByTester() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer by Tester user + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncTesterUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Get Consumer by Admin + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void getEcompUserByOps() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer by Ops user + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncOpsUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncOpsUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Get Consumer by Admin + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void getEcompUserByGovernor() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer by Ops user + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncGovernorUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncGovernorUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Get Consumer by Admin + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void getEcompUserByDesigner() throws Exception { + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // Get Consumer by Designer user + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncDesignerUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION); + // Get Consumer by Admin + getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } + + @Test + public void getEcompUserByNoExistingIUser() throws Exception { + User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + noSdncUserDetails.setRole("blabla"); + noSdncUserDetails.setUserId("bt750h"); + // Get Consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, noSdncUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_ACCESS, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(GET_ECOMP_USER_CREDENTIALS); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("")); + expectedEcomConsumerAuditJavaObject.setModifier("(" + noSdncUserDetails.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, + GET_ECOMP_USER_CREDENTIALS); + } + + @Test + public void getEcompCredentialsUserDoesNotExist() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + + } + + @Test + public void getEcompCredentialsUserNameIsNull() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + consumerDataDefinition.setConsumerName(null); + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, + getConsumerRest.getErrorCode().intValue()); + // Audit validation + AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName()); + } + + @Test + public void getEcompCredentialsUserNameMaxLength() throws Exception { + consumerDataDefinition.setConsumerName( + "_ABCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.-"); // SVC4528 + RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, + sdncAdminUserDetails); + assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED, + createConsumerRest.getErrorCode().intValue()); + // parse updated response to javaObject + ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest); + // Validate actual consumerData to returned from response + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Get Consumer + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails); + assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS, + getConsumerRest.getErrorCode().intValue()); + getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest); + ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject); + // Audit validation + AuditValidationUtils.ecompConsumerAuditSuccess(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition, + sdncAdminUserDetails, STATUS_CODE_SUCCESS_DELETE_GET); + // Delete consumer + ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java new file mode 100644 index 0000000000..acb7e15c6c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java @@ -0,0 +1,104 @@ +/*- + * ============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.ci.tests.execute.general; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.List; +import java.util.UUID; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.common.api.Constants; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + +public class UuidTest extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public UuidTest() { + super(name, UuidTest.class.getName()); + config = Config.instance(); + } + + @Test + public void testE2EUuidHeaderReturnedAndPreserved() throws IOException { + UUID randomUUID = UUID.randomUUID(); + String uuidStr = randomUUID.toString(); + RestResponse allTagsTowardsCatalogFe = CatalogRestUtils.getAllCategoriesTowardsCatalogFeWithUuid(uuidStr); + AssertJUnit.assertEquals(allTagsTowardsCatalogFe.getErrorCode(), new Integer(200)); + List list = allTagsTowardsCatalogFe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER); + // check that header is returned + AssertJUnit.assertTrue(list != null && !list.isEmpty()); + String receivedUuid = list.get(0); + // Check that same uuid returned + AssertJUnit.assertEquals(uuidStr, receivedUuid); + } + + @Test + public void testUuidHeaderGeneratedBe() throws IOException { + RestResponse allTagsTowardsCatalogBe = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + List list = allTagsTowardsCatalogBe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER); + // check that response was OK + assertEquals(allTagsTowardsCatalogBe.getErrorCode(), new Integer(200)); + // check that header is returned + assertTrue(list != null && !list.isEmpty()); + String uuid = list.get(0); + // Check there is no conversion error + UUID.fromString(uuid); + } + + @Test + public void testE2EOptionsNoUuid() throws IOException { + RestResponse allTagsTowardsCatalogFe = ResourceRestUtils.sendOptionsTowardsCatalogFeWithUuid(); + assertEquals(allTagsTowardsCatalogFe.getErrorCode(), new Integer(200)); + List list = allTagsTowardsCatalogFe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER); + // check that header is returned (generated by BE) + assertTrue(list != null && !list.isEmpty()); + String receivedUuid = list.get(0); + // Check there is no conversion error + UUID.fromString(receivedUuid); + } + + @Test + public void testE2EMethodNotAllowedWithUuid() throws IOException { + UUID randomUUID = UUID.randomUUID(); + String uuidStr = randomUUID.toString(); + RestResponse allTagsTowardsCatalogFe = ResourceRestUtils + .putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(uuidStr); + assertEquals(allTagsTowardsCatalogFe.getErrorCode(), new Integer(405)); + List list = allTagsTowardsCatalogFe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER); + // check that header is returned (generated by BE) + assertTrue(list != null && !list.isEmpty()); + String receivedUuid = list.get(0); + // Check that same uuid returned + assertEquals(uuidStr, receivedUuid); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java new file mode 100644 index 0000000000..650ed619b7 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java @@ -0,0 +1,460 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.FileUtils; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +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.ci.tests.api.ComponentBaseTest; +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.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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.common.util.YamlToObjectConverter; +import org.testng.annotations.Test; +import org.yaml.snakeyaml.Yaml; + +public class CsarUtilsTest extends ComponentBaseTest { + + public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; + + @Rule + public static TestName name = new TestName(); + + public CsarUtilsTest() { + super(name, CsarUtilsTest.class.getName()); + } + + @Test(enabled = true) + public void createServiceCsarBasicTest() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, + true, true); + resourceVF = (Resource) AtomicOperationUtils + .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service); + + csarBasicValidation(service, downloadCSAR); + } + + @Test(enabled = true) + public void createResourceCsarBasicTest() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + 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); + } + + @Test(enabled = true) + public void createServiceCsarInclDeploymentArtTest() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + 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); + + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, service, UserRoleEnum.DESIGNER, true, true); + + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service); + + csarBasicValidation(service, downloadCSAR); + + validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 5, 1); + } + + @Test(enabled = true) + public void createResourceCsarInclDeploymentArtTest() throws Exception { + + 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); + + resourceVF1 = (Resource) AtomicOperationUtils + .changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF1); + + csarBasicValidation(resourceVF1, downloadCSAR); + + validateVFCsar(resourceVF1, downloadCSAR, 1, 0, 1, 1); + } + + private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) { + try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR); + ZipInputStream zip = new ZipInputStream(ins);) { + + String resourceYaml = null; + byte[] buffer = new byte[1024]; + ZipEntry nextEntry = zip.getNextEntry(); + StringBuffer sb = new StringBuffer(); + int len; + + while ((len = zip.read(buffer)) > 0) { + sb.append(new String(buffer, 0, len)); + } + + assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta")); + + sb.setLength(0); + nextEntry = zip.getNextEntry(); + + while ((len = zip.read(buffer)) > 0) { + sb.append(new String(buffer, 0, len)); + } + + resourceYaml = sb.toString(); + + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + ArtifactDefinition artifactDefinition = mainComponent.getToscaArtifacts() + .get(ASSET_TOSCA_TEMPLATE); + String fileName = artifactDefinition.getArtifactName(); + assertEquals("Tosca-Template file name: ", "Definitions/" + fileName, nextEntry.getName()); + assertTrue("Tosca template Yaml validation: ", yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); + + ins.close(); + zip.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void validateServiceCsar(Component certifiedVFC1, Component certifiedVFC2, Service fetchedService, + byte[] resultByte, int toscaEntryIndexToPass, int generatorEntryIndexToPass, + int deploymentArtifactIndexToPass) { + + // TODO Test to validate everything is right (comment out after testing) + /*try { + FileUtils.writeByteArrayToFile(new File("c:/TestCSAR/" + fetchedService.getName() + ".zip"), resultByte); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + }*/ + + try (ByteArrayInputStream ins = new ByteArrayInputStream(resultByte); + ZipInputStream zip = new ZipInputStream(ins);) { + + String resourceYaml = null; + byte[] buffer = new byte[1024]; + ZipEntry nextEntry = zip.getNextEntry(); + StringBuffer sb = new StringBuffer(); + int len; + + while ((len = zip.read(buffer)) > 0) { + sb.append(new String(buffer, 0, len)); + } + + assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta")); + + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + + int toscaEntryIndex = 0; + int generatorEntryIndex = 0; + int deploymentArtifactIndex = 0; + String fileName = null; + ArtifactDefinition artifactDefinition; + Component componentToValidate = null; + + artifactDefinition = fetchedService.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); + String serviceFileName = artifactDefinition.getArtifactName(); + artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); + String vfc1FileName = artifactDefinition.getArtifactName(); + artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); + String vfc2FileName = artifactDefinition.getArtifactName(); + + while ((nextEntry = zip.getNextEntry()) != null) { + sb.setLength(0); + + while ((len = zip.read(buffer)) > 0) { + sb.append(new String(buffer, 0, len)); + } + + String entryName = nextEntry.getName(); + + resourceYaml = sb.toString(); + if (entryName.contains(serviceFileName)) { + componentToValidate = fetchedService; + fileName = "Definitions/" + serviceFileName; + + assertEquals("Validate entry Name", (fileName), nextEntry.getName()); + assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); + validateContent(resourceYaml, componentToValidate); + ++toscaEntryIndex; + continue; + } + + if (entryName.contains(vfc1FileName)) { + componentToValidate = certifiedVFC1; + fileName = "Definitions/" + vfc1FileName; + + assertEquals("Validate entry Name", (fileName), nextEntry.getName()); + assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); + validateContent(resourceYaml, componentToValidate); + ++toscaEntryIndex; + continue; + } + if (entryName.contains(vfc2FileName)) { + componentToValidate = certifiedVFC2; + fileName = "Definitions/" + vfc2FileName; + + assertEquals("Validate entry Name", (fileName), nextEntry.getName()); + assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); + validateContent(resourceYaml, componentToValidate); + ++toscaEntryIndex; + continue; + } + + if (entryName.contains(".xml") && !entryName.startsWith("Artifacts/AAI")) { + ++deploymentArtifactIndex; + continue; + } + + if (entryName.startsWith("Artifacts/AAI")) { + ++generatorEntryIndex; + continue; + } + + assertTrue("Unexpected entry: " + entryName, true); + } + assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex); + assertEquals("Validate amount of generated AAI artifacts", generatorEntryIndexToPass, generatorEntryIndex); + assertEquals("Validate amount of generated Deployment artifacts", deploymentArtifactIndexToPass, + deploymentArtifactIndex); + + ins.close(); + zip.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void validateVFCsar(Component certifiedVF, byte[] resultByte, int toscaEntryIndexToPass, int ymlDeploymentArtifactIndexToPass, + int xmlDeploymentArtifactIndexToPass, int heatEnvDeploymentArtifactIndexToPass) { + + // TODO Test to validate everything is right (comment out after testing) + /*try { + FileUtils.writeByteArrayToFile(new File("c:/TestCSAR/" + fetchedService.getName() + ".zip"), resultByte); + } catch (IOException e) { + // Auto-generated catch block + e.printStackTrace(); + }*/ + + try (ByteArrayInputStream ins = new ByteArrayInputStream(resultByte); + ZipInputStream zip = new ZipInputStream(ins);) { + + String resourceYaml = null; + byte[] buffer = new byte[1024]; + ZipEntry nextEntry = zip.getNextEntry(); + StringBuffer sb = new StringBuffer(); + int len; + + while ((len = zip.read(buffer)) > 0) { + sb.append(new String(buffer, 0, len)); + } + + assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta")); + + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + + int toscaEntryIndex = 0; + int ymlEntryIndex = 0; + int xmlArtifactsIndex = 0; + int heatEnvDeploymentArtifactIndex = 0; + String fileName = null; + ArtifactDefinition artifactDefinition; + Component componentToValidate = null; + + artifactDefinition = certifiedVF.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); + String vfFileName = artifactDefinition.getArtifactName(); + + while ((nextEntry = zip.getNextEntry()) != null) { + sb.setLength(0); + + while ((len = zip.read(buffer)) > 0) { + sb.append(new String(buffer, 0, len)); + } + + String entryName = nextEntry.getName(); + + resourceYaml = sb.toString(); + if (entryName.contains(vfFileName)) { + componentToValidate = certifiedVF; + fileName = "Definitions/" + vfFileName; + + assertEquals("Validate entry Name", (fileName), nextEntry.getName()); + assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); + validateContent(resourceYaml, componentToValidate); + ++toscaEntryIndex; + continue; + } + + if (entryName.contains(".xml") && entryName.startsWith("Artifacts/")) { + ++xmlArtifactsIndex; + continue; + } + + if (entryName.contains(".sh") && entryName.startsWith("Artifacts/")) { + ++heatEnvDeploymentArtifactIndex; + continue; + } + + if (entryName.contains(".yml") && entryName.startsWith("Artifacts/")) { + ++ymlEntryIndex; + continue; + } + + assertTrue("Unexpected entry: " + entryName, false); + } + assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex); + assertEquals("Validate amount of YAML artifacts", ymlDeploymentArtifactIndexToPass, ymlEntryIndex); + assertEquals("Validate amount of generated XML artifacts", xmlDeploymentArtifactIndexToPass, + xmlArtifactsIndex); + assertEquals("Validate amount of generated HEAT ENV artifacts", heatEnvDeploymentArtifactIndexToPass, + heatEnvDeploymentArtifactIndex); + + ins.close(); + zip.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void validateContent(String content, Component component) { + Yaml yaml = new Yaml(); + + InputStream inputStream = new ByteArrayInputStream(content.getBytes()); + @SuppressWarnings("unchecked") + Map load = (Map) yaml.load(inputStream); + @SuppressWarnings("unchecked") + Map metadata = (Map) load.get("metadata"); + assertNotNull(metadata); + + String name = (String) metadata.get("name"); + assertNotNull(name); + assertEquals("Validate component name", component.getName(), name); + + String invariantUUID = (String) metadata.get("invariantUUID"); + assertNotNull(invariantUUID); + assertEquals("Validate component invariantUUID", component.getInvariantUUID(), invariantUUID); + + String UUID = (String) metadata.get("UUID"); + assertNotNull(UUID); + assertEquals("Validate component invariantUUID", 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); + } else { + assertEquals("Validate component type", ((Resource) component).getResourceType(), + ResourceTypeEnum.valueOf(type)); + } + } + + private byte[] downloadCSAR(User sdncModifierDetails, Component createdComponent) throws Exception { + + String artifactUniqeId = createdComponent.getToscaArtifacts().get("assettoscacsar").getUniqueId(); + RestResponse getCsarResponse = null; + + switch (createdComponent.getComponentType()) { + case RESOURCE: + getCsarResponse = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdComponent.getUniqueId(), + sdncModifierDetails, artifactUniqeId); + break; + case SERVICE: + getCsarResponse = ArtifactRestUtils.downloadServiceArtifactInternalApi(createdComponent.getUniqueId(), + sdncModifierDetails, artifactUniqeId); + break; + default: + break; + } + + assertNotNull(getCsarResponse); + BaseRestUtils.checkSuccess(getCsarResponse); + + ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(getCsarResponse.getResponse(), + ArtifactUiDownloadData.class); + + assertNotNull(artifactUiDownloadData); + + byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes(); + byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload); + + return decodeBase64; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java new file mode 100644 index 0000000000..163504fbb0 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java @@ -0,0 +1,458 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactUiDownloadData; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +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.tosca.ToscaPropertyType; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +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.ServiceCategoriesEnum; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.InputsRestUtils; +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.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.testng.annotations.Test; +import org.yaml.snakeyaml.Yaml; + +import com.google.gson.Gson; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +public class ExportToscaTest extends ComponentBaseTest { + @Rule + public static TestName name = new TestName(); + + public ExportToscaTest() { + super(name, ExportToscaTest.class.getName()); + } + + @Test(enabled = true) + public void exportVfModuleTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Resource createdResource = createVfFromCSAR(sdncModifierDetails, "VSPPackage"); + + Map load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource); + assertNotNull(load); + Map topology_template = (Map) load.get("topology_template"); + assertNotNull(topology_template); + Map groups = (Map) topology_template.get("groups"); + assertNotNull(groups); + List groupsOrigin = createdResource.getGroups(); + + assertEquals("Validate groups size", groupsOrigin.size(), groups.size()); + for (GroupDefinition group : groupsOrigin) { + Map groupTosca = (Map) groups.get(group.getName()); + assertNotNull(groupTosca); + + Map metadata = (Map) groupTosca.get("metadata"); + assertNotNull(metadata); + + String invariantUUID; + String name; + String UUID; + String version; + Map properties = (Map) groupTosca.get("properties"); + + if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { + invariantUUID = (String) metadata.get("vfModuleModelInvariantUUID"); + name = (String) metadata.get("vfModuleModelName"); + UUID = (String) metadata.get("vfModuleModelUUID"); + version = (String) metadata.get("vfModuleModelVersion"); + assertNotNull(properties); + + String vf_module_type = (String) properties.get("vf_module_type"); + List props = group.getProperties(); + for (PropertyDataDefinition prop : props) { + if (prop.getName().equals(Constants.IS_BASE)) { + String value = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); + boolean bvalue = Boolean.parseBoolean(value); + if (bvalue) { + assertEquals("Validate vf_module_type", "Base", vf_module_type); + } else { + assertEquals("Validate vf_module_type", "Expansion", vf_module_type); + } + break; + } + } + String vf_module_description = (String) properties.get("vf_module_description"); + assertEquals("Validate vf_module_description", group.getDescription(), vf_module_description); + + Boolean volume_group = (Boolean) properties.get("volume_group"); + boolean isVolume = false; + List artifactsList = group.getArtifacts(); + List artifacts = new ArrayList<>(); + if (artifactsList != null && !artifactsList.isEmpty()) { + ArtifactDefinition masterArtifact = findMasterArtifact(createdResource.getDeploymentArtifacts(), + artifacts, artifactsList); + if (masterArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + isVolume = true; + } + } + assertEquals("Validate volume_group", isVolume, volume_group); + + } else { + invariantUUID = (String) metadata.get("invariantUUID"); + name = (String) metadata.get("name"); + UUID = (String) metadata.get("UUID"); + version = (String) metadata.get("version"); + assertNull(properties); + + } + assertEquals("Validate InvariantUUID", group.getInvariantUUID(), invariantUUID); + assertEquals("Validate name", group.getName(), name); + assertEquals("Validate UUID", group.getGroupUUID(), UUID); + assertEquals("Validate version", group.getVersion(), version); + + } + } + + @Test(enabled = true) + public void exportCsarInputsTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1"); + Map load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource); + assertNotNull(load); + + Map topology_template = (Map) load.get("topology_template"); + assertNotNull(topology_template); + + Map inputs = (Map) topology_template.get("inputs"); + assertNotNull(inputs); + + List inputsFromResource = createdResource.getInputs(); + assertEquals("validate inputs size", inputsFromResource.size(), inputs.size()); + for (InputDefinition inputDef : inputsFromResource) { + Map inputInFile = (Map) inputs.get(inputDef.getName()); + assertNotNull(inputInFile); + validateInput(inputDef, inputInFile); + } + List componentInstances = createdResource.getComponentInstances(); + Map> componentInstancesProperties = createdResource + .getComponentInstancesProperties(); + Map node_templates = (Map) topology_template.get("node_templates"); + assertNotNull(node_templates); + + JsonParser jsonParser = new JsonParser(); + + for (Map.Entry> entry : componentInstancesProperties.entrySet()) { + + Optional findFirst = componentInstances.stream() + .filter(ci -> ci.getUniqueId().equals(entry.getKey())).findFirst(); + assertTrue(findFirst.isPresent()); + String resourceName = findFirst.get().getName(); + Map instance = (Map) node_templates.get(resourceName); + assertNotNull(instance); + Map properties = (Map) instance.get("properties"); + + for (ComponentInstanceProperty cip : entry.getValue()) { + if (cip.getValueUniqueUid() != null && !cip.getValueUniqueUid().isEmpty()) { + assertNotNull(properties); + if (cip.getValue().contains("get_input")) { + Object prop = properties.get(cip.getName()); + assertNotNull(prop); + + Gson gson = new Gson(); + String json = gson.toJson(prop); + assertEquals("validate json property", cip.getValue(), json); + } + + } + } + + } + + } + + @Test + public void importExportCsarWithJsonPropertyType() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "jsonPropertyTypeTest.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + path = Paths.get(rootPath + "/src/test/resources/CI/csars/jsonPropertyTypeTest.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + ComponentInstance pmaaServer = resource.getComponentInstances().stream() + .filter(p -> p.getName().equals("pmaa_server_0")).findAny().get(); + ComponentInstanceProperty jsonProp = resource.getComponentInstancesProperties().get(pmaaServer.getUniqueId()) + .stream().filter(p -> p.getType().equals(ToscaPropertyType.JSON.getType())).findAny().get(); + String jsonValue = "{\"pmaa.sb_nic\":{\"address\":{\"get_input\":\"pmaa_dpu_fixed_ip\"},\"cidr\":{\"get_input\":\"pmaa_dpu_cidr\"},\"gateway\":{\"get_input\":\"pmaa_dpu_gateway\"}}}"; + assertEquals(jsonProp.getValue(), jsonValue); + // download and compare + Map load = downloadAndParseToscaTemplate(sdncModifierDetails, resource); + assertNotNull(load); + Map topology_template = (Map) load.get("topology_template"); + assertNotNull(topology_template); + Map nodes = (Map) topology_template.get("node_templates"); + assertNotNull(nodes); + Map pmaaServerObj = (Map) nodes.get("pmaa_server_0"); + assertNotNull(pmaaServerObj); + Map props = (Map) pmaaServerObj.get("properties"); + assertNotNull(props); + Map jsonPropObj = (Map) props.get("metadata"); + assertNotNull(jsonPropObj); + Gson gson = new Gson(); + String json = gson.toJson(jsonPropObj); + assertEquals(json, jsonValue); + } + + @Test(enabled = true) + public void exportServiceInputValue() throws Exception { + //1 create vf as certified + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1"); + RestResponse checkinState = LifecycleRestUtils.changeComponentState(createdResource, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + BaseRestUtils.checkSuccess(checkinState); + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId()); + + //2 create service + RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails); + ResourceRestUtils.checkCreateResponse(createServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class); + + //3 create vf instance in service + ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(createdResource); + RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service); + ResourceRestUtils.checkCreateResponse(createComponentInstance); + + RestResponse getService = ServiceRestUtils.getService(service.getUniqueId()); + BaseRestUtils.checkSuccess(getService); + service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class); + + //4 download tosca template + Map tosca = downloadAndParseToscaTemplate(sdncModifierDetails, service); + assertNotNull(tosca); + Map topology_template = (Map) tosca.get("topology_template"); + assertNotNull(topology_template); + + //5 validate no inputs in service + Map inputs = (Map) tosca.get("inputs"); + assertNull(inputs); + + List componentInstances = service.getComponentInstances(); + assertNotNull(componentInstances); + assertEquals(1, componentInstances.size()); + ComponentInstance vfi = componentInstances.get(0); + + //6 add instance inputs in service + RestResponse getComponentInstanceInputsResponse = InputsRestUtils.getComponentInstanceInputs(service, vfi); + BaseValidationUtils.checkSuccess(getComponentInstanceInputsResponse); + List instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken>(){}.getType()); + // Take only the 2 first inputs + List inputsToAdd = instanceInputs.stream().limit(2).collect(Collectors.toList()); + + //7 Build component instances input map to add to server + ComponentInstInputsMap buildComponentInstInputsMap = buildComponentInstInputsMap(vfi.getUniqueId(), inputsToAdd); + RestResponse addInputResponse = InputsRestUtils.addInput(service, buildComponentInstInputsMap, UserRoleEnum.DESIGNER); + BaseValidationUtils.checkSuccess(addInputResponse); + + //8 validate inputs in service + //8.1 download tosca template + getService = ServiceRestUtils.getService(service.getUniqueId()); + BaseRestUtils.checkSuccess(getService); + service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class); + + tosca = downloadAndParseToscaTemplate(sdncModifierDetails, service); + assertNotNull(tosca); + topology_template = (Map) tosca.get("topology_template"); + assertNotNull(topology_template); + + //8.2 validate inputs in service + inputs = (Map) topology_template.get("inputs"); + assertNotNull(inputs); + assertEquals(2, inputs.size()); + + //validate created inputs vs inputs in Tosca inputs section + final Map inputsFinal = inputs; + buildComponentInstInputsMap.getComponentInstanceInputsMap().values().forEach(listPerInstance ->{ + listPerInstance.forEach(input ->{ + Map inputInMap = (Map)inputsFinal.get(input.getName()); + assertNotNull(inputInMap); + }); + }); + Map> componentInstancesInputs = service.getComponentInstancesInputs(); + + //validate created inputs vs inputs in Tosca instance input value + List vfiInputs = componentInstancesInputs.get(vfi.getUniqueId()); + assertNotNull(vfiInputs); + assertEquals(2, vfiInputs.size()); + + Map node_templates = (Map) topology_template.get("node_templates"); + assertNotNull(node_templates); + + Map instance = (Map) node_templates.get(vfi.getName()); + assertNotNull(instance); + Map properties = (Map)instance.get("properties"); + assertNotNull(properties); + + vfiInputs.forEach(vfiInput ->{ + Map inputPropValueInTosca = (Map)properties.get(vfiInput.getName() ); + assertNotNull(inputPropValueInTosca); + String instaneInputName = (String)inputPropValueInTosca.get("get_input"); + assertNotNull(instaneInputName); + Map inputInMap = (Map)inputsFinal.get(instaneInputName); + assertNotNull(inputInMap); + }); + + + } + + + // ---------------------------------------- + private void validateInput(InputDefinition inputDef, Map inputInFile) { + assertEquals("validate input type", inputDef.getType(), (String) inputInFile.get("type")); + + if (inputDef.getDefaultValue() == null) { + assertNull(inputInFile.get("default")); + } else { + assertNotNull(inputInFile.get("default")); + String value = inputDef.getDefaultValue().replace("\"", ""); + value = value.replace(" ", ""); + String expValue = inputInFile.get("default").toString().replace(" ", ""); + assertEquals("validate input default", value, expValue); + } + assertEquals("validate input description", inputDef.getDescription(), (String) inputInFile.get("description")); + } + + private Map downloadAndParseToscaTemplate(User sdncModifierDetails, Component createdComponent) + throws Exception { + String artifactUniqeId = createdComponent.getToscaArtifacts().get("assettoscatemplate").getUniqueId(); + RestResponse toscaTemplate; + + if ( createdComponent.getComponentType() == ComponentTypeEnum.RESOURCE ){ + toscaTemplate = ArtifactRestUtils.downloadResourceArtifactInternalApi( + createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId); + + }else{ + toscaTemplate = ArtifactRestUtils.downloadServiceArtifactInternalApi( + createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId); + } + BaseRestUtils.checkSuccess(toscaTemplate); + + ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(toscaTemplate.getResponse(), + ArtifactUiDownloadData.class); + byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes(); + byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload); + Yaml yaml = new Yaml(); + + InputStream inputStream = new ByteArrayInputStream(decodeBase64); + + Map load = (Map) yaml.load(inputStream); + return load; + } + + + public ArtifactDefinition findMasterArtifact(Map deplymentArtifact, + List artifacts, List artifactsList) { + for (String artifactUid : artifactsList) { + for (Entry entry : deplymentArtifact.entrySet()) { + ArtifactDefinition artifact = entry.getValue(); + if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) { + artifacts.add(artifact); + } + + } + } + ArtifactDefinition masterArtifact = null; + for (ArtifactDefinition artifactInfo : artifacts) { + String atrifactType = artifactInfo.getArtifactType(); + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) + || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { + masterArtifact = artifactInfo; + continue; + } + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + masterArtifact = artifactInfo; + break; + } + } + return masterArtifact; + } + private ComponentInstInputsMap buildComponentInstInputsMap (String addToInput, List inputs) { + Map> map = new HashMap<>(); + map.put(addToInput, inputs); + ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap(); + componentInstInputsMap.setComponentInstanceInputsMap(map); + return componentInstInputsMap; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java new file mode 100644 index 0000000000..1b559aaaad --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java @@ -0,0 +1,1751 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.tinkerpop.gremlin.process.traversal.P; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +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.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupProperty; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +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.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +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.ServiceCategoriesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.GroupRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils; +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.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class ImportCsarResourceTest extends ComponentBaseTest { + private static Logger log = LoggerFactory.getLogger(ImportCsarResourceTest.class.getName()); + @Rule + public static TestName name = new TestName(); + + Gson gson = new Gson(); + + public ImportCsarResourceTest() { + super(name, ImportCsarResourceTest.class.getName()); + } + + private String buildAssertMessage(String expectedString, String actualString) { + return String.format("expected is : %s , actual is: %s", expectedString, actualString); + } + + /** + * + * User Story : US640615 [BE] - Extend create VF API with Import TOSCA CSAR + */ + + @Test(enabled = true) + public void createResourceFromCsarHappy() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("AF7F231969C5463F9C968570070E8877"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + String expectedCsarUUID = resourceDetails.getCsarUUID(); + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void emptyStringInCsarUUIDFieldTest() throws Exception { + String emptyString = ""; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(emptyString); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(null, resource.getComponentInstances()); + + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(emptyString, resource.getCsarUUID()), resource.getCsarUUID() == emptyString); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(emptyString, getResource.getCsarUUID()), getResource.getCsarUUID() == emptyString); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void createResourceFromScratchTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(null, resource.getComponentInstances()); + + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(null, resource.getCsarUUID()), resource.getCsarUUID() == null); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(null, getResource.getCsarUUID()), getResource.getCsarUUID() == null); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void fileNotCsarTypeTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("valid_vf_zip"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_NOT_FOUND.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void missingToscaMetadataFolderTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("toscaFolderNotExists"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void missingToscaMetaFileTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("toscaMetaFileNotExists"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void toscaMetaFileOutsideTheFolderTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("toscaMetaOutsideTheFolder"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void caseSensitiveTest_1() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("caseSensitiveTest_1"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void caseSensitiveTest_2() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("caseSensitiveTest_2"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void missingOneLineInToscaMetaFileTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("missingOneLineInToscaMeta"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void noCSARVersionTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("noCSARVersion"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void noCreatedByValueTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("noCreatedByValue"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void noEntryDefinitionsValueTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("noEntryDefinitionsValue"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void noTOSCAMetaFileVersionValueTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("noTOSCAMetaFileVersionValue"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void invalidCsarVersionInMetaFileTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("invalidCsarVersion"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + + resourceDetails.setCsarUUID("invalidCsarVersion2"); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + + resourceDetails.setCsarUUID("invalidCsarVersion3"); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + + resourceDetails.setCsarUUID("invalidCsarVersion4"); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + + resourceDetails.setCsarUUID("invalidCsarVersion5"); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + + } + + @Test(enabled = true) + public void validCsarVersionInMetaFileTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("validCsarVersion"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + String expectedCsarUUID = resourceDetails.getCsarUUID(); + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void underscoreInToscaMetaFileVersionNameTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("underscoreInsteadOfDash"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void missingEntryDefintionInMetaFileTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("missingEntryDefintionPair"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = false) + public void noNewLineAfterBLock0Test() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("noNewLineAfterBLock0"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void moreThanOneYamlFileTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("moreThenOneYamlFile"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + String expectedCsarUUID = resourceDetails.getCsarUUID(); + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void moreThanOneMetaFileTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("moreThanOneMetaFile"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + String expectedCsarUUID = resourceDetails.getCsarUUID(); + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void csarNotContainsYamlAndMetaFilesTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("notContainYamlAndMetaFiles"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void csarNotContainsYamlFileTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("notContainYamlFile"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + variables.add("Definitions/tosca_mock_vf.yaml"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.YAML_NOT_FOUND_IN_CSAR.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void missingCsarFileTest() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("abc"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_NOT_FOUND.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void longNamesInToscaMetaFileTest_1() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("longNamesInToscaMetaFile1"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void longNamesInToscaMetaFileTest_2() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("longNamesInToscaMetaFile2"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void longNamesInToscaMetaFileTest_3() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("longNamesInToscaMetaFile3"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void longNamesInToscaMetaFileTest_4() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("longNamesInToscaMetaFile4"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void longNamesInToscaMetaFileTest_5() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("longNamesInToscaMetaFile5"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + // possible to have more than four lines in block 0 + // @Test (enabled = true) + public void fiveLinesAsBlock0Test() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + resourceDetails.setCsarUUID("fiveLinesAsBlock0"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + List variables = new ArrayList(); + variables.add(resourceDetails.getCsarUUID()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse()); + } + + @Test(enabled = true) + public void lifecycleChangingToResourceFromCsarTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("valid_vf"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertTrue("0.1".equals(resource.getVersion())); + assertTrue(LifeCycleStatesEnum.CHECKOUT.getComponentState().equals(resource.getLifecycleState().toString())); + + String designerUserId = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId(); + String testerUserId = ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId(); + String csarUniqueId = resourceDetails.getUniqueId(); + assertNotNull(csarUniqueId); + + RestResponse lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUserId, LifeCycleStatesEnum.STARTCERTIFICATION); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUserId, LifeCycleStatesEnum.CERTIFY); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + + resource = ResponseParser.parseToObjectUsingMapper(lifecycleChangeResponse.getResponse(), Resource.class); + Map allVersions = resource.getAllVersions(); + assertEquals(2, allVersions.keySet().size()); + assertEquals(2, allVersions.values().size()); + Set keySet = allVersions.keySet(); + assertTrue(keySet.contains("1.0")); + assertTrue(keySet.contains("1.1")); + } + + @Test(enabled = true) + public void csarWithJsonPromEnvTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("VSPPackageJsonProp.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + } + + @Test(enabled = true) + public void uploadArtifactToResourceFromCsarTest() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("valid_vf"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + + User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact("firstArtifact"); + String firstArtifactLabel = artifactDetails.getArtifactLabel(); + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, designer, resourceDetails.getUniqueId()); + ArtifactRestUtils.checkSuccess(addInformationalArtifactToResource); + RestResponse getResourceResponse = ResourceRestUtils.getResource(resourceDetails.getUniqueId()); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + Map informationalArtifacts = resource.getArtifacts(); + assertEquals(1, informationalArtifacts.keySet().size()); + Set keySet = informationalArtifacts.keySet(); + assertTrue(keySet.contains(firstArtifactLabel.toLowerCase())); + Collection values = informationalArtifacts.values(); + assertEquals(1, values.size()); + Iterator iterator = values.iterator(); + while (iterator.hasNext()) { + ArtifactDefinition actualArtifact = iterator.next(); + assertTrue(firstArtifactLabel.equals(actualArtifact.getArtifactDisplayName())); + } + + RestResponse lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designer.getUserId(), LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designer.getUserId(), LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + + ArtifactReqDetails artifactDetails2 = ElementFactory.getDefaultArtifact("secondArtifact"); + artifactDetails2.setArtifactName("secondArtifact"); + addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails2, designer, resourceDetails.getUniqueId()); + ArtifactRestUtils.checkSuccess(addInformationalArtifactToResource); + + getResourceResponse = ResourceRestUtils.getResource(resourceDetails.getUniqueId()); + resource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + informationalArtifacts = resource.getArtifacts(); + assertEquals(2, informationalArtifacts.keySet().size()); + keySet = informationalArtifacts.keySet(); + assertTrue(keySet.contains(firstArtifactLabel.toLowerCase())); + assertTrue(keySet.contains(artifactDetails2.getArtifactLabel().toLowerCase())); + values = informationalArtifacts.values(); + assertEquals(2, values.size()); + ArtifactDefinition[] actualArtifacts = values.toArray(new ArtifactDefinition[2]); + assertTrue(firstArtifactLabel.equals(actualArtifacts[0].getArtifactDisplayName())); + assertTrue(artifactDetails2.getArtifactLabel().equals(actualArtifacts[1].getArtifactDisplayName())); + } + + /* + * // @Test (enabled = true) public void createUpdateImportResourceFromCsarArtifactsWereNotChangedTest() throws Exception { // User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); // //back original scar RestResponse + * copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); BaseRestUtils.checkSuccess(copyRes); + * + * // resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); // RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); resourceDetails.setName("test5"); + * resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); resourceDetails.setCsarVersion("1"); // String invariantUUID = resource.getInvariantUUID(); // // RestResponse changeResourceState = + * LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); // assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + * + * // BaseRestUtils.checkSuccess(copyRes); // //change name (temporary) resourceDetails.setCsarVersion("2"); resourceDetails.setName("test6"); createResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, + * resourceDetails.getUniqueId()); Resource updatedResource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); Map updatedArtifacts = updatedResource.getDeploymentArtifacts(); for + * (Entry artifactEntry : resource.getDeploymentArtifacts().entrySet()) { if (updatedArtifacts.containsKey(artifactEntry.getKey())) { ArtifactDefinition currArt = updatedArtifacts.get(artifactEntry.getKey()); + * assertEquals(currArt.getArtifactVersion(), artifactEntry.getValue().getArtifactVersion()); assertEquals(currArt.getArtifactUUID(), artifactEntry.getValue().getArtifactUUID()); assertEquals(currArt.getArtifactChecksum(), + * artifactEntry.getValue().getArtifactChecksum()); } } // resourceDetails = ElementFactory.getDefaultResource(); // resourceDetails.setName("test5"); // resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); } + */ + + @Test(enabled = true) + public void createImportResourceFromCsarDissotiateArtifactFromGroupTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + + // create new resource from Csar + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + String invariantUUID = resource.getInvariantUUID(); + + // add artifact from metadata (resource metadata should be updated) + // RestResponse addInformationalArtifactToResource = + // ArtifactRestUtils.addInformationalArtifactToResource(ElementFactory.getDefaultArtifact(), + // sdncModifierDetails, resourceDetails.getUniqueId()); + // ArtifactRestUtils.checkSuccess(addInformationalArtifactToResource); + resourceDetails.setName("test4"); + RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(invariantUUID, resource.getInvariantUUID()); + + // wrong RI (without node types, resource shouldn't be updated) + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_dissociate.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + // change name (temporary) + resourceDetails.setName("test4"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(invariantUUID, resource.getInvariantUUID()); + + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + } + + @Test(enabled = true) + public void createImportResourceFromCsarNewgroupTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + + // create new resource from Csar + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + String invariantUUID = resource.getInvariantUUID(); + + // update scar + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_UpdateToscaAndArtifacts.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails.setName("test2"); + // change resource metaData (resource should be updated) + resourceDetails.setDescription("It is new description bla bla bla"); + RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + assertEquals(invariantUUID, resource.getInvariantUUID()); + + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + } + + @Test(enabled = true) + public void createImportResourceFromCsarGetGroupTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // RestResponse copyRes = + // copyCsarRest(sdncModifierDetails,"VF_RI2_G4_withArtifacts_a.csar","VF_RI2_G4_withArtifacts.csar"); + + // create new resource from Csar + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("VSPPackage"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + String invariantUUID = resource.getInvariantUUID(); + List groups = resource.getGroups(); + + GroupDefinition groupWithArtifact = groups.stream().filter(p -> p.getArtifacts() != null && !p.getArtifacts().isEmpty()).findFirst().get(); + + RestResponse groupRest = GroupRestUtils.getGroupById(resource, groupWithArtifact.getUniqueId(), sdncModifierDetails); + BaseRestUtils.checkSuccess(groupRest); + + GroupDefinition groupWithoutArtifact = groups.stream().filter(p -> p.getArtifacts() == null || p.getArtifacts().isEmpty()).findFirst().get(); + + groupRest = GroupRestUtils.getGroupById(resource, groupWithoutArtifact.getUniqueId(), sdncModifierDetails); + BaseRestUtils.checkSuccess(groupRest); + } + + @Test(enabled = true) + public void createImportResourceFromCsarUITest() throws Exception { + RestResponse getResource = null; + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "valid_vf.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + // create new resource from Csar + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change composition (resource should be updated) + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_b.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + // change name + resourceDetails.setName("test1"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(2, resource.getComponentInstances().size()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change name + resourceDetails.setName("test2"); + // change resource metaData (resource should be updated) + resourceDetails.setDescription("It is new description bla bla bla"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(2, resource.getComponentInstances().size()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // wrong RI (without node types, resource shouldn't be updated) + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_c.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + // change name + resourceDetails.setName("test3"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/tosca_mock_vf.yaml", "nodejs", "tosca.nodes.Weber"); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(null, resource); + getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test3", resourceDetails.getVersion()); + BaseRestUtils.checkErrorResponse(getResource, ActionStatus.RESOURCE_NOT_FOUND, "test3"); + + // create new resource from other Csar + resourceDetails = ElementFactory.getDefaultImportResource(); + path = Paths.get(rootPath + "/src/main/resources/ci/VF_RI2_G4_withArtifacts.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setPayloadName("VF_RI2_G4_withArtifacts.csar"); + resourceDetails.setName("test4"); + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // wrong RI (with node types) resource shouldn't be created + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts_b.csar"); + path = Paths.get(rootPath + "/src/main/resources/ci/VF_RI2_G4_withArtifacts_b.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setPayloadName("VF_RI2_G4_withArtifacts_b.csar"); + resourceDetails.setName("test5"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/VF_RI2_G1.yaml", "ps04_port_0", "org.openecomp.resource.cp.nodes.heat.network.neutron.Portur"); + } + + @Test(enabled = true) + public void createUpdateImportResourceFromCsarUITest() throws Exception { + RestResponse getResource = null; + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "valid_vf.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + // create new resource from Csar + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change composition and update resource + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_b.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setUniqueId(resource.getUniqueId()); + // change name + RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(2, resource.getComponentInstances().size()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change name + resourceDetails.setName("test2"); + // change resource metaData (resource should be updated) + resourceDetails.setDescription("It is new description bla bla bla"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(2, resource.getComponentInstances().size()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // try to update resource with wrong RI (without node types, resource + // shouldn't be updated) + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_c.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + // change name + resourceDetails.setName("test3"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId()); + BaseRestUtils.checkErrorResponse(updateResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/tosca_mock_vf.yaml", "nodejs", "tosca.nodes.Weber"); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(null, resource); + getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test3", resourceDetails.getVersion()); + BaseRestUtils.checkErrorResponse(getResource, ActionStatus.RESOURCE_NOT_FOUND, "test3"); + } + + @Test(enabled = true) + public void createUpdateImportResourceFromCsarTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = null; + RestResponse getResource = null; + ResourceReqDetails resourceDetails = null; + RestResponse updateResource = null; + RestResponse createResource = null; + Resource resource = null; + RestResponse changeResourceState = null; + + // create new resource from Csar + copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar"); + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("valid_vf.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + String invariantUUID = resource.getInvariantUUID(); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change composition and update resource + copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_b.csar", "valid_vf.csar"); + BaseRestUtils.checkSuccess(copyRes); + // change name + resourceDetails.setName("test1"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(2, resource.getComponentInstances().size()); + assertEquals(invariantUUID, resource.getInvariantUUID()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar"); + BaseRestUtils.checkSuccess(copyRes); + + // change name + resourceDetails.setName("test2"); + // change resource metaData and update resource + resourceDetails.setDescription("It is new description bla bla bla"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + assertEquals(invariantUUID, resource.getInvariantUUID()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar"); + BaseRestUtils.checkSuccess(copyRes); + + // try to update resource with wrong RI (without node types, resource + // shouldn't be updated) + copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_c.csar", "valid_vf.csar"); + BaseRestUtils.checkSuccess(copyRes); + // change name (temporary) + resourceDetails.setName("test3"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId()); + BaseRestUtils.checkErrorResponse(updateResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/tosca_mock_vf.yaml", "nodejs", "tosca.nodes.Weber"); + + getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test3", resourceDetails.getVersion()); + BaseRestUtils.checkErrorResponse(getResource, ActionStatus.RESOURCE_NOT_FOUND, "test3"); + getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test2", resourceDetails.getVersion()); + BaseRestUtils.checkSuccess(getResource); + + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar"); + BaseRestUtils.checkSuccess(copyRes); + + // create new resource from Csar + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("TEST01"); + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // scar with wrong RI + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_b.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + resourceDetails.setDescription("BLA BLA BLA"); + // wrong RI (with node types) resource shouldn't be created + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkErrorResponse(updateResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/VF_RI2_G1.yaml", "ps04_port_0", "org.openecomp.resource.cp.nodes.heat.network.neutron.Portur"); + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + } + + @Test(enabled = true) + public void createUpdateImportResourceFromCsarWithArtifactsTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = null; + ResourceReqDetails resourceDetails = null; + RestResponse updateResource = null; + RestResponse createResource = null; + Resource resource = null; + RestResponse changeResourceState = null; + + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("TEST01"); + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); + resourceDetails.setCsarVersion("1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + // create new resource from Csar + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + List requiredArtifactsOld = resource.getDeploymentArtifacts().get("heat5").getRequiredArtifacts(); + assertTrue(requiredArtifactsOld != null && !requiredArtifactsOld.isEmpty() && requiredArtifactsOld.size() == 3); + assertTrue(requiredArtifactsOld.contains("hot-nimbus-pcm-volumes_v1.0.yaml")); + assertTrue(requiredArtifactsOld.contains("nested-pcm_v1.0.yaml")); + assertTrue(requiredArtifactsOld.contains("hot-nimbus-oam-volumes_v1.0.yaml")); + + // update scar with new artifacts + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_updated.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + resourceDetails.setDescription("BLA BLA BLA"); + resourceDetails.setCsarVersion("2"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + + List requiredArtifactsNew = resource.getDeploymentArtifacts().get("heat5").getRequiredArtifacts(); + assertTrue(requiredArtifactsNew != null && !requiredArtifactsNew.isEmpty() && requiredArtifactsNew.size() == 3); + assertTrue(requiredArtifactsNew.contains("hot-nimbus-swift-container_v1.0.yaml")); + assertTrue(requiredArtifactsNew.contains("hot-nimbus-oam-volumes_v1.0.yaml")); + assertTrue(requiredArtifactsNew.contains("nested-oam_v1.0.yaml")); + + // back original scar + copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); + BaseRestUtils.checkSuccess(copyRes); + } + + @Test(enabled = true) + public void createUpdateImportWithPropertiesFromCsarUITest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "valid_vf.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + // create new resource from Csar + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change composition (add new RI with specified property values) + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_d.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + // change name + resourceDetails.setName("test1"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(6, resource.getComponentInstances().size()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + // change composition (add new specified property values to existing RI) + path = Paths.get(rootPath + "/src/main/resources/ci/valid_vf_f.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + // change name + resourceDetails.setName("test2"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(6, resource.getComponentInstances().size()); + + } + + public static RestResponse copyCsarRest(User sdncModifierDetails, String sourceCsarUuid, String targetCsarUuid) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.COPY_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), sourceCsarUuid, targetCsarUuid); + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse copyCsarResponse = http.httpSendPost(url, "dummy", headersMap); + if (copyCsarResponse.getErrorCode() != 200) { + return null; + } + return copyCsarResponse; + + } + + public static RestResponse getCsarRest(User sdncModifierDetails, String sourceCsarUuid) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), sourceCsarUuid); + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse copyCsarResponse = http.httpSendGet(url, headersMap); + if (copyCsarResponse.getErrorCode() != 200) { + return null; + } + return copyCsarResponse; + + } + + @Test(enabled = true) + public void updateResourceFromCsarHappy() throws Exception { + RestResponse copyRes = copyCsarRest(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "valid_vf_a.csar", "valid_vf.csar"); + BaseRestUtils.checkSuccess(copyRes); + // create + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("valid_vf"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + String expectedCsarUUID = resourceDetails.getCsarUUID(); + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + + RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + + } + + @Test(enabled = true) + public void createResourceFromCsarWithGroupsHappy() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroups"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + assertEquals("verify there are 2 groups", 2, resource.getGroups().size()); + + Map compNameToUniqueId = resource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId())); + + // Verify 2 members on group1 + // members: [ app_server, mongo_server ] + String[] membersNameGroup1 = { "app_server", "mongo_server" }; + verifyMembersInResource(resource, compNameToUniqueId, "group1", membersNameGroup1); + // Verify 4 members on group2 + // members: [ mongo_db, nodejs, app_server, mongo_server ] + String[] membersNameGroup2 = { "app_server", "mongo_server", "mongo_db", "nodejs" }; + verifyMembersInResource(resource, compNameToUniqueId, "group2", membersNameGroup2); + + // Check OUT + resourceDetails.setUniqueId(resource.getUniqueId()); + RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + + Resource checkedOutResource = ResponseParser.parseToObjectUsingMapper(changeResourceState.getResponse(), Resource.class); + compNameToUniqueId = checkedOutResource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId())); + + // Verify 2 members on group1 + // members: [ app_server, mongo_server ] + verifyMembersInResource(checkedOutResource, compNameToUniqueId, "group1", membersNameGroup1); + // Verify 4 members on group2 + // members: [ mongo_db, nodejs, app_server, mongo_server ] + verifyMembersInResource(checkedOutResource, compNameToUniqueId, "group2", membersNameGroup2); + + } + + private void verifyMembersInResource(Resource resource, Map compNameToUniqueId, String groupName, String[] membersName) { + GroupDefinition groupDefinition = resource.getGroups().stream().filter(p -> p.getName().equals(groupName)).findFirst().get(); + assertEquals("Verify number of members", membersName.length, groupDefinition.getMembers().size()); + Map createdMembers = groupDefinition.getMembers(); + Arrays.asList(membersName).forEach(p -> { + assertTrue("check member name exist", createdMembers.containsKey(p)); + }); + + verifyMembers(createdMembers, compNameToUniqueId); + } + + @Test(enabled = true) + public void createResourceFromCsarWithGroupsAndPropertiesHappy() throws Exception { + + RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack1", UserRoleEnum.ADMIN); + // BaseRestUtils.checkCreateResponse(importNewGroupTypeByName); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroupsWithProps"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + + assertEquals("verify there are 2 groups", 2, resource.getGroups().size()); + + Map compNameToUniqueId = resource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId())); + + // Verify 2 members on group1 + // members: [ app_server, mongo_server ] + List groupDefinition1 = resource.getGroups().stream().filter(p -> p.getName().equals("group1")).collect(Collectors.toList()); + assertEquals("Verify number of members", 2, groupDefinition1.get(0).getMembers().size()); + Map createdMembers = groupDefinition1.get(0).getMembers(); + verifyMembers(createdMembers, compNameToUniqueId); + + List properties = groupDefinition1.get(0).getProperties(); + assertEquals("Verify number of members", 2, properties.size()); + + PropertyDataDefinition heatFiles = properties.stream().filter(p -> p.getName().equals("heat_files")).findFirst().get(); + assertNotNull("check heat files not empty", heatFiles); + List heatFilesValue = new ArrayList<>(); + heatFilesValue.add("heat1.yaml"); + heatFilesValue.add("heat2.yaml"); + String heatFilesJson = gson.toJson(heatFilesValue); + log.debug(heatFiles.getValue()); + assertEquals("check heat files value", heatFilesJson, heatFiles.getValue()); + + PropertyDataDefinition urlCredential = properties.stream().filter(p -> p.getName().equals("url_credential")).findFirst().get(); + assertNotNull("check heat files not empty", urlCredential); + log.debug(urlCredential.getValue()); + assertEquals("check url credential", "{\"protocol\":\"protocol1\",\"keys\":{\"keya\":\"valuea\",\"keyb\":\"valueb\"}}", urlCredential.getValue()); + } + + @Test(enabled = true) + public void createResourceFromCsarWithGroupsAndPropertyInvalidValue() throws Exception { + + RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack1", UserRoleEnum.ADMIN); + // BaseRestUtils.checkCreateResponse(importNewGroupTypeByName); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroupsInvalidPropertyValue"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400); + + } + + @Test(enabled = true) + public void createResourceFromCsarWithGroupsAndInvalidPropertyName() throws Exception { + + RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack1", UserRoleEnum.ADMIN); + // BaseRestUtils.checkCreateResponse(importNewGroupTypeByName); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroupsPropertyNotExist"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_PROPERTY_NOT_FOUND, "url_credential111", "group1", "org.openecomp.groups.MyHeatStack1"); + + } + + @Test(enabled = true) + public void createResourceFromCsarGroupTypeNotExist() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroupsInvalidGroupType"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_TYPE_IS_INVALID, "org.openecomp.groups.stamGroupType"); + + } + + @Test(enabled = true) + public void createResourceFromCsarMemberNotExist() throws Exception { + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroupsInvalidMember"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, "mycomp", "mygroup", ValidationUtils.normaliseComponentName(resourceDetails.getName()), "VF"); + + } + + @Test(enabled = true) + public void createResourceFromCsarMemberNotAllowed() throws Exception { + + RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack2", UserRoleEnum.ADMIN); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csarWithGroupsNotAllowedMember"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, "nodejs", "group1", "org.openecomp.groups.MyHeatStack2"); + + } + + @Test(enabled = true) + public void getResourceFromCsarUuidHappy() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("tam"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(6, resource.getComponentInstances().size()); + + String expectedCsarUUID = resourceDetails.getCsarUUID(); + String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName())); + + RestResponse getResourceResponse = ResourceRestUtils.getLatestResourceFromCsarUuid(resource.getCsarUUID()); + Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class); + assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID())); + assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName())); + } + + @Test(enabled = true) + public void getResourceFromCsarResourceNotFound() throws Exception { + String csarUUID = "tam"; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + + RestResponse resResponse = ResourceRestUtils.getLatestResourceFromCsarUuid(csarUUID); + + BaseRestUtils.checkStatusCode(resResponse, "Check bad request error", false, 400); + BaseRestUtils.checkErrorResponse(resResponse, ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUUID); + + } + + @Test(enabled = true) + public void getResourceFromMissingCsar() throws Exception { + String csarUUID = "abcdefg12345"; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID(csarUUID); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + + RestResponse resResponse = ResourceRestUtils.getLatestResourceFromCsarUuid(csarUUID); + + BaseRestUtils.checkStatusCode(resResponse, "Check bad request error", false, 400); + BaseRestUtils.checkErrorResponse(resResponse, ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUUID); + + } + + @Test(enabled = true) + public void createUpdateCertifiedImportResourceFromCsarTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar"); + RestResponse updateResponse = null; + String oldName = null; + // create new resource from Csar + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("valid_vf.csar"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + String invariantUUID = resource.getInvariantUUID(); + + // change metadata + // resource name, icon, vendor name, category, template derivedFrom + oldName = resourceDetails.getName(); + resourceDetails.setName("test1"); + resourceDetails.setIcon("newicon"); + resourceDetails.setVendorName("newname"); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.VSP_ALREADY_EXISTS, "valid_vf.csar", oldName); + + updateResponse = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResponse); + + LifecycleRestUtils.certifyResource(resourceDetails); + // change metadata + // resource name, icon, vendor name, category, template derivedFrom + resourceDetails.setName("test2"); + resourceDetails.setIcon("new icon1"); + resourceDetails.setVendorName("new name1"); + resourceDetails.setDescription("bla bla bla"); + updateResponse = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResponse); + resource = ResponseParser.parseToObjectUsingMapper(updateResponse.getResponse(), Resource.class); + assertEquals(5, resource.getComponentInstances().size()); + assertEquals(invariantUUID, resource.getInvariantUUID()); + assertEquals(resource.getName(), "test1"); + assertEquals(resource.getIcon(), "newicon"); + assertEquals(resource.getVendorName(), "newname"); + assertEquals(resource.getDescription(), "bla bla bla"); + assertEquals(resource.getTags().contains("test2"), false); + } + + @Test + public void createImportRIRelationByCapNameFromCsarUITest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "vmmc_relate_by_cap_name.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + + path = Paths.get(rootPath + "/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + // create new resource from Csar + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + // assert all relations created + assertEquals(80, resource.getComponentInstancesRelations().size()); + } + + @Test + public void createImportRIRelationByCapNameFromCsarUITest2() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "vf_relate_by_cap_name.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + + path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_relate_by_cap_name.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + // create new resource from Csar + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + // assert relations created: 1.by name: virtual_linkable. 2.by name: + // link + Map nodes = resource.getComponentInstances().stream().collect(Collectors.toMap(n -> n.getName(), n -> n)); + Map capabilities = nodes.get("elinenode").getCapabilities().get("tosca.capabilities.network.Linkable").stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); + String cp1Uid = nodes.get("cp1node").getUniqueId(); + String cp2Uid = nodes.get("cp2node").getUniqueId(); + Map> mappedByReqOwner = resource.getComponentInstancesRelations().stream().collect(Collectors.groupingBy(e -> e.getFromNode())); + assertEquals(mappedByReqOwner.get(cp1Uid).get(0).getRelationships().get(0).getCapabilityUid(), capabilities.get("virtual_linkable").getUniqueId()); + assertEquals(mappedByReqOwner.get(cp2Uid).get(0).getRelationships().get(0).getCapabilityUid(), capabilities.get("link").getUniqueId()); + } + + @Test(enabled = true) + public void importCsarCheckVfHeatEnv() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("csar_1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + // 2 lisence, 1 heat, 1 heatenv + assertEquals(4, deploymentArtifacts.size()); + + ArtifactDefinition artifactHeat = deploymentArtifacts.get("heat0"); + assertNotNull(artifactHeat); + + ArtifactDefinition artifactHeatEnv = deploymentArtifacts.get("heat0env"); + assertNotNull(artifactHeatEnv); + + assertEquals(artifactHeat.getUniqueId(), artifactHeatEnv.getGeneratedFromId()); + assertEquals("VF HEAT ENV", artifactHeatEnv.getArtifactDisplayName()); + assertEquals("HEAT_ENV", artifactHeatEnv.getArtifactType()); + assertEquals("VF Auto-generated HEAT Environment deployment artifact", artifactHeatEnv.getDescription()); + + String designerUserId = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId(); + String testerUserId = ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId(); + RestResponse lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUserId, LifeCycleStatesEnum.STARTCERTIFICATION); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUserId, LifeCycleStatesEnum.CERTIFY); + LifecycleRestUtils.checkSuccess(lifecycleChangeResponse); + Resource certifiedResource = ResponseParser.parseToObjectUsingMapper(lifecycleChangeResponse.getResponse(), Resource.class); + + + User modifier = new User(); + modifier.setUserId(designerUserId); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY, designerUserId); + + RestResponse serviceRes = ServiceRestUtils.createService(serviceDetails, modifier); + ResourceRestUtils.checkCreateResponse(serviceRes); + Service service = ResponseParser.parseToObjectUsingMapper(serviceRes.getResponse(), Service.class); + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentInstance(certifiedResource); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, service.getUniqueId(), service.getComponentType()); + BaseRestUtils.checkCreateResponse(createResourceInstanceResponse); + RestResponse serviceByGet = ServiceRestUtils.getService(service.getUniqueId()); + service = ResponseParser.parseToObjectUsingMapper(serviceByGet.getResponse(), Service.class); + + List componentInstances = service.getComponentInstances(); + assertNotNull(componentInstances); + + assertEquals(1, componentInstances.size()); + ComponentInstance ci = componentInstances.get(0); + Map instDepArtifacts = ci.getDeploymentArtifacts(); + assertNotNull(instDepArtifacts); + ArtifactDefinition instArtifactHeat = instDepArtifacts.get("heat0"); + assertNotNull(instArtifactHeat); + + ArtifactDefinition instArtifactHeatEnv = instDepArtifacts.get("heat0env"); + assertNotNull(instArtifactHeatEnv); + assertEquals(artifactHeat.getUniqueId(), instArtifactHeatEnv.getGeneratedFromId()); + assertEquals("HEAT ENV", instArtifactHeatEnv.getArtifactDisplayName()); + assertEquals("HEAT_ENV", instArtifactHeatEnv.getArtifactType()); + + assertEquals(artifactHeat.getUniqueId(), instArtifactHeat.getUniqueId()); + //different artifacts + assertTrue( !artifactHeatEnv.getUniqueId().equals(instArtifactHeat.getUniqueId()) ); + + + } + + @Test(enabled = true) + public void createAndUpdateCsarCheckVfHeatEnv() throws Exception { + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setCsarUUID("orig2G_org"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + + assertEquals(13, deploymentArtifacts.size()); + + ArtifactDefinition artifactHeat = deploymentArtifacts.get("heat0"); + assertNotNull(artifactHeat); + + ArtifactDefinition artifactHeatEnv = deploymentArtifacts.get("heat0env"); + assertNotNull(artifactHeatEnv); + + assertEquals(artifactHeat.getUniqueId(), artifactHeatEnv.getGeneratedFromId()); + assertEquals("VF HEAT ENV", artifactHeatEnv.getArtifactDisplayName()); + assertEquals("HEAT_ENV", artifactHeatEnv.getArtifactType()); + assertEquals("VF Auto-generated HEAT Environment deployment artifact", artifactHeatEnv.getDescription()); + + List groups = resource.getGroups(); + assertEquals(2, groups.size()); + GroupDefinition group1 = groups.stream().filter(p -> p.getName().contains("module-0")).findAny().get(); + GroupDefinition group2 = groups.stream().filter(p -> p.getName().contains("module-1")).findAny().get(); + assertEquals(11, group1.getArtifacts().size()); + assertEquals(3, group2.getArtifacts().size()); + + resourceDetails.setCsarUUID("orig2G_update"); + + RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + + + Map deploymentArtifactsUpd = resource.getDeploymentArtifacts(); + assertNotNull(deploymentArtifactsUpd); + + assertEquals(13, deploymentArtifactsUpd.size()); + + ArtifactDefinition artifactHeatUpd = deploymentArtifacts.get("heat0"); + assertNotNull(artifactHeatUpd); + + ArtifactDefinition artifactHeatEnvUpd = deploymentArtifacts.get("heat0env"); + assertNotNull(artifactHeatEnvUpd); + + groups = resource.getGroups(); + assertEquals(2, groups.size()); + assertEquals(7, groups.get(0).getArtifacts().size()); + assertEquals(7, groups.get(1).getArtifacts().size()); + + + } + + @Test + public void importInnerVfcWithArtifactsSucceed() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String rootPath = System.getProperty("user.dir"); + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + + String payloadName = "ImportArtifactsToVFC.csar"; + Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/ImportArtifactsToVFC.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + List componentInstances = resource.getComponentInstances(); + List reducedComponentInstances = componentInstances.stream() + .filter(ci->ci.getNormalizedName().contains("server_sm")) + .collect(Collectors.toList()); + assertTrue(!reducedComponentInstances.isEmpty() && reducedComponentInstances.size() == 2); + reducedComponentInstances.stream().forEach(ci->isValidArtifacts(ci)); + + payloadName = "ImportArtifactsToVFC_empty.csar"; + path = Paths.get(rootPath + "/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setName(resourceDetails.getName()+"2"); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + componentInstances = resource.getComponentInstances(); + reducedComponentInstances = componentInstances.stream() + .filter(ci->ci.getNormalizedName().contains("server_sm")) + .collect(Collectors.toList()); + assertTrue(!reducedComponentInstances.isEmpty() && reducedComponentInstances.size() == 2); + reducedComponentInstances.stream() + .forEach(ci->assertTrue( + (ci.getDeploymentArtifacts()==null || ci.getDeploymentArtifacts().isEmpty()) && + (ci.getArtifacts()==null || ci.getArtifacts().isEmpty())) + ); + } + + private void isValidArtifacts(ComponentInstance ci) { + assertTrue(!ci.getDeploymentArtifacts().isEmpty() && ci.getDeploymentArtifacts().size() == 11); + ci.getDeploymentArtifacts().values().stream() + .forEach(a->assertTrue(a.getArtifactName().startsWith("Some"))); + + assertTrue(!ci.getArtifacts().isEmpty() && ci.getArtifacts().size() == 1); + ci.getArtifacts().values().stream() + .forEach(a->assertTrue(a.getArtifactName().startsWith("Process"))); + } + + private void verifyMembers(Map createdMembers, Map compNameToUniqueId) { + for (Map.Entry entry : createdMembers.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + String comparedValue = compNameToUniqueId.get(key); + + assertEquals("compare instance ids", comparedValue, value); + } + + } + + private static Map prepareHeadersMap(String userId) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + return headersMap; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java new file mode 100644 index 0000000000..110fa0f53c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java @@ -0,0 +1,600 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpStatus; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +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.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.TODO.ImportCapabilityTypeCITest; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +import fj.data.Either; + +public class ImportGenericResourceCITest extends ComponentBaseTest { + private static Logger log = LoggerFactory.getLogger(ImportGenericResourceCITest.class.getName()); + private static final String FILE_NAME_MY_COMPUTE = "tosca.nodes.MyCompute"; + private static final String RESOURCE_NAME_UPDATE_COMPUTE = "userUpdateCompute"; + private static final String RESOURCE_NAME_MY_COMPUTE = "myCompute"; + private static final String RESOURCE_NAME_USER_COMPUTE = "userCompute"; + private static final String FILE_NAME_USER_COMPUTE = "tosca.nodes.userCompute"; + @Rule + public static TestName name = new TestName(); + + public ImportGenericResourceCITest() { + super(name, ImportGenericResourceCITest.class.getName()); + } + + @BeforeClass + public static void beforeImportClass() throws IOException { + ImportCapabilityTypeCITest.importAllCapabilityTypes(); + // removeAllNormativeTypeResources(); + // importAllNormativeTypesResources(UserRoleEnum.ADMIN); + } + + static Config config = Config.instance(); + + public static Map removeAllNormativeTypeResources() throws ClientProtocolException, IOException { + Map normativeExistInDB = new HashMap<>(); + + for (NormativeTypesEnum current : NormativeTypesEnum.values()) { + Boolean existedBeforeDelete = ImportRestUtils.removeNormativeTypeResource(current); + normativeExistInDB.put(current, existedBeforeDelete); + } + return normativeExistInDB; + } + + public static Either getNormativeTypeResource(NormativeTypesEnum current) throws ClientProtocolException, IOException { + return getResource(current.getNormativeName(), "1.0"); + } + + @Test + public void importAllTestResources() throws Exception { + for (ImportTestTypesEnum currResource : ImportTestTypesEnum.values()) { + DbUtils.cleanAllAudits(); + + RestResponse importResponse = ImportRestUtils.importTestResource(currResource, UserRoleEnum.ADMIN); + // System.err.println("import Resource + // "+"<"+currResource+">"+"response: + // "+importResponse.getErrorCode()); + ImportRestUtils.validateImportTestTypesResp(currResource, importResponse); + if (currResource.getvalidateAudit() == true) { + // validate audit + String baseVersion = "1.0"; + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName()); + expectedResourceAuditJavaObject.setResourceName(currResource.getNormativeName()); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(baseVersion); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString()); + expectedResourceAuditJavaObject.setComment(null); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + List variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAuditImport(expectedResourceAuditJavaObject, auditAction); + } + } + } + + // ----------------------------------------------------------------------------------- + protected void validateMyComputeCapabilities(Map map) { + assertTrue(map.containsKey("capabilities")); + Map capabilities = (Map) map.get("capabilities"); + assertTrue(capabilities.containsKey("tosca.capabilities.Container")); + List hostCapList = (List) capabilities.get("tosca.capabilities.Container"); + assertFalse(hostCapList.isEmpty()); + Map hostCap = (Map) hostCapList.get(0); + validateField(hostCap, "type", "tosca.capabilities.Container"); + validateField(hostCap, "name", "host"); + validateField(hostCap, "validSourceTypes", Arrays.asList(new String[] { "tosca.nodes.SoftwareComponent" })); + + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); + List endPointCapList = (List) capabilities.get("tosca.capabilities.Endpoint.Admin"); + assertFalse(endPointCapList.isEmpty()); + Map endPointCap = (Map) endPointCapList.get(0); + validateField(endPointCap, "name", "endpoint"); + validateField(endPointCap, "type", "tosca.capabilities.Endpoint.Admin"); + + assertTrue(capabilities.containsKey("tosca.capabilities.OperatingSystem")); + List osCapList = (List) capabilities.get("tosca.capabilities.OperatingSystem"); + assertFalse(osCapList.isEmpty()); + Map osCap = (Map) osCapList.get(0); + validateField(osCap, "name", "os"); + validateField(osCap, "type", "tosca.capabilities.OperatingSystem"); + + assertTrue(capabilities.containsKey("tosca.capabilities.Scalable")); + List scalableCapList = (List) capabilities.get("tosca.capabilities.Scalable"); + assertFalse(scalableCapList.isEmpty()); + Map scalableCap = (Map) scalableCapList.get(0); + validateField(scalableCap, "name", "scalable"); + validateField(scalableCap, "type", "tosca.capabilities.Scalable"); + + assertTrue(capabilities.containsKey("tosca.capabilities.network.Bindable")); + List bindingCapList = (List) capabilities.get("tosca.capabilities.network.Bindable"); + assertFalse(bindingCapList.isEmpty()); + Map bindingCap = (Map) bindingCapList.get(0); + validateField(bindingCap, "name", "binding"); + validateField(bindingCap, "type", "tosca.capabilities.network.Bindable"); + + } + + protected void validateMyComputeResource(String resourceName, String resourceVersion, String expectedState) throws ClientProtocolException, IOException { + Either eitherMyCompute = getResource(resourceName, resourceVersion); + assertTrue(eitherMyCompute.isLeft()); + String testComputeYml = eitherMyCompute.left().value(); + + Map map = new HashMap(); + map = (Map) new Gson().fromJson(testComputeYml, map.getClass()); + + validateMyComputeBasicFields(map, resourceName, resourceVersion, expectedState); + + validateMyComputeCapabilities(map); + + validateMyComputeRequirements(map); + validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceVersion); + + } + + protected void validateMyComputeResource(String uid, String resourceName, String resourceVersion, String expectedState) throws ClientProtocolException, IOException { + RestResponse resourceResponse = ResourceRestUtils.getResource(uid); + ResourceRestUtils.checkSuccess(resourceResponse); + String testComputeYml = resourceResponse.getResponse(); + + // Either eitherMyCompute = getResource(resourceName, + // resourceVersion); + // assertTrue( eitherMyCompute.isLeft() ); + // String testComputeYml = eitherMyCompute.left().value(); + + Map map = new HashMap(); + map = (Map) new Gson().fromJson(testComputeYml, map.getClass()); + + validateMyComputeBasicFields(map, resourceName, resourceVersion, expectedState); + + validateMyComputeCapabilities(map); + + validateMyComputeRequirements(map); + validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceVersion); + + } + + protected void validateMyComputeResourceAfterUpdate(String uid, String resourceName, String resourceVersion, String expectedState) throws ClientProtocolException, IOException { + RestResponse resourceResponse = ResourceRestUtils.getResource(uid); + ResourceRestUtils.checkSuccess(resourceResponse); + String testComputeYml = resourceResponse.getResponse(); + + // Either eitherMyCompute = getResource(resourceName, + // resourceVersion); + // assertTrue( eitherMyCompute.isLeft() ); + + // String testComputeYml = eitherMyCompute.left().value(); + + Map map = new HashMap(); + map = (Map) new Gson().fromJson(testComputeYml, map.getClass()); + + validateMyComputeBasicFields(map, resourceName, resourceVersion, expectedState); + validateField(map, RespJsonKeysEnum.DESCRIPTION.getRespJsonKeyName(), "Short description"); + validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), "UserVendor"); + validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(), "1.1.2"); + + // validateMyComputeCapabilities(map); + // AssertJUnit.assertTrue(map.containsKey("capabilities")); + // Map capabilities = (Map) + // map.get("capabilities"); + // AssertJUnit.assertTrue(capabilities.containsKey("host")); + // Map hostCap = (Map) + // capabilities.get("host"); + // validateField(hostCap, "type", "tosca.capabilities.Container"); + // validateField(hostCap, "validSourceTypes", Arrays.asList(new + // String[]{"tosca.nodes.SoftwareComponent"})); + // + // AssertJUnit.assertTrue(capabilities.containsKey("endpoint")); + // Map endPointCap = (Map) + // capabilities.get("endpoint"); + // validateField(endPointCap, "type", + // "tosca.capabilities.Endpoint.Admin"); + + assertTrue(map.containsKey("capabilities")); + Map capabilities = (Map) map.get("capabilities"); + assertTrue(capabilities.containsKey("tosca.capabilities.Container")); + List hostCapList = (List) capabilities.get("tosca.capabilities.Container"); + assertFalse(hostCapList.isEmpty()); + Map hostCap = (Map) hostCapList.get(0); + validateField(hostCap, "type", "tosca.capabilities.Container"); + validateField(hostCap, "name", "host"); + validateField(hostCap, "validSourceTypes", Arrays.asList(new String[] { "tosca.nodes.SoftwareComponent" })); + + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); + List endPointCapList = (List) capabilities.get("tosca.capabilities.Endpoint.Admin"); + assertFalse(endPointCapList.isEmpty()); + Map endPointCap = (Map) endPointCapList.get(0); + validateField(endPointCap, "name", "endpoint"); + validateField(endPointCap, "type", "tosca.capabilities.Endpoint.Admin"); + + validateMyComputeRequirements(map); + validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceVersion); + + } + + protected void validateMyComputeRequirements(Map map) { + assertTrue(map.containsKey("requirements")); + Map requirements = (Map) map.get("requirements"); + + assertTrue(requirements.containsKey("tosca.capabilities.Attachment")); + List localStorageReqList = (List) requirements.get("tosca.capabilities.Attachment"); + assertFalse(localStorageReqList.isEmpty()); + Map localStorageReq = (Map) localStorageReqList.get(0); + validateField(localStorageReq, "capability", "tosca.capabilities.Attachment"); + validateField(localStorageReq, "node", "tosca.nodes.BlockStorage"); + validateField(localStorageReq, "relationship", "tosca.relationships.AttachesTo"); + validateField(localStorageReq, "name", "local_storage"); + } + + protected void validateMyComputeBasicFields(Map map, String resourceName, String resourceVersion, String expectedState) { + validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(), false); + // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(), + // categoryDefinition); + // validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), + // UniqueIdBuilder.buildResourceUniqueId(resourceName, + // resourceVersion)); + validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceName); + validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), Arrays.asList(new String[] { resourceName })); + validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(), expectedState); + + validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), Arrays.asList(new String[] { "tosca.nodes.Root" })); + } + + protected static void validateField(Map map, String jsonField, Object expectedValue) { + if (expectedValue == null) { + assertTrue(!map.containsKey(jsonField)); + } else { + assertTrue("map does not contain field " + jsonField, map.containsKey(jsonField)); + Object foundValue = map.get(jsonField); + compareElements(expectedValue, foundValue); + } + } + + protected static void compareElements(Object expectedValue, Object foundValue) { + if (expectedValue instanceof String) { + assertTrue(foundValue instanceof String); + assertTrue(foundValue.equals(expectedValue)); + } + + else if (expectedValue instanceof Boolean) { + assertTrue(foundValue instanceof Boolean); + assertTrue(foundValue == expectedValue); + } else if (expectedValue instanceof Map) { + assertTrue(foundValue instanceof Map); + Map foundMap = (Map) foundValue; + Map excpectedMap = (Map) expectedValue; + assertTrue(foundMap.size() == excpectedMap.size()); + Iterator foundkeyItr = foundMap.keySet().iterator(); + while (foundkeyItr.hasNext()) { + String foundKey = foundkeyItr.next(); + assertTrue(excpectedMap.containsKey(foundKey)); + compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey)); + } + + } else if (expectedValue instanceof List) { + assertTrue(foundValue instanceof List); + List foundList = (List) foundValue; + List excpectedList = (List) expectedValue; + assertTrue(foundList.size() == excpectedList.size()); + for (int i = 0; i < foundList.size(); i++) { + compareElements(excpectedList.get(i), foundList.get(i)); + } + + } else if (expectedValue instanceof CategoryDefinition) { + assertTrue(foundValue instanceof Map); + CategoryDefinition expCat = (CategoryDefinition) expectedValue; + Map actCat = (Map) foundValue; + assertEquals(expCat.getName(), actCat.get("name")); + + // assertEquals(expCat.getSubcategories().get(0).getName(), + // actCat.get("subcategories").getName()); + } else { + assertTrue(foundValue.equals(expectedValue)); + } + } + + public static void restoreToOriginalState(Map originalState, UserRoleEnum userRole) throws IOException { + removeAllNormativeTypeResources(); + + Iterator> iterator = originalState.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + Boolean isExistBeforeDelete = entry.getValue(); + if (isExistBeforeDelete) { + importNormativeResource(entry.getKey(), userRole); + } + } + + } + + public static void importAllNormativeTypesResources(UserRoleEnum userRole) throws IOException { + for (NormativeTypesEnum currResource : NormativeTypesEnum.values()) { + Either resource = getResource(currResource.getNormativeName(), "1.0"); + if (resource.isRight()) { + importNormativeResource(currResource, userRole); + } + } + + } + + protected static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole) throws IOException { + return importResource(resource.getFolderName(), userRole, true); + } + + protected static Integer importResource(String folderName, UserRoleEnum userRole, boolean isNormative) throws IOException { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getZipFile(folderName))); + mpBuilder.addPart("resourceMetadata", new StringBody(getJsonStringOfFile(folderName, folderName + ".json"), ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort()); + if (!isNormative) { + url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + } + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("USER_ID", userRole.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + return response.getStatusLine().getStatusCode(); + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + public static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + log.debug("failed to close client or response: ", e); + } + } + + public static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + log.debug("failed to close client or response: ", e); + } + } + + protected static String getJsonStringOfFile(String folderName, String fileName) throws IOException { + String sourceDir = config.getImportResourceConfigDir(); + sourceDir += File.separator + "normative-types"; + + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + protected static File getZipFile(String elementName) throws IOException { + String sourceDir = config.getImportResourceConfigDir(); + sourceDir += File.separator + "normative-types"; + + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, "normative-types-new-" + elementName + ".zip"); + return filePath.toFile(); + } + + protected static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException { + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + protected static File getTestZipFile(String elementName) throws IOException { + String sourceDir = config.getImportResourceTestsConfigDir(); + + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, "normative-types-new-" + elementName + ".zip"); + return filePath.toFile(); + } + + protected static Either getResource(String name, String version) throws IOException { + RestResponse resource = ResourceRestUtils.getResourceByNameAndVersion(UserRoleEnum.DESIGNER.getUserId(), name, version); + if (resource.getErrorCode() == ImportRestUtils.STATUS_CODE_GET_SUCCESS) { + return Either.left(resource.getResponse()); + // return Either.right(true); + + } + return Either.right(false); + } + + @Test + public void testImportWithRequirmentsAndCapabilities() throws IOException { + String fileName = FILE_NAME_MY_COMPUTE; + RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN); + Integer statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS); + String uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "1.0", "CERTIFIED"); + } + + @Test + public void testImportWithUpdateNormativeType() throws IOException { + String fileName = FILE_NAME_MY_COMPUTE; + RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN); + Integer statusCode = response.getErrorCode(); + assertTrue(statusCode == BaseRestUtils.STATUS_CODE_IMPORT_SUCCESS); + String uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "1.0", "CERTIFIED"); + + // update + response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN); + statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS); + uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "2.0", "CERTIFIED"); + + } + + @Test + public void testImportWithInvalidDefaultValue() throws IOException { + RestResponse response = ImportRestUtils.importNewResourceByName("portInvalidDefaultValue", UserRoleEnum.DESIGNER); + assertTrue(response.getErrorCode() == HttpStatus.SC_BAD_REQUEST); + } + + @Test + public void testImportUserResource() throws IOException { + String fileName = FILE_NAME_USER_COMPUTE; + RestResponse response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER); + Integer statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS); + String uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT"); + + } + + @Test + public void testImportAndUpdateUserResource() throws IOException { + String fileName = FILE_NAME_USER_COMPUTE; + RestResponse response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER); + Integer statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS); + String uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT"); + response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_UPDATE_COMPUTE, UserRoleEnum.DESIGNER); + statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS); + uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResourceAfterUpdate(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT"); + + } + + @Test + public void testImportAndUpdateChangesUserResource() throws IOException { + String fileName = FILE_NAME_USER_COMPUTE; + RestResponse response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER); + Integer statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS); + String uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT"); + // Either resource = getResource(fileName, "0.1"); + // assertTrue(resource.isLeft()); + + response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_UPDATE_COMPUTE, UserRoleEnum.DESIGNER); + statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS); + validateMyComputeResourceAfterUpdate(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT"); + + } + + @Test + public void testImportCheckoutAndUpdateUserResource() throws IOException { + String fileName = FILE_NAME_USER_COMPUTE; + RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.ADMIN); + Integer statusCode = response.getErrorCode(); + assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS); + String uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "1.0", "CERTIFIED"); + + response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER); + statusCode = response.getErrorCode(); + assertEquals("check response code after update resource", ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS, statusCode.intValue()); + uid = ResponseParser.getUniqueIdFromResponse(response); + validateMyComputeResource(uid, fileName, "1.1", "NOT_CERTIFIED_CHECKOUT"); + + } + + @Test + public void importNormativeTypesTesterUserRole() throws Exception { + Integer statusCode = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.TESTER).getErrorCode(); + assertTrue(statusCode == ImportRestUtils.RESTRICTED_OPERATION); + } + + @Test + public void importNormativeTypesDesignerUserRole() throws Exception { + Integer statusCode = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.DESIGNER).getErrorCode(); + assertTrue(statusCode == 409); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java new file mode 100644 index 0000000000..c069f984d2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java @@ -0,0 +1,1529 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpStatus; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +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.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +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.ImportRestUtils; +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.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.exception.ResponseFormat; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class ImportNewResourceCITest extends ComponentBaseTest { + + // public static UserUtils userUtils = new UserUtils(); + // public ResourceUtils resourceUtils = new ResourceUtils(); + // public AuditValidationUtils AuditValidationUtils = new + // AuditValidationUtils(); + // protected ArtifactUtils artifactUtils = new ArtifactUtils(); + + protected String resourceVersion = null; + protected String auditAction = null; + public User sdncModifierDetails = new User(); + protected String artifactName1 = "data_artifact1.sh"; + protected String artifactName2 = "data_artifact2.sh"; + protected String interfaze = "standard"; + protected String interfaceArtifactName = "data_interface1.sh"; + + private String SPECIAL_CHARACTERS = "~!#@~$%^*()[];:'\"|\\/"; + + public ResourceReqDetails resourceDetails = new ResourceReqDetails(); + + public Gson gson = new Gson(); + + @Rule + public static TestName name = new TestName(); + + public ImportNewResourceCITest() { + super(name, ImportNewResourceCITest.class.getName()); + } + + @BeforeMethod + public void before() throws Exception { + + // init user + sdncModifierDetails.setUserId(UserRoleEnum.ADMIN.getUserId()); + // init resource details + resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003"); + } + + @Test + public void importAllTestResources_toValidateNewAPI() throws Exception { + + for (ImportTestTypesEnum currResource : ImportTestTypesEnum.values()) { + // clean audit + DbUtils.cleanAllAudits(); + + // import testResources trough newResource API + RestResponse importResponse = ImportRestUtils.importNewResourceByName(currResource.getFolderName(), + UserRoleEnum.ADMIN); + System.err.println("import Resource " + "<" + currResource.getFolderName() + ">" + "response: " + + importResponse.getErrorCode()); + + // validate response + ImportRestUtils.validateImportTestTypesResp(currResource, importResponse); + if (currResource.getvalidateAudit() == true) { + // validate audit + // String baseVersion="0.1"; + String baseVersion = ""; + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName()); + expectedResourceAuditJavaObject.setResourceName(currResource.getNormativeName()); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(baseVersion); + expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setComment(null); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + List variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() + : new ArrayList()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAuditImport(expectedResourceAuditJavaObject, auditAction); + } + } + } + + protected RestResponse importNewResource(UserRoleEnum userRoleEnum) throws Exception { + + // init user + sdncModifierDetails.setUserId(userRoleEnum.getUserId()); + // init resource details + resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003"); + // clean ES DB + DbUtils.cleanAllAudits(); + // import new resource (expected checkOut state) + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4test", userRoleEnum); + return importResponse; + } + + @Test(enabled = false) + public void importUIResource() throws IOException { + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + + " description: someDesc"; + + String encodedPayload = new String(Base64.encodeBase64(payload.getBytes())); + + String json = "{\r\n" + " \"resourceName\": \"importResource4test\",\r\n" + + " \"payloadName\": \"importResource4test.yml\",\r\n" + + " \"categories\": [{\"name\": \"Application L4+\",\"normalizedName\": \"application l4+\",\"uniqueId\": \"resourceNewCategory.application l4+\",\"subcategories\": [{\"name\": \"Web Server\"}]}],\r\n" + + " \"description\": \"ResourceDescription\",\r\n" + " \"vendorName\": \"VendorName\",\r\n" + + " \"vendorRelease\": \"VendorRelease\",\r\n" + " \"contactId\": \"AT1234\",\r\n" + + " \"icon\": \"router\",\r\n" + " \"tags\": [\r\n" + " \"importResource4test\"\r\n" + " ],\r\n" + + " \"payloadData\": \"" + encodedPayload + "\"\r\n" + "}"; + + String md5 = GeneralUtility.calculateMD5ByString(json); + + Map headers = new HashMap(); + headers.put(Constants.MD5_HEADER, md5); + headers.put(Constants.USER_ID_HEADER, UserRoleEnum.ADMIN.getUserId()); + headers.put(Constants.CONTENT_TYPE_HEADER, "application/json"); + + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + + HttpRequest httpUtil = new HttpRequest(); + RestResponse httpSendPost = httpUtil.httpSendPost(url, json, headers); + Integer errorCode = httpSendPost.getErrorCode(); + assertTrue(errorCode == HttpStatus.SC_CREATED); + + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_suc() throws Exception { + + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + // validate response + + resourceVersion = "0.1"; + + // ResourceRespJavaObject resourceRespJavaObject = + // Convertor.constructFieldsForRespValidation(resourceDetails, + // resourceVersion); + // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // ResourceValidationUtils.validateResp(importResponse, + // resourceRespJavaObject); + // + // //validate get response + // + // RestResponse resourceGetResponse = + // ResourceRestUtils.getResource(sdncModifierDetails, resourceVersion); + // ResourceValidationUtils.validateResp(resourceGetResponse, + // resourceRespJavaObject); + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + assertNotNull(resourceFromImport); + + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceRespJavaObject.getUniqueId()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // validate + ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet); + + // validate audit + resourceDetails.setVersion(resourceDetails.getVersion()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + + auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void importNewResource_byTester_failed() throws Exception { + + RestResponse importResponse = importNewResource(UserRoleEnum.TESTER); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 409, importResponse.getErrorCode().intValue()); + + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existInCheckout_updateVendorName_updateCategory() throws Exception { + + // import new resource + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in other state + importResponse = ImportRestUtils.importNewResourceByName("importResource4testUpdateVendorNameAndCategory", + UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue()); + + // validate response + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + assertNotNull(resourceFromImport); + + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceRespJavaObject.getUniqueId()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // validate + ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet); + + // validate audit + resourceDetails.setVersion(resourceDetails.getVersion()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails); + + auditAction = "ResourceImport"; + resourceVersion = "0.1"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @Test + public void importNewResource_perfromByAdmin_ownedBy_diffrentUser() throws Exception { + + RestResponse importResponse = importNewResource(UserRoleEnum.DESIGNER); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + // clean audit + DbUtils.cleanAllAudits(); + + importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), importResponse.getErrorCode()); + + String[] split = resourceFromImport.getLastUpdaterFullName().split(" "); + String firstName = split[0]; + String lastName = split[1]; + List variables = Arrays.asList(resourceFromImport.getName(), "resource", firstName, lastName, + resourceFromImport.getLastUpdaterUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name(), variables, + importResponse.getResponse()); + + } + + @Test + public void importNewResource_perfromByDesigner_ownedBy_diffrentUser() throws Exception { + + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + // clean audit + DbUtils.cleanAllAudits(); + + importResponse = importNewResource(UserRoleEnum.DESIGNER); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name()); + assertEquals("Check response code after adding artifact", errorInfo.getCode(), importResponse.getErrorCode()); + + String[] split = resourceFromImport.getLastUpdaterFullName().split(" "); + String firstName = split[0]; + String lastName = split[1]; + List variables = Arrays.asList(resourceFromImport.getName(), "resource", firstName, lastName, + resourceFromImport.getLastUpdaterUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name(), variables, + importResponse.getResponse()); + + } + + @Test(enabled = false) + public void importNewResource_nameSpace_vf() throws Exception { + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testVF", + UserRoleEnum.DESIGNER); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResponse.getResponse()); + assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VF)); + + } + + @Test + public void importNewResource_nameSpace_vfc() throws Exception { + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testVFC", + UserRoleEnum.DESIGNER); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResponse.getResponse()); + assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VFC)); + } + + @Test + public void importNewResource_nameSpace_vl() throws Exception { + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testVL", + UserRoleEnum.DESIGNER); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResponse.getResponse()); + assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VL)); + + } + + @Test + public void importNewResource_nameSpace_cp() throws Exception { + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testCP", + UserRoleEnum.DESIGNER); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResponse.getResponse()); + assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.CP)); + } + + @Test + public void importNewResource_nameSpace_unknown() throws Exception { + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4test", + UserRoleEnum.DESIGNER); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResponse.getResponse()); + assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VFC)); + + } + + @Test + public void importNewResource_MissingNameSpace() throws Exception { + RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testMissingNameSpace", + UserRoleEnum.DESIGNER); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 400, importResponse.getErrorCode().intValue()); + + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existInCheckOut() throws Exception { + + // import new resource + + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in CHECKOUT state + + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue()); + + // validate response + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + assertNotNull(resourceFromImport); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceRespJavaObject.getUniqueId()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // validate + ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet); + + // validate audit + resourceDetails.setVersion(resourceDetails.getVersion()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails); + + auditAction = "ResourceImport"; + resourceVersion = "0.1"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existIn_CheckIn_state() throws Exception { + + // import new resource + + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + // checkIn resource + + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in CHECKIN state + + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue()); + + // validate response + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + assertNotNull(resourceFromImport); + + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceRespJavaObject.getUniqueId()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // validate + ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet); + + // validate audit + resourceDetails.setVersion(resourceDetails.getVersion()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails); + + resourceVersion = "0.2"; + auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @Test + public void importNewResource_existIn_Ready4cert_state_performByTester() throws Exception { + // import new resource + + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + // add mandatory artifacts + // // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // checkIn resource + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(checkInResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(checkInResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in CHECKIN state + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.TESTER); + + // validate response + resourceVersion = resourceDetails.getVersion(); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + assertNotNull("check response object is not null after create resouce", importResponse); + assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + importResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setResourceName(""); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.TESTER.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.TESTER.getUserName()); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existIn_Ready4cert_state_performByDesigner() throws Exception { + // import new resource + + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + // add mandatory artifacts + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // checkIn resource + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in other state + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.DESIGNER); + + // validate response + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION.name()); + assertNotNull("check response object is not null after create resouce", importResponse); + assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode()); + String[] split = resourceFromGet.getLastUpdaterFullName().split(" "); + String firstName = split[0]; + String lastName = split[1]; + List variables = Arrays.asList(resourceFromGet.getName(), "resource", firstName, lastName, + resourceFromGet.getLastUpdaterUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION.name(), variables, + importResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.DESIGNER.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.DESIGNER.getUserName()); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.READY_FOR_CERTIFICATION).toString()); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existIn_Ready4cert_state_performByAdmin() throws Exception { + + // import new resource + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // add mandatory artifacts + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // checkIn resource + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in other state + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + resourceVersion = resourceDetails.getVersion(); + // resourceVersion="0.2"; + + // validate response + Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + assertNotNull(resourceFromImport); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + + // validate get response + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // validate + ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @Test + public void importNewResource_existIn_CerInProgress_state_performByTester() throws Exception { + + // import new resource + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // add mandatory artifacts + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // checkIn resource + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // startCert + RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertNotNull("check response object is not null after resource request start certification", startCert); + assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in other state + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.TESTER); + + // validate response + resourceVersion = resourceDetails.getVersion(); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + assertNotNull("check response object is not null after create resouce", importResponse); + assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + importResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setResourceName(""); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.TESTER.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.TESTER.getUserName()); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existIn_CerInProgress_state_performByDesigner() throws Exception { + + User sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // import new resource + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // add mandatory artifacts + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // checkIn resource + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // startCert + RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertNotNull("check response object is not null after resource request start certification", startCert); + assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + resourceVersion = resourceDetails.getVersion(); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in other state + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.DESIGNER); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()); + assertNotNull("check response object is not null after create resouce", importResponse); + assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode()); + List variables = Arrays.asList(resourceDetails.getName(), "resource", sdncAdminUser.getFirstName(), + sdncAdminUser.getLastName(), sdncAdminUser.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name(), + variables, importResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.DESIGNER.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.DESIGNER.getUserName()); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.CERTIFICATION_IN_PROGRESS).toString()); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + // TODO DE171337 + @Test(enabled = false) + public void importNewResource_existIn_CerInProgress_state_performByAdmin() throws Exception { + + User sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // import new resource + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + + // add mandatory artifacts + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // checkIn resource + resourceVersion = resourceDetails.getVersion(); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + // startCert + RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertNotNull("check response object is not null after resource request start certification", startCert); + assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + resourceVersion = resourceDetails.getVersion(); + + // clean audit + DbUtils.cleanAllAudits(); + + // import new resource while resource already exist in other state + importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN); + + // validate response + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()); + assertNotNull("check response object is not null after create resouce", importResponse); + assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode()); + List variables = Arrays.asList(resourceDetails.getName(), "resource", sdncAdminUser.getFirstName(), + sdncAdminUser.getLastName(), sdncAdminUser.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name(), + variables, importResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "ResourceImport"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName()); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.CERTIFICATION_IN_PROGRESS).toString()); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + // TODO DE171337 + // @Test(enabled = false) + // public void + // importNewResource_existIn_Certified_state_chnage_reqAndCap_byDesigner() + // throws Exception{ + // + // // Andrey - set default artifact details + // ArtifactDefinition artifactDefinition = + // artifactUtils.constructDefaultArtifactInfo(); + // + // // import new resource + // RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + // assertNotNull("check response object is not null after import resource", + // importResponse); + // assertNotNull("check error code exists in response after import + // resource", importResponse.getErrorCode()); + // assertEquals("Check response code after import resource", 201, + // importResponse.getErrorCode().intValue()); + // String resourceId = + // ResponseParser.getUniqueIdFromResponse(importResponse); + // resourceDetails = + // ResponseParser.parseToObject(importResponse.getResponse(), + // ResourceReqDetails.class); + // resourceVersion = resourceDetails.getVersion(); + // RestResponse resourceGetResponse = + // ResourceRestUtils.getResource(sdncModifierDetails, + // resourceDetails.getUniqueId()); + // assertEquals("Check response code after get resource", 200, + // resourceGetResponse.getErrorCode().intValue()); + // Resource resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + // assertNotNull(resourceFromGet); + // + // // add mandatory artifacts + // // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + // resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + // resourceDetails.getUniqueId()); + // assertEquals("Check response code after get resource", 200, + // resourceGetResponse.getErrorCode().intValue()); + // resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + // assertNotNull(resourceFromGet); + // resourceDetails = + // ResponseParser.parseToObject(importResponse.getResponse(), + // ResourceReqDetails.class); + // resourceDetails.setVersion(resourceFromGet.getVersion()); + // + // // add artifact + // artifactDefinition.setArtifactName(artifactName1); + // ArtifactRestUtils.addInformationalArtifactToResource(resourceDetails, + // sdncModifierDetails, resourceVersion , artifactDefinition); + // + // // add artifact + // artifactDefinition.setArtifactName(artifactName2); + // resourceUtils.add_artifact(resourceDetails, sdncModifierDetails, + // resourceVersion , artifactDefinition); + // + // // add interface + // artifactDefinition.setArtifactName(interfaceArtifactName); + // ResourceRestUtils.add_interface(resourceDetails, sdncModifierDetails, + // resourceVersion , artifactDefinition); + // + // //construct fields for validation + // resourceVersion="1.0"; + // + // ResourceRespJavaObject resourceRespJavaObject = + // Convertor.constructFieldsForRespValidation(resourceDetails, + // resourceVersion); + // ArrayList artifacts = new ArrayList(); + // + // artifacts.add(resourceId+":"+artifactName1); + // artifacts.add(resourceId+":"+artifactName2); + // resourceRespJavaObject.setArtifacts(artifacts); + // ArrayList interfaces = new ArrayList(); + // + // interfaces.add(interfaze); + // resourceRespJavaObject.setInterfaces(interfaces); + // + // // checkIn resource + // resourceVersion = resourceDetails.getVersion(); + // String checkinComment = "good checkin"; + // String checkinComentJson = "{\"userRemarks\": \""+checkinComment+"\"}"; + // RestResponse checkInResponse = + // LifecycleRestUtils.changeResourceState(resourceDetails, + // sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, + // checkinComentJson); + // assertNotNull("check response object is not null after import resource", + // checkInResponse); + // assertEquals("Check response code after checkout resource", 200, + // checkInResponse.getErrorCode().intValue()); + // + // // req4cert resource + // RestResponse request4cert = + // LifecycleRestUtils.changeResourceState(resourceDetails, + // sdncModifierDetails, resourceVersion, + // LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // assertNotNull("check response object is not null after resource request + // for certification", request4cert); + // assertEquals("Check response code after checkout resource", 200, + // request4cert.getErrorCode().intValue()); + // resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + // assertNotNull(resourceFromGet); + // resourceDetails = + // ResponseParser.parseToObject(request4cert.getResponse(), + // ResourceReqDetails.class); + // resourceDetails.setVersion(resourceFromGet.getVersion()); + // + // // startCert + // RestResponse startCert = + // LifecycleRestUtils.changeResourceState(resourceDetails, + // sdncModifierDetails, resourceVersion, + // LifeCycleStatesEnum.STARTCERTIFICATION); + // assertNotNull("check response object is not null after resource request + // start certification", startCert); + // assertEquals("Check response code after checkout resource", 200, + // startCert.getErrorCode().intValue()); + // resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse()); + // assertNotNull(resourceFromGet); + // resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), + // ResourceReqDetails.class); + // resourceDetails.setVersion(resourceFromGet.getVersion()); + // + // // certify + // RestResponse certify = + // LifecycleRestUtils.changeResourceState(resourceDetails, + // sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFY); + // assertNotNull("check response object is not null after resource request + // certify", certify); + // assertEquals("Check response code after certify resource", 200, + // certify.getErrorCode().intValue()); + // resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(certify.getResponse()); + // assertNotNull(resourceFromGet); + // resourceDetails = ResponseParser.parseToObject(certify.getResponse(), + // ResourceReqDetails.class); + // resourceDetails.setVersion(resourceFromGet.getVersion()); + // + // // clean audit + // DbUtils.cleanAllAudits(); + // + // // change resource details + // + // // import new resource while resource already exist in other state + // importResponse = + // ImportRestUtils.importNewResourceByName("importResource4testUpdateWithoutReqCap", + // UserRoleEnum.ADMIN); + // assertNotNull("check response object is not null after import resource", + // importResponse); + // assertNotNull("check error code exists in response after import + // resource", importResponse.getErrorCode()); + // assertEquals("Check response code after import resource", 200, + // importResponse.getErrorCode().intValue()); + // resourceDetails = + // ResponseParser.parseToObject(importResponse.getResponse(), + // ResourceReqDetails.class); + // resourceVersion = resourceDetails.getVersion(); + // resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + // resourceDetails.getUniqueId()); + // assertEquals("Check response code after get resource", 200, + // resourceGetResponse.getErrorCode().intValue()); + // resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + // assertNotNull(resourceFromGet); + // + // // validate response + // Resource resourceFromImport = + // ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse()); + // assertNotNull(resourceFromImport); + // + // resourceDetails = + // ResponseParser.parseToObject(importResponse.getResponse(), + // ResourceReqDetails.class); + // resourceRespJavaObject = + // Convertor.constructFieldsForRespValidation(resourceDetails); + // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // + // // validate get response + // resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + // resourceRespJavaObject.getUniqueId()); + // resourceFromGet = + // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + // assertNotNull(resourceFromGet); + // + // // validate + // ResourceValidationUtils.validateModelObjects(resourceFromImport, + // resourceFromGet); + // + // // validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // Convertor.constructFieldsForAuditValidation(resourceDetails, + // resourceVersion); + // auditAction="ResourceImport"; + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setPrevVersion(resourceVersion); + // expectedResourceAuditJavaObject.setStatus("200"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName()); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // } + + @Test + public void importNewResource_uuidTest() throws Exception { + RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN); + + assertNotNull("check response object is not null after import resource", importResponse); + assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode()); + assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue()); + String oldUuid = ResponseParser.getValueFromJsonResponse(importResponse.getResponse(), "uuid"); + + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceVersion = resourceDetails.getVersion(); + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + Resource resourceFromGet = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + // add mandatory artifacts + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // resourceGetResponse); + resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId()); + assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + "0.1", LifeCycleStatesEnum.CHECKIN); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + String newUuid = ResponseParser.getValueFromJsonResponse(checkInResponse.getResponse(), "uuid"); + assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid)); + + // req4cert resource + RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertNotNull("check response object is not null after resource request for certification", request4cert); + assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + String newUuid2 = ResponseParser.getValueFromJsonResponse(request4cert.getResponse(), "uuid"); + assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid2)); + + // startCert + RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertNotNull("check response object is not null after resource request start certification", startCert); + assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue()); + resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse()); + assertNotNull(resourceFromGet); + resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class); + resourceDetails.setVersion(resourceFromGet.getVersion()); + + String newUuid3 = ResponseParser.getValueFromJsonResponse(startCert.getResponse(), "uuid"); + assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid3)); + + RestResponse certify = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, "0.1", + LifeCycleStatesEnum.CERTIFY); + assertNotNull("check response object is not null after import resource", certify); + assertEquals("Check response code after checkout resource", 200, certify.getErrorCode().intValue()); + + String newUuid4 = ResponseParser.getValueFromJsonResponse(certify.getResponse(), "uuid"); + assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid4)); + + RestResponse checkoutResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + "1.0", LifeCycleStatesEnum.CHECKOUT); + assertNotNull("check response object is not null after import resource", checkInResponse); + assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue()); + + String newUuid5 = ResponseParser.getValueFromJsonResponse(checkoutResponse.getResponse(), "uuid"); + assertFalse(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid5)); + } + + @Test + public void importNewResource_propertiesMapInternalUrlCredential() throws Exception { + String folderName = "validateProporties_typeMap_valueUrlCredential"; + RestResponse importResponse = ImportRestUtils.importNewResourceByName(folderName, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.parseToObjectUsingMapper(importResponse.getResponse(), Resource.class); + + List properties = resource.getProperties(); + assertEquals("check properties size", 3, properties.size()); + + PropertyDefinition propertyDefinition = properties.stream().filter(p -> p.getName().equals("validation_test")) + .findFirst().get(); + String defaultValue = propertyDefinition.getDefaultValue(); + + Map mapValue = gson.fromJson(defaultValue, Map.class); + assertEquals("check Map value size", 2, mapValue.size()); + checkMapValues(mapValue, "key", 1, null); + checkMapValues(mapValue, "key", 2, null); + + System.err.println("import Resource " + "<" + folderName + ">" + "response: " + importResponse.getErrorCode()); + + } + + @Test + public void importNewResource_propertiesListInternalUrlCredential() throws Exception { + String folderName = "validateProporties_typeList_valueUrlCredential"; + RestResponse importResponse = ImportRestUtils.importNewResourceByName(folderName, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.parseToObjectUsingMapper(importResponse.getResponse(), Resource.class); + + List properties = resource.getProperties(); + assertEquals("check properties size", 3, properties.size()); + + PropertyDefinition propertyDefinition = properties.stream().filter(p -> p.getName().equals("validation_test")) + .findFirst().get(); + String defaultValue = propertyDefinition.getDefaultValue(); + + List listValue = gson.fromJson(defaultValue, List.class); + assertEquals("check List value size", 2, listValue.size()); + checkListValues(listValue.get(0), 1, SPECIAL_CHARACTERS); + checkListValues(listValue.get(1), 2, SPECIAL_CHARACTERS); + + // Verify attributes + List attributes = resource.getAttributes(); + + assertEquals("check properties size", 2, attributes.size()); + + // Verify attribute from type map + PropertyDefinition attributeMapDefinition = attributes.stream() + .filter(p -> p.getName().equals("validation_test_map")).findFirst().get(); + String defaultMapValue = attributeMapDefinition.getDefaultValue(); + Map attributeMapValue = gson.fromJson(defaultMapValue, Map.class); + assertEquals("check Map value size", 2, attributeMapValue.size()); + checkMapValues(attributeMapValue, "key", 1, SPECIAL_CHARACTERS); + checkMapValues(attributeMapValue, "key", 2, SPECIAL_CHARACTERS); + + // Verify attribute from type list + PropertyDefinition attributeListDefinition = attributes.stream() + .filter(p -> p.getName().equals("validation_test_list")).findFirst().get(); + String defaultListValue = attributeListDefinition.getDefaultValue(); + + List attributeListValue = gson.fromJson(defaultListValue, List.class); + assertEquals("check List value size", 2, attributeListValue.size()); + checkListValues(attributeListValue.get(0), 1, SPECIAL_CHARACTERS); + checkListValues(attributeListValue.get(1), 2, SPECIAL_CHARACTERS); + + System.err.println("import Resource " + "<" + folderName + ">" + "response: " + importResponse.getErrorCode()); + + } + + private void checkListValues(Object object, int index, String suffix) { + + Map map = (Map) object; + assertEquals("check Map protocol value", "protocol" + index + (suffix == null ? "" : suffix), + map.get("protocol")); + assertEquals("check Map token value", "token" + index, map.get("token")); + } + + // @Test + public void importNewResource_validateProporties_typeTestDataType() throws Exception { + String folderName = "validateProporties_typeTestDataType"; + RestResponse importResponse = ImportRestUtils.importNewResourceByName(folderName, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.parseToObjectUsingMapper(importResponse.getResponse(), Resource.class); + + } + + private void checkMapValues(Map mapValue, String key, int index, String suffix) { + + Map map1 = (Map) mapValue.get(key + index); + assertEquals("check Map protocol value", "protocol" + index + (suffix == null ? "" : suffix), + map1.get("protocol")); + assertEquals("check Map token value", "token" + index, map1.get("token")); + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java new file mode 100644 index 0000000000..3d7c81abae --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java @@ -0,0 +1,416 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +/** + * US US730518 Story [BE] - TOSCA capabilities with properties - import "As a + * resource designer, I would like to add my VFC capabilities with properties." + * + * @author ns019t + * + */ +public class ImportToscaCapabilitiesWithProperties extends ComponentBaseTest { + @Rule + public static TestName name = new TestName(); + + Gson gson = new Gson(); + + /** + * public Constructor ImportToscaCapabilitiesWithProperties + */ + public ImportToscaCapabilitiesWithProperties() { + super(name, ImportToscaCapabilitiesWithProperties.class.getName()); + } + + /** + * String constants + */ + public static String propertyForTestName = "propertyfortest"; + public static String rootPath = System.getProperty("user.dir"); + public static String scalable = "tosca.capabilities.Scalable"; + public static String container = "tosca.capabilities.Container"; + public static String minInstances = "min_instances"; + public static String userDefinedNodeYaml = "mycompute.yml"; + + /** + * Capability Type - capability type on the graph should already have + * properties modeled on it. please verify. The import of the capability + * types should support adding those properties. when importing, validate + * name uniqueness between the capability's properties see capability + * tosca.capabilities.Container + * + * Acceptance Criteria: validate capability type properties (for example, + * compute have capability Container -> the properties of this capability + * should be in the Json response) + * + * @throws IOException + */ + @Test + public void validateCapabilityTypePropertiesSucceed() throws IOException { + User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse createResourceRes = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), "Compute", + "1.0"); + BaseRestUtils.checkSuccess(createResourceRes); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResourceRes.getResponse()); + Map> capabilities = resource.getCapabilities(); + assertEquals(capabilities.size(), 6); + + CapabilityDefinition capability = capabilities.get(scalable).get(0); + List properties = capability.getProperties(); + assertEquals(properties.size(), 3); + assertTrue(!properties.stream().filter(p -> p.getName().equalsIgnoreCase(propertyForTestName)).findAny() + .isPresent()); + + ComponentInstanceProperty originalProperty = properties.stream() + .filter(p -> p.getName().equalsIgnoreCase(minInstances)).findAny().get(); + assertEquals(originalProperty.getType(), "integer"); + assertEquals(originalProperty.getDefaultValue(), "1"); + + capability = capabilities.get(container).get(0); + properties = capability.getProperties(); + assertEquals(properties.size(), 4); + } + + /** + * Capability Definition on VFC / CP / VL - properties can also be defined + * on the capability when the capability is declared. (property definition + * with default value) If the property name (case insensitive) already + * defined on the capability type, it overrides the capability from the + * capability type Import of VFC / CP /VL should support adding properties + * to the capability. when importing, validate name uniqueness between the + * capability's properties + * + * Acceptance Criteria: import node type with capability definition on it. + * use the attached "myCompute" + * + * @throws Exception + */ + @Test + public void importNodeTypeWithCapabilityWithPropertiesFromYmlSucceed() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + RestResponse createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, + resourceDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + Map> capabilities = resource.getCapabilities(); + assertEquals(capabilities.size(), 6); + + CapabilityDefinition capability = capabilities.get(scalable).get(0); + List properties = capability.getProperties(); + assertEquals(properties.size(), 4); + + ComponentInstanceProperty newProperty = properties.stream() + .filter(p -> p.getName().equalsIgnoreCase(propertyForTestName)).findAny().get(); + assertEquals(newProperty.getType(), "string"); + assertEquals(newProperty.getDescription(), "test"); + assertEquals(newProperty.getDefaultValue(), "success"); + + ComponentInstanceProperty overriddenProperty = properties.stream() + .filter(p -> p.getName().equalsIgnoreCase(minInstances)).collect(Collectors.toList()).get(0); + assertEquals(overriddenProperty.getType(), "integer"); + assertEquals(overriddenProperty.getDefaultValue(), "3"); + + } + + /** + * importNodeTypeWithCapabilityWithPropertiesFromYmlFailed + * + * @throws Exception + */ + @Test + public void importNodeTypeWithCapabilityWithPropertiesFromYmlFailed() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + RestResponse createResource = importUserDefinedNodeType("mycompute_failed.yml", sdncModifierDetails, + resourceDetails); + BaseRestUtils.checkErrorMessageResponse(createResource, ActionStatus.PROPERTY_NAME_ALREADY_EXISTS); + } + + /** + * Capability Assignment (on node_template / resource instance) - should + * support assignment of the property (property value). On the resource + * instance level, value can be assigned to either properties that are + * defined on the capability type or on the capability definition. When + * importing a VF - the node_template can have capability's property value. + * It should be imported and saved on the graph Acceptance Criteria: import + * a VF that assign values to property of capability that was defined on the + * capability type + * + * @throws Exception + */ + @Test + public void importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesSucceed() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "vf_with_cap_prop_override_cap_type_prop.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + + List> propertyNamesValues = new ArrayList<>(); + propertyNamesValues.add(new ImmutablePair("num_cpus", "2")); + propertyNamesValues.add(new ImmutablePair("mem_size", "2000 MB")); + checkResource(createResource, 8, container, "DBMS", propertyNamesValues); + + ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource(); + resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop.csar"); + resourceDetails2.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + + checkResource(createResource, 8, container, "DBMS", propertyNamesValues); + } + + /** + * importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesFailed + * + * @throws Exception + */ + @Test + public void importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesFailed() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String payloadName = "vf_with_cap_prop_override_cap_type_prop_failed.csar"; + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + Path path = Paths + .get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop_failed.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkErrorMessageResponse(createResource, ActionStatus.INVALID_PROPERTY); + + ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource(); + resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop_failed.csar"); + resourceDetails2.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + BaseRestUtils.checkErrorMessageResponse(createResource, ActionStatus.INVALID_PROPERTY); + + } + + /** + * Capability Assignment (on node_template / resource instance) - should + * support assignment of the property (property value). On the resource + * instance level, value can be assigned to either properties that are + * defined on the capability type or on the capability definition. When + * importing a VF - the node_template can have capability's property value. + * It should be imported and saved on the graph Acceptance Criteria: import + * a VF that assign values to property of capability that was defined on the + * capability definition (on the node type) + * + * @throws Exception + */ + @Test + public void importResourceWithCapabilityWithPropertiesOverridingNodeTypeCapPropertiesSucceed() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + RestResponse createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, + resourceDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource userDefinedNodeType = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), + Resource.class); + + String payloadName = "vf_with_cap_prop_override_cap_type_prop1.csar"; + resourceDetails = ElementFactory.getDefaultImportResource(); + Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + + List> propertyNamesValues = new ArrayList<>(); + propertyNamesValues.add(new ImmutablePair("num_cpus", "2")); + propertyNamesValues.add(new ImmutablePair("mem_size", "2000 MB")); + checkResource(createResource, 8, container, "DBMS", propertyNamesValues); + + List> propertyNamesValues1 = new ArrayList<>(); + propertyNamesValues1.add(new ImmutablePair(propertyForTestName, "success_again")); + propertyNamesValues1.add(new ImmutablePair(minInstances, "4")); + checkResource(createResource, 8, scalable, userDefinedNodeType.getName(), propertyNamesValues1); + + ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource(); + resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop1.csar"); + resourceDetails2.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + + checkResource(createResource, 8, container, "DBMS", propertyNamesValues); + checkResource(createResource, 8, scalable, userDefinedNodeType.getName(), propertyNamesValues1); + + } + + /** + * importResourceWithCapabilityWithPropertiesOverridingNodeTypeCapPropertiesFailed + * + * @throws Exception + */ + @Test + public void importResourceWithCapabilityWithPropertiesOverridingNodeTypeCapPropertiesFailed() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + RestResponse createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, + resourceDetails); + BaseRestUtils.checkCreateResponse(createResource); + + String payloadName = "vf_with_cap_prop_override_cap_type_prop1_failed.csar"; + resourceDetails = ElementFactory.getDefaultImportResource(); + Path path = Paths + .get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, + propertyForTestName); + + ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource(); + resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop1_failed.csar"); + resourceDetails2.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + BaseRestUtils.checkErrorResponse(createResource, ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, + propertyForTestName); + } + + private RestResponse importUserDefinedNodeType(String payloadName, User sdncModifierDetails, + ImportReqDetails resourceDetails) throws Exception { + + Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/" + payloadName); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VFC.name()); + return ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + } + + // TODO Tal: Since Cashing change partial resource returned that causes null + // pointer exception + // commented out till fixing + private void checkResource(RestResponse createResource, int capNum, String capType, String riName, + List> propertyNamesValues) { + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + Map> capabilities = resource.getCapabilities(); + // TODO Tal: Since Cashing change partial resource returned that causes + // null pointer exception + /* assertEquals(capabilities.size(), capNum); */ + /* + * List capabilitesContainer = + * capabilities.get(capType); + */ + + ComponentInstance resourceRI = resource.getComponentInstances().stream() + .filter(ri -> ri.getComponentName().equals(riName)).collect(Collectors.toList()).get(0); + // TODO Tal: Since Cashing change partial resource returned that causes + // null pointer exception + /* + * CapabilityDefinition capabilityFromContainer = + * capabilitesContainer.stream() + * .filter(cap->cap.getOwnerId().equals(resourceRI.getUniqueId())). + * collect(Collectors.toList()).get(0); + */ + + CapabilityDefinition capabilityFromRI = resourceRI.getCapabilities().get(capType).get(0); + for (ImmutablePair propValuePair : propertyNamesValues) { + // TODO Tal: Since Cashing change partial resource returned that + // causes null pointer exception + /* + * Map propertiesFromContainer = + * capabilityFromContainer.getProperties() + * .stream().filter(p->p.getName().equalsIgnoreCase(propValuePair. + * getLeft())) .collect(Collectors.toMap(p->p.getName(), p->p)); + */ + + List propertiesFromRI = capabilityFromRI.getProperties().stream() + .filter(p -> p.getName().equalsIgnoreCase(propValuePair.getLeft())).collect(Collectors.toList()); + // TODO Tal: Since Cashing change partial resource returned that + // causes null pointer exception + /* + * for(ComponentInstanceProperty riProp : propertiesFromRI){ + * assertTrue(propertiesFromContainer.containsKey(riProp.getName())) + * ; ComponentInstanceProperty containerProp = + * propertiesFromContainer.get(riProp.getName()); + * assertEquals(riProp.getValue(), containerProp.getValue()); + * if(riProp.getName().equals(propValuePair.getLeft())) + * assertEquals(riProp.getValue(), propValuePair.getRight()); + * + * } + */ + } + } + +} 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 new file mode 100644 index 0000000000..8ce8dc5433 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java @@ -0,0 +1,2896 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.http.client.ClientProtocolException; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapReqDef; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedResourceAuditJavaObject; +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.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Decoder; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.general.ImportUtils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils; +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.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ToscaNodeTypeInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import aj.org.objectweb.asm.Attribute; + +/** + * + * @author Andrey + Pavel + Shay + * + */ + +public class ImportToscaResourceTest extends ComponentBaseTest { + private static Logger logger = LoggerFactory.getLogger(ImportToscaResourceTest.class.getName()); + protected Utils utils = new Utils(); + + public ImportToscaResourceTest() { + super(name, ImportToscaResourceTest.class.getName()); + } + + public ImportReqDetails importReqDetails; + protected static User sdncUserDetails; + protected static User testerUser; + protected String testResourcesPath; + protected ResourceReqDetails resourceDetails; + private HashSet capabilitySources; + private int actualNumOfReqOrCap; + + @Rule + public static TestName name = new TestName(); + + @BeforeMethod + public void before() throws Exception { + importReqDetails = ElementFactory.getDefaultImportResource(); + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + resourceDetails = ElementFactory.getDefaultResource(); + String sourceDir = config.getResourceConfigDir(); + final String workDir = "importToscaResourceByCreateUrl"; + testResourcesPath = sourceDir + File.separator + workDir; + capabilitySources = new HashSet(); + actualNumOfReqOrCap = 0; + } + + @DataProvider + private static final Object[][] getYmlWithInValidListProperties() throws IOException, Exception { + return new Object[][] { { "ListPropertyFalure02.yml", "[false,\"truee\"]", "boolean" }, + { "ListPropertyFalure03.yml", "[false,3]", "boolean" }, + { "ListPropertyFalure04.yml", "[false,3.56]", "boolean" }, + { "ListPropertyFalure05.yml", "[10000,3.56]", "integer" }, + { "ListPropertyFalure06.yml", "[10000,\"aaaa\"]", "integer" }, + { "ListPropertyFalure07.yml", "[10000,true]", "integer" }, + { "ListPropertyFalure08.yml", "[10.5,true]", "float" }, + { "ListPropertyFalure09.yml", "[10.5,\"asdc\"]", "float" }, // type + // float + { "ListPropertyFalure11.yml", "[10.5,\"500.0@\"]", "float" }, // property + // list + // float + // type + // contain + // @ + // in + // default + // value + { "ListPropertyFalure12.yml", "[10000,\"3#\"]", "integer" }, // property + // list + // integer + // type + // contain + // # + // in + // default + // value + { "ListPropertyFalure13.yml", "[false,\"true%\"]", "boolean" }, // property + // list + // boolean + // type + // contain + // % + // in + // default + // value + { "ListPropertyFalure14.yml", "[false,\"falsee\",true]", "boolean" }, + { "ListPropertyFalure15.yml", "[10.5,\"10.6x\",20.5,30.5]", "float" } // float + // with + // value + // 10.6x + // instead + // 10.6f + + }; + } + + @DataProvider + private static final Object[][] getYmlWithInValidMapProperties() throws IOException, Exception { + return new Object[][] { { "MapPropertyFalure02.yml", "[false,\"truee\"]", "boolean" }, + { "MapPropertyFalure03.yml", "[false,3]", "boolean" }, + { "MapPropertyFalure04.yml", "[false,3.56]", "boolean" }, + { "MapPropertyFalure05.yml", "[10000,3.56]", "integer" }, + { "MapPropertyFalure06.yml", "[10000,\"aaaa\"]", "integer" }, + { "MapPropertyFalure07.yml", "[10000,true]", "integer" }, + { "MapPropertyFalure08.yml", "[10.5,true]", "float" }, + { "MapPropertyFalure09.yml", "[10.5,\"asdc\"]", "float" }, // type + // float + { "MapPropertyFalure11.yml", "[10.5,\"500.0@\"]", "float" }, // property + // list + // float + // type + // contain + // @ + // in + // default + // value + { "MapPropertyFalure12.yml", "[10000,\"3#\"]", "integer" }, // property + // list + // integer + // type + // contain + // # + // in + // default + // value + { "MapPropertyFalure13.yml", "[false,\"true%\"]", "boolean" }, // property + // list + // boolean + // type + // contain + // % + // in + // default + // value + { "MapPropertyFalure14.yml", "[false,\"falsee\",true]", "boolean" }, + { "MapPropertyFalure15.yml", "[10.5,\"10.6x\",20.5,30.5]", "float" } // float + // with + // value + // 10.6x + // instead + // 10.6f + + }; + } + + @DataProvider + private static final Object[][] getYmlWithInValidOccurrences() throws IOException, Exception { + return new Object[][] { { "occurencyFalure01.yml" }, // requirements [2 + // , 0] + { "occurencyFalure02.yml" }, // requirements [-1, 2] + { "occurencyFalure03.yml" }, // requirements [1 ,-2] + { "occurencyFalure05.yml" }, // requirements MAX occurrences not + // exist [ 1 , ] + { "occurencyFalure06.yml" }, // requirements [ 0 , 0 ] + { "occurencyFalure08.yml" }, // requirements [ 1.0 , 2.0 ] + { "occurencyFalure09.yml" }, // requirements [ "1" , "2" ] + { "occurencyFalure10.yml" }, // requirements [ ] + { "occurencyFalure11.yml" }, // requirements [ UNBOUNDED , + // UNBOUNDED ] + { "occurencyFalure31.yml" }, // capability [ 2, 1] + { "occurencyFalure32.yml" }, // capability [-1, 2] + { "occurencyFalure33.yml" }, // capability [1, -2] + { "occurencyFalure35.yml" }, // capability MAX occurrences not + // exist [ 1 , ] + { "occurencyFalure36.yml" }, // capability [ 0 , 0 ] + { "occurencyFalure38.yml" }, // capability [ 1.0 , 2.0 ] + { "occurencyFalure39.yml" }, // capability [ "1" , "2" ] + { "occurencyFalure40.yml" }, // capability [ ] + { "occurencyFalure41.yml" } // capability [ UNBOUNDED , + // UNBOUNDED ] + }; + } + + @DataProvider + private static final Object[][] getInvalidYmlWithOccurrences() throws IOException, Exception { + return new Object[][] { { "occurencyFalure04.yml" }, // requirements MIN + // occurrences + // not exist [ , + // 1] + { "occurencyFalure07.yml" }, // requirements [ @ , 1 ] + { "occurencyFalure34.yml" }, // capability MIN occurrences not + // exist [ , 1] + { "occurencyFalure37.yml" } // capability [ 0 , # ] + + }; + } + + // US656928 + protected final String importMapPropertySuccess = "importMapPropertySuccessFlow.yml"; + protected final String importAttributeSuccess = "importAttributeSuccessFlow.yml"; + protected final String importSuccessFile = "myCompute.yml"; + protected final String derivedFromMyCompute = "derivedFromMyCompute.yml"; + protected final String importSuccessVFFile = "myComputeVF.yml"; + protected final String importNoDerivedFromFile = "myComputeDerivedFromNotExists.yml"; + protected final String importInvalidDefinitionVersionFile = "myComputeIncorrectDefenitionVersionValue.yml"; + protected final String importIncorrectNameSpaceFormatFile = "myComputeIncorrectNameSpaceFormat.yml"; + protected final String importNoDefenitionVersionFile = "myComputeNoDefenitionVersion.yml"; + protected final String importNodeTypesTwiceFile = "myComputeWithNodeTypesTwice.yml"; + protected final String importTopologyTemplateFile = "myComputeWithTopologyTemplate.yml"; + protected final String importNoContentFile = "noContent.yml"; + protected final String importWithOccurrences = "myComputeOccurencySuccess.yml"; + protected final String importListPropertyBadDefault = "importListPropertyBadDefault.yml"; + protected final String importListPropertyGoodDefault = "importListPropertyGoodDefault.yml"; + protected final String importListPropertySuccess = "importListPropertySuccessFlow.yml"; + // US631462 + protected final String importDuplicateRequirements = "importDuplicateRequirements.yml"; + protected final String importDuplicateCapability = "importDuplicateCapability.yml"; + protected final String importCapabilityNameExistsOnParent = "importCapabilityNameExistsOnParent.yml"; + protected final String importRequirementNameExistsOnParent = "importRequirementNameExistsOnParent.yml"; + protected final String importToscaResourceReqCapDerivedFromParent = "derivedFromWebAppDerivedReqCap.yml"; + protected final String missingCapInReqDef = "missingCapInReqDefinition.yml"; + protected final String missingCapInCapDef = "missingCapInCapDefinition.yml"; + + // US558432 - Support for Capability/Requirement "occurences" Import + @Test(dataProvider = "getYmlWithInValidOccurrences") + public void importToscaResourceWithOccurrencesFailuresFlow01(String ymlFileWithInvalidCapReqOccurrences) + throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFileWithInvalidCapReqOccurrences); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_OCCURRENCES.name(), new ArrayList(), + importResourceResponse.getResponse()); + } + + @Test(dataProvider = "getInvalidYmlWithOccurrences") + public void importToscaResourceWithOccurrencesFailuresFlow02(String ymlFileWithInvalidCapReqOccurrences) + throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFileWithInvalidCapReqOccurrences); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_YAML_FILE.name(), new ArrayList(), + importResourceResponse.getResponse()); + } + + @Test + public void importToscaResource() throws Exception { + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importSuccessFile); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + AssertJUnit.assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + AssertJUnit.assertTrue("validate toscaResourceName field", + resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName())); + AssertJUnit.assertTrue("validate resourceType field", + resourceJavaObject.getResourceType().equals(ResourceTypeEnum.VFC)); + // find derived from resource details + // Validate resource details after import-create resource including + // capabilities, interfaces from derived_from resource + + // Validate audit message + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceWithOccurrencesSuccessFlow() throws Exception { + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importWithOccurrences); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + AssertJUnit.assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + AssertJUnit.assertTrue("validate toscaResourceName field", + resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName())); + AssertJUnit.assertTrue("validate resourceType field", + resourceJavaObject.getResourceType().equals(ResourceTypeEnum.VFC)); + String requirementsType = "tosca.capabilities.Attachment"; + String capabilitType = "tosca.capabilities.Endpoint.Admin"; + // Verify Occurrences of requirements and capabilities in resource + verifyRequirementsOccurrences(resourceJavaObject, requirementsType); + verifyCapabilitiesOccurrences(resourceJavaObject, capabilitType); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + // ------------------------------Success--------------------------------- + + @Test(enabled = false) + public void importToscaResourceVFResType() throws Exception { + + String resourceType = ResourceTypeEnum.VF.toString(); + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importSuccessVFFile); + // importReqDetails.setResourceType(resourceType); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + assertTrue("validate toscaResourceName field", + resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName())); + assertTrue( + "validate resourceType field, expected - " + resourceType + ", actual - " + + resourceJavaObject.getResourceType(), + resourceJavaObject.getResourceType().toString().equals(resourceType)); + + // Validate audit message + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + // ------------------------------Failure--------------------------------- + + @Test + public void importToscaResourceDerivedFromNotExist() throws Exception { + + String fileName = importNoDerivedFromFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + // List derivedFrom = new ArrayList() ; + // derivedFrom.add("hh"); + // importReqDetails.setDerivedFrom(derivedFrom); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.PARENT_RESOURCE_NOT_FOUND.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PARENT_RESOURCE_NOT_FOUND.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceIncorrectDefinitionVersion() throws Exception { + + String fileName = importInvalidDefinitionVersionFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_TOSCA_TEMPLATE.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceIncorrectSpaceNameFormat() throws Exception { + + String fileName = importIncorrectNameSpaceFormatFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_NAMESPACE.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_NAMESPACE.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceNoDefinitionVersion() throws Exception { + + String fileName = importNoDefenitionVersionFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_TOSCA_TEMPLATE.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceNoContent() throws Exception { + + String fileName = importNoContentFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_PAYLOAD.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_PAYLOAD.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceWithTopologyTemplate() throws Exception { + + String fileName = importTopologyTemplateFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceWithNodeTypesTwice() throws Exception { + + String fileName = importNodeTypesTwiceFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_SINGLE_RESOURCE.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_SINGLE_RESOURCE.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + // failed case - uniqueness of toscaResourceName - RESOURCE_ALREADY_EXISTS + @Test + public void importToscaResourceTwice() throws Exception { + String fileName = importSuccessFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + RestResponse checkInresponse = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertTrue("checkIn resource request returned status:" + checkInresponse.getErrorCode(), + checkInresponse.getErrorCode() == 200); + + // Validate audit message + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + + // import the same tosca resource with different resourceName + DbUtils.cleanAllAudits(); + + importReqDetails.setName("kuku"); + List tags = new ArrayList(); + tags.add(importReqDetails.getName()); + importReqDetails.setTags(tags); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_ALREADY_EXISTS.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name(), variables, + importResourceResponse.getResponse()); + + expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(importReqDetails.getToscaResourceName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + + } + + @Test + public void importToscaResourceWithTheSameNameAsCreatedResourceBefore() throws Exception { + + // create resource + String fileName = importSuccessFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName(importReqDetails.getName()); + + RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails); + int status = response.getErrorCode(); + assertEquals("create request returned status:" + status, 201, status); + assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId()); + Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + // assertNull("validate toscaResourceName field", + // resourceJavaObject.getToscaResourceName()); + + // import the same tosca resource + DbUtils.cleanAllAudits(); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_ALREADY_EXISTS.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + + } + + @Test + public void importToscaResourceInvalidChecksum() throws Exception { + String fileName = importSuccessFile; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), "invalidMd5Sum"); + + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + headersMap); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + assertNotNull("check response object is not null after import tosca resource", importResourceResponse); + assertNotNull("check error code exists in response after import tosca resource", + importResourceResponse.getErrorCode()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_CHECKSUM.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_CHECKSUM.name(), variables, + importResourceResponse.getResponse()); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceInvalidResType() throws Exception { + + String resourceType = "invalidResourceType"; + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importSuccessFile); + importReqDetails.setResourceType(resourceType); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name()); + assertNotNull("check response object is not null after import resouce", importResourceResponse); + assertNotNull("check error code exists in response after import resource", + importResourceResponse.getErrorCode()); + assertEquals("Check response code after import resource", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + + List variables = new ArrayList<>(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, + importResourceResponse.getResponse()); + + // Validate audit message + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void derivedTemplateImportedSecondResourceAsFirstImportedNodeType() throws Exception { + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importSuccessFile); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + assertTrue("validate toscaResourceName field", + resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName())); + assertTrue( + "validate resourceType field, expected - " + importReqDetails.getResourceType() + ", actual - " + + resourceJavaObject.getResourceType(), + resourceJavaObject.getResourceType().toString().equals(importReqDetails.getResourceType())); + + // Validate audit message + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + + RestResponse certifyResource = LifecycleRestUtils.certifyResource(importReqDetails); + assertTrue("certify resource request returned status:" + certifyResource.getErrorCode(), + certifyResource.getErrorCode() == 200); + + // import second resource template derived from first resource + DbUtils.cleanAllAudits(); + importReqDetails.setName("kuku"); + List tags = new ArrayList(); + tags.add(importReqDetails.getName()); + importReqDetails.setTags(tags); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + derivedFromMyCompute); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + Resource resourceJavaObject2 = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + assertTrue("validate toscaResourceName field", + resourceJavaObject2.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName())); + assertTrue( + "validate resourceType field, expected - " + importReqDetails.getResourceType() + ", actual - " + + resourceJavaObject2.getResourceType(), + resourceJavaObject2.getResourceType().toString().equals(importReqDetails.getResourceType())); + + // Validate audit message + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject2 = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject2.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject2.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject2.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject2.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject2, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + + } + + @Test + public void importToscaResourceListPropertyGoodDefault() throws Exception { + + String fileName = importListPropertyGoodDefault; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), + importResourceResponse.getErrorCode() == 201); + + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + assertTrue("Properties size : " + resourceJavaObject.getProperties().size(), + resourceJavaObject.getProperties().size() == 1); + assertTrue("Property type : " + resourceJavaObject.getProperties().get(0).getType(), + resourceJavaObject.getProperties().get(0).getType().equals(ToscaPropertyType.LIST.getType())); + assertTrue( + "actual Default values : " + resourceJavaObject.getProperties().get(0).getDefaultValue() + + " , expected : " + "[false, true]", + resourceJavaObject.getProperties().get(0).getDefaultValue().equals("[\"false\",\"true\"]")); + + } + + @Test + public void importToscaResourceListPropertyBadDefault() throws Exception { + + String fileName = importListPropertyBadDefault; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name()); + assertEquals("Check response code after tosca resource import", errorInfo.getCode(), + importResourceResponse.getErrorCode()); + ArrayList variables = new ArrayList<>(); + variables.add("my_prop"); + variables.add("list"); + variables.add("boolean"); + variables.add("[12,true]"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, + importResourceResponse.getResponse()); + + } + + // Benny US580744 - Add support for TOSCA "list" type - import + + @Test + public void importToscaResourceListPropertySuccessFlow() throws Exception { + String fileName = importListPropertySuccess; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + ResourceRestUtils.checkCreateResponse(importResourceResponse); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + // Verify Properties List in resource + verifyResourcePropertiesList(resourceJavaObject); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + // DE198534 + @Test(dataProvider = "getYmlWithInValidListProperties") // invalid default + // values + public void importToscaResourceListPropertyFailureFlows(String ymlFileWithInvalidPropertyDefualtValues, + String defualtValues, String enterySchemaType) throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFileWithInvalidPropertyDefualtValues); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("my_property"); + variables.add("list"); + variables.add(enterySchemaType); + variables.add(defualtValues); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, + importResourceResponse.getResponse()); + } + + // BUG DE198650 + @Test + public void importToscaResourceListPropertyNonSupportEntrySchemaType() throws Exception { + String ymlFile = "ListPropertyFalure01.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFile); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("booolean"); // property entry_schema data type + variables.add("my_boolean"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables, + importResourceResponse.getResponse()); + } + + // BUG DE198676 + @Test // (enabled=false) + public void importToscaResourceListPropertyNonSupportedPropertyType() throws Exception { // Not + // "list" + // type + String ymlFile = "ListPropertyFalure16.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFile); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("koko"); // property data type (koko instead list) + variables.add("my_boolean"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables, + importResourceResponse.getResponse()); + } + + /// US656928 - [BE] - Add support for TOSCA "map" type - Phase 1 import + @Test + public void importToscaResourceMapPropertySuccessFlow() throws Exception { + String fileName = importMapPropertySuccess; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + ResourceRestUtils.checkCreateResponse(importResourceResponse); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + // Verify Properties MAP in resource + verifyResourcePropertiesMap(resourceJavaObject); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test(dataProvider = "getYmlWithInValidMapProperties") // invalid default + // values + public void importToscaResourceMapPropertyFailureFlows(String ymlFileWithInvalidPropertyDefualtValues, + String defualtValues, String enterySchemaType) throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFileWithInvalidPropertyDefualtValues); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("my_property"); + variables.add("map"); + variables.add(enterySchemaType); + variables.add(defualtValues); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, + importResourceResponse.getResponse()); + } + + @Test + public void importToscaResourceMaptPropertyNonSupportedPropertyType() throws Exception { // Not + // "Map" + // type + String ymlFile = "MapPropertyFalure16.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFile); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("koko"); // property data type (koko instead list) + variables.add("my_boolean"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables, + importResourceResponse.getResponse()); + } + + @Test + public void importToscaResourceMissingCapabilityInReqDefinition() throws Exception { + + String fileName = missingCapInReqDef; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_CAPABILITY_TYPE.name()); + String missingCapName = "org.openecomp.capabilities.networkInterfaceNotFound"; + BaseRestUtils.checkErrorResponse(importResourceResponse, ActionStatus.MISSING_CAPABILITY_TYPE, missingCapName); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, Arrays.asList(missingCapName)); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType("org.openecomp.resource.vSCP-03-16"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceMissingCapabilityInCapDefinition() throws Exception { + + String fileName = missingCapInCapDef; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage()); + + // Validate audit message + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_CAPABILITY_TYPE.name()); + String missingCapName = "org.openecomp.capabilities.networkInterfaceNotFound"; + BaseRestUtils.checkErrorResponse(importResourceResponse, ActionStatus.MISSING_CAPABILITY_TYPE, missingCapName); + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, Arrays.asList(missingCapName)); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType("org.openecomp.resource.vSCP-03-16"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceDuplicateRequirements() throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importDuplicateRequirements); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("requirement"); + variables.add("local_storage"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name(), variables, + importResourceResponse.getResponse()); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceDuplicateCapabilities() throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importDuplicateCapability); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("capability"); + variables.add("scalable"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name(), variables, + importResourceResponse.getResponse()); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceRequirementNameExistsOnParent() throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importRequirementNameExistsOnParent); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("requirement"); + variables.add("local_storage"); + variables.add("Compute"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), + variables, importResourceResponse.getResponse()); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceCapabilityNameExistsOnParent() throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importCapabilityNameExistsOnParent); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add("capability"); + variables.add("binding"); + variables.add("Compute"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), + variables, importResourceResponse.getResponse()); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgFailure(errorInfo, variables); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + @Test + public void importToscaResourceReqCapDerivedFromParent() throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + importToscaResourceReqCapDerivedFromParent); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + BaseRestUtils.checkCreateResponse(importResourceResponse); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType("org.openecomp.resource.MyWebApp"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + /************************ Shay ************************/ + + @Test + public void caseRequirementInsensitiveTest() throws Exception { + String fileName = "CaseInsensitiveReqTest_1.yml"; + int expectedNumOfRequirements = 2; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + importReqDetails.setRequirements(testResourcesPath, fileName, sdncUserDetails, null); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String fileName2 = "CaseInsensitiveReqTest_2.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName2); + importReqDetails.setName("secondImportedResource"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, null); + requirements = importReqDetails.getRequirements(); + requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + checkImportedAssetAssociated(importReqDetails); + + } + + private void checkImportedAssetAssociated(ImportReqDetails importDetails) throws IOException, Exception { + RestResponse importResourceResponse; + ImportReqDetails importReqDetails2 = ElementFactory.getDefaultImportResource(); + importReqDetails2 = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails2, testResourcesPath, + "BindingAsset.yml"); + importReqDetails2.setName("bindingAsset"); + importReqDetails2.setTags(Arrays.asList(importReqDetails2.getName())); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails2, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + ResourceReqDetails vf = ElementFactory.getDefaultResourceByType("VF100", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncUserDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + RestResponse createResourceResponse = ResourceRestUtils.createResource(vf, sdncUserDetails); + ResourceRestUtils.checkCreateResponse(createResourceResponse); + + LifecycleRestUtils.changeResourceState(importDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + LifecycleRestUtils.changeResourceState(importReqDetails2, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + + RestResponse response = ResourceRestUtils.createResourceInstance(importDetails, sdncUserDetails, + vf.getUniqueId()); + ResourceRestUtils.checkCreateResponse(response); + ComponentInstance riCap = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class); + + response = ResourceRestUtils.createResourceInstance(importReqDetails2, sdncUserDetails, vf.getUniqueId()); + ResourceRestUtils.checkCreateResponse(response); + ComponentInstance riReq = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class); + + RestResponse getResourceBeforeAssociate = ComponentRestUtils + .getComponentRequirmentsCapabilities(sdncUserDetails, vf); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceBeforeAssociate.getResponse(), CapReqDef.class); + + String capbilityUid = capReqDef.getCapabilities().get("tosca.capabilities.network.Bindable").get(0) + .getUniqueId(); + String requirementUid = capReqDef.getRequirements().get("tosca.capabilities.network.Bindable").get(0) + .getUniqueId(); + + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + requirementDef.setFromNode(riReq.getUniqueId()); + requirementDef.setToNode(riCap.getUniqueId()); + + RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(); + pair.setRequirementOwnerId(riReq.getUniqueId()); + pair.setCapabilityOwnerId(riCap.getUniqueId()); + pair.setRequirement("VirtualBinding"); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("tosca.capabilities.network.Bindable"); + pair.setRelationships(relationship); + pair.setCapabilityUid(capbilityUid); + pair.setRequirementUid(requirementUid); + List relationships = new ArrayList<>(); + relationships.add(pair); + requirementDef.setRelationships(relationships); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncUserDetails, + vf.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + } + + @Test + public void caseCapabilitiesInsensitiveTest() throws Exception { + String fileName = "CaseInsensitiveCapTest_1.yml"; + int expectedNumOfCapabilities = 6; + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setCapabilities(testResourcesPath, fileName, sdncUserDetails, null); + Map capabilities = importReqDetails.getCapabilities(); + Map capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String fileName2 = "CaseInsensitiveCapTest_2.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName2); + importReqDetails.setName("secondImportedResource"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setCapabilities(testResourcesPath, fileName2, sdncUserDetails, null); + capabilities = importReqDetails.getCapabilities(); + capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + + } + + @Test + public void fatherAndChildHaveDifferentRequirementsTest() throws Exception { + String fileName = "DifferentReqFromCompute.yml"; + int expectedNumOfRequirements = 3; + + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, fileName, sdncUserDetails, "Compute"); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + checkImportedAssetAssociated(importReqDetails); + } + + @Test + public void fatherHasNoRequirementsTest() throws Exception { + String fatherFileName = "CPHasNoReqCap.yml"; + String childFileName = "DerivedFromCPWithOwnReq.yml"; + int expectedNumOfRequirements = 3; + + importReqDetails.setName("father"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String derivedFromResourceName = importReqDetails.getName(); + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromResourceName); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + } + + @Test + public void childHasSameReqNameAndTypeLikeFatherTest() throws Exception { + String childFileName = "SameReqAsCompute.yml"; + int expectedNumOfRequirements = 2; + + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, null); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + } + + @Test + public void childHasSameCapNameAndTypeLikeFatherTest() throws Exception { + String childFileName = "SameCapAsCompute.yml"; + int expectedNumOfCapabilities = 6; + + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + "Compute"); + Map capabilities = importReqDetails.getCapabilities(); + Map capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + } + + @Test + public void childGetsAllRequirementsOfFatherAndGrandfatherTest() throws Exception { + int expectedNumOfRequirements = 4; + + String fatherFileName = "DifferentReqFromCompute.yml"; + importReqDetails.setName("father"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String derivedFromName = importReqDetails.getName(); + String childFileName = "DifferentReqCapFromCompute1.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + } + + @Test + public void childOverridesGrandfatherRequirementsTest() throws Exception { + int expectedNumOfRequirements = 3; + + String fatherFileName = "DifferentReqFromCompute.yml"; + importReqDetails.setName("father"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String derivedFromName = importReqDetails.getName(); + String childFileName = "SameReqAsCompute_DerivedFromMyCompute1.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + } + + @Test + public void childAndGrandfatherHaveDifferenetReqiurementTypeTest() throws Exception { + int expectedNumOfRequirements = 3; + int expectedNumOfCapabilities = 6; + + String fatherName = "father"; + String fatherFileName = "DifferentReqFromCompute.yml"; + importReqDetails.setName(fatherName); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String fatherUniqueId = importReqDetails.getUniqueId(); + ImportReqDetails importReqDetailsFather = importReqDetails; + + String childFileName = "importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_INVALID_CONTENT, importResourceResponse.getErrorCode().intValue()); + ArrayList variables = new ArrayList<>(); + variables.add("requirement"); + variables.add("local_storage"); + variables.add(fatherName); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), + variables, importResourceResponse.getResponse()); + + importReqDetails.setUniqueId(fatherUniqueId); + + importReqDetailsFather.setRequirements(testResourcesPath, fatherFileName, sdncUserDetails, "Compute"); + Map requirements = importReqDetailsFather.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetailsFather, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetailsFather.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + importReqDetailsFather.setCapabilities(testResourcesPath, fatherFileName, sdncUserDetails, "Compute"); + Map capabilities = importReqDetailsFather.getCapabilities(); + Map capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetailsFather, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + } + + @Test + public void childHasNoReqCapTest() throws Exception { + int expectedNumOfRequirements = 3; + int expectedNumOfCapabilities = 6; + + String fatherFileName = "DifferentReqFromCompute.yml"; + importReqDetails.setName("father"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String derivedFromName = importReqDetails.getName(); + String childFileName = "CPHasNoReqCap_DerivedFromMyCompute1.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map capabilities = importReqDetails.getCapabilities(); + Map capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + } + + @Test + public void fatherAndChildGetReqCapFromGrandfatherTest() throws Exception { + int expectedNumOfRequirements = 2; + int expectedNumOfCapabilities = 6; + + String fatherFileName = "MyFatherCompute_NoReqCap.yml"; + importReqDetails.setName("father"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String derivedFromName = importReqDetails.getName(); + String childFileName = "myChildCompute_NoReqCap.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map requirements = importReqDetails.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map capabilities = importReqDetails.getCapabilities(); + Map capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + } + + @Test + public void reverseInheritanceTest() throws Exception { + int expectedNumOfRequirements = 2; + int expectedNumOfCapabilities = 2; + + String fatherName = "father"; + String fatherFileName = "myFatherWebApp_derviedFromDocker.yml"; + importReqDetails.setName(fatherName); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String fatherUniqueId = importReqDetails.getUniqueId(); + ImportReqDetails importReqDetailsFather = importReqDetails; + String childFileName = "myChildWebApp_DerivedFromContainer.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_INVALID_CONTENT, importResourceResponse.getErrorCode().intValue()); + ArrayList variables = new ArrayList<>(); + variables.add("requirement"); + variables.add("host"); + variables.add(fatherName); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), + variables, importResourceResponse.getResponse()); + + importReqDetails.setUniqueId(fatherUniqueId); + importReqDetailsFather.setRequirements(testResourcesPath, fatherFileName, sdncUserDetails, "Root"); + Map requirements = importReqDetailsFather.getRequirements(); + Map requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetailsFather, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size()); + importReqDetailsFather.compareRequirementsOrCapabilities(requirements, requirementsFromResponse); + + importReqDetailsFather.setCapabilities(testResourcesPath, fatherFileName, sdncUserDetails, "Root"); + Map capabilities = importReqDetailsFather.getCapabilities(); + Map capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetailsFather, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size()); + importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse); + } + + // DE202329 + @Test(enabled = false) + public void requirementWithMissingTypeTest() throws Exception { + String fatherName = "father"; + String fatherFileName = "DerivedFromWebApplication_HasNoReqType.yml"; + importReqDetails.setName(fatherName); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_INVALID_CONTENT, importResourceResponse.getErrorCode().intValue()); + ArrayList variables = new ArrayList<>(); + variables.add("diff"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_CAPABILITY_TYPE.name(), variables, + importResourceResponse.getResponse()); + + } + + @Test + public void TwinBrothersHaveSameReqCapTest() throws Exception { + int expectedNumOfRequirements = 4; + int expectedNumOfCapabilities = 7; + + String derivedFromName = "father"; + String fatherFileName = "DifferentReqFromCompute.yml"; + importReqDetails.setName(derivedFromName); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fatherFileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue()); + RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue()); + RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue()); + + String childFileName = "DifferentReqCapFromCompute1.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("child"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + childFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + Map childRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + Map childCapabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities - 1); + + String twinFileName = "DifferentReqCapFromCompute2.yml"; + importReqDetails = ElementFactory.getDefaultImportResource(); + importReqDetails.setName("twin"); + importReqDetails.setTags(Arrays.asList(importReqDetails.getName())); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + twinFileName); + importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + + importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map requirements = importReqDetails.getRequirements(); + Map twinRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, + expectedNumOfRequirements); + assertEquals(requirements.keySet().size(), twinRequirementsFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(requirements, twinRequirementsFromResponse); + + importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, + derivedFromName); + Map capabilities = importReqDetails.getCapabilities(); + Map twinCapabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, + expectedNumOfCapabilities); + assertEquals(capabilities.keySet().size(), twinCapabilitiesFromResponse.keySet().size()); + importReqDetails.compareRequirementsOrCapabilities(capabilities, twinCapabilitiesFromResponse); + + assertEquals(childRequirementsFromResponse.keySet().size(), twinRequirementsFromResponse.keySet().size()); + assertEquals(childCapabilitiesFromResponse.keySet().size(), twinCapabilitiesFromResponse.keySet().size()); + } + + /* + * invariantUUID - US672129 + */ + + private void checkInvariantUuidIsImmutableInDifferentAction(ImportReqDetails importReqDetails) throws Exception { + // create resource + importReqDetails.setName("import"); + String invariantUuidDefinedByUser = "abcd1234"; + RestResponse importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, + invariantUuidDefinedByUser); + String invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse); + assertFalse(checkInvariantUuidEqual(invariantUuidDefinedByUser, importResourceResponse)); + + // get resource + RestResponse getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, getResource)); + + // checkin resource + RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // checkout resource + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // checkin resource + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // checkout resource + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // checkin resource + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // certification request + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // start certification + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // certify + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, + LifeCycleStatesEnum.CERTIFY); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + String certifiedUniqueId = importReqDetails.getUniqueId(); + + // update resource + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceReqDetails updatedResourceReqDetails = new ResourceReqDetails(importReqDetails, + importReqDetails.getVersion()); + updatedResourceReqDetails.setDescription("updatedDescription"); + updatedResourceReqDetails.setVendorRelease("1.2.3.4"); + RestResponse updateResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceReqDetails, + sdncUserDetails, importReqDetails.getUniqueId()); + assertEquals(STATUS_CODE_SUCCESS, updateResponse.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, updateResponse)); + + // certification request + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // checkout resource + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // certification request + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // start certification + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // cancel certification + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, + LifeCycleStatesEnum.CANCELCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // start certification + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // failure + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, + LifeCycleStatesEnum.FAILCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // upload artifact + changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, + LifeCycleStatesEnum.CHECKOUT); + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact(); + ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncUserDetails, + importReqDetails.getUniqueId()); + assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState)); + + // create instance + resourceDetails.setResourceType(ResourceTypeEnum.VF.toString()); + ResourceRestUtils.createResource(resourceDetails, sdncUserDetails); + importReqDetails.setUniqueId(certifiedUniqueId); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(importReqDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncUserDetails, resourceDetails.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals(STATUS_CODE_CREATED, createResourceInstanceResponse.getErrorCode().intValue()); + getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId()); + assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, getResource)); + } + + private boolean checkInvariantUuidEqual(String expectedInvariantUuid, RestResponse response) { + String invariantUUIDFromResponse = ResponseParser.getInvariantUuid(response); + return expectedInvariantUuid.equals(invariantUUIDFromResponse); + } + + @Test + public void checkCPHasImmutableInvariantUuidTest() throws Exception { + String filename = "FatherHasNoReqCap.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + filename); + checkResourceHasImmutableInvariantUuidTest(importReqDetails); + } + + @Test + public void checkVFCHasImmutableInvariantUuidTest() throws Exception { + String filename = "computeCap11.yml"; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + filename); + checkResourceHasImmutableInvariantUuidTest(importReqDetails); + } + + public void checkResourceHasImmutableInvariantUuidTest(ImportReqDetails importReqDetails) throws Exception { + // invariantUuid is null + importReqDetails.setName("first"); + RestResponse importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, null); + String invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse); + assertNotNull(invariantUUIDcreation); + + ResourceRestUtils.deleteResource(importReqDetails.getUniqueId(), sdncUserDetails.getUserId()); + + // invariantUuid is empty + importReqDetails.setName("second"); + String invariantUuidDefinedByUser = ""; + importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, invariantUuidDefinedByUser); + invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse); + assertNotNull(invariantUUIDcreation); + + ResourceRestUtils.deleteResource(importReqDetails.getUniqueId(), sdncUserDetails.getUserId()); + + checkInvariantUuidIsImmutableInDifferentAction(importReqDetails); + } + + private static RestResponse importResourceWithRequestedInvariantUuid(ImportReqDetails importDetails, + String invariantUuid) throws Exception { + importDetails.setInvariantUUID(invariantUuid); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importDetails, sdncUserDetails, + null); + assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue()); + return importResourceResponse; + } + + private Map parseReqOrCapFromResponse(String parsedFieldName, ImportReqDetails importReqDetails, + int expectedNumOfReqCap) throws ClientProtocolException, IOException { + RestResponse getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId()); + assertTrue(getResource.getErrorCode().equals(STATUS_CODE_SUCCESS)); + Map parsedFieldFromResponseToMap = ResponseParser.getJsonValueAsMap(getResource, + parsedFieldName); + Iterator iterator = parsedFieldFromResponseToMap.keySet().iterator(); + actualNumOfReqOrCap = 0; + while (iterator.hasNext()) { + String next = iterator.next(); + List object = (List) parsedFieldFromResponseToMap.get(next); + actualNumOfReqOrCap += object.size(); + } + assertEquals(expectedNumOfReqCap, actualNumOfReqOrCap); + return parsedFieldFromResponseToMap; + } + + // --------------------------------- + + private void verifyResourcePropertiesList(Resource resourceJavaObject) { // use + // importListPropertySuccessFlow.yml + boolean isPropertyAppear = false; + List propertiesList = resourceJavaObject.getProperties(); + for (PropertyDefinition pro : propertiesList) { + switch (pro.getName()) { + case "my_boolean": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[false,true]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "my_boolean_array": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "duplicate_boolean_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false,true]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_values_Insensitive": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false,true]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "my_integers": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[0,1000,-1000,50]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "my_integers_array": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[10,-1000,0]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "duplicate_integers_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[10,10,-1000,0]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "my_string": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("[\"asdc\",\"$?^@ecomp$!#%()_-~@+*^...;;/w#\",\"uc\"]")); + // assertTrue("Check Property default values ", + // pro.getDefaultValue().equals("[\"asdc\",\"@=~!@#$%^&*()_+=?><:-w\",\"uc\"]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "my_string_array": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("[\"AAA\",\"~$~#bbb%^*_-\",\"qwe\",\"1.3\",\"500\",\"true\"]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "duplicate_string_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("[\"asdc\",\"asdc\",\"uc\"]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_null_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"asdc\",\"uc\"]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_space_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"asdc\",\"uc\"]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_array_null_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("[\"aaa\",\"bbb\",\"500\"]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "my_float": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[6,1000.000001,-3.0]")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "my_float_array": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[0.01,-5.0,2.1]")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "duplicate_float_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[0.0,0.0,4.555555]")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_no_default_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "integer_no_default_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "string_no_default_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "boolean_no_default_values": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "integer_null_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[1000,2000]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "boolean_null_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false]")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "float_null_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[6,-3.0]")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_space_value": + assertTrue("Check Property Type ", pro.getType().equals("list")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("[6,-3.0]")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + + } + assertTrue(isPropertyAppear); + isPropertyAppear = false; + } + + } + + private void verifyRequirementsOccurrences(Resource resourceJavaObject, String requirementsType) { + boolean isRequirementAppear = false; + // List requerments = + // resourceJavaObject.getRequirements().get("tosca.capabilities.Attachment"); + List requerments = resourceJavaObject.getRequirements().get(requirementsType); + + for (RequirementDefinition req : requerments) { + switch (req.getName()) { + case "local_storage100": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1")); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("UNBOUNDED")); + isRequirementAppear = true; + break; + case "local_storage200": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1")); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("1")); + isRequirementAppear = true; + break; + case "local_storage300": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1")); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("10")); + isRequirementAppear = true; + break; + case "local_storage400": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1")); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("10000000")); + isRequirementAppear = true; + break; + case "local_storage500": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("2")); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("3")); + isRequirementAppear = true; + break; + case "local_storageNoOccurrences600": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1")); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("1")); + isRequirementAppear = true; + break; + } + assertTrue(isRequirementAppear); + isRequirementAppear = false; + } + + } + + private void verifyCapabilitiesOccurrences(Resource resourceJavaObject, String capabilitType) { + boolean isCapabilityAppear = false; + // List capabilities = + // resourceJavaObject.getCapabilities().get("tosca.capabilities.Endpoint.Admin"); + List capabilities = resourceJavaObject.getCapabilities().get(capabilitType); + + for (CapabilityDefinition cap : capabilities) { + switch (cap.getName()) { + case "endpointNoOccurrence": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("UNBOUNDED")); + isCapabilityAppear = true; + break; + case "endpoint200": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("2")); + isCapabilityAppear = true; + break; + case "endpoint300": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("1")); + isCapabilityAppear = true; + break; + case "endpoint400": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("10")); + isCapabilityAppear = true; + break; + case "endpoint500": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("10000000")); + isCapabilityAppear = true; + break; + case "endpoint600": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("UNBOUNDED")); + isCapabilityAppear = true; + break; + case "endpoint700": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("2")); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("4")); + isCapabilityAppear = true; + break; + + } + assertTrue(isCapabilityAppear); + isCapabilityAppear = false; + } + + } + + private void verifyResourcePropertiesMap(Resource resourceJavaObject) { // use + // importMapPropertySuccessFlow.yml + boolean isPropertyAppear = false; + List propertiesList = resourceJavaObject.getProperties(); + for (PropertyDefinition pro : propertiesList) { + switch (pro.getName()) { + case "string_prop01": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"val1\",\"keyB\":\"val2\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop02": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"val1\",\"keyB\":\"val2\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop03": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"val1\",\"keyB\":\"val2\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop04": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"10\",\"keyB\":\"true\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop05": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":\"Big\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop06": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"aaaA\",\"keyB\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop07": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop08": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"\",\"keyB\":\"abcd\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop09": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\" \",\"keyB\":\"abcd\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop10": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\" aaaa\",\"keyB\":\" bbbb\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop11": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\"aaaa \",\"keyB\":\"bbbb \"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop12": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":\" aaaa \",\"keyB\":\" bbbb ccccc \"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop13": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"aaaa\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop14": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\" aaaa \"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop15": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop16": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop17": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop18": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop19": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop20": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue() + .equals("{\"keyA\":\"aaaa\",\"keya\":\"aaaa\",\"Keya\":\"Aaaa\",\"KEYA\":\"nnnn\"}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop21": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "string_prop22": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("string")); + isPropertyAppear = true; + break; + case "integer_prop01": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":1,\"keyB\":1000}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop02": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop03": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":800,\"keyB\":-600}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop04": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":-600}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop05": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":0}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop06": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":0}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop07": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":100}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop08": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":200}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop09": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":200}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop10": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":2222}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop11": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop12": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "integer_prop13": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":200}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("integer")); + isPropertyAppear = true; + break; + case "boolean_prop01": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false,\"keyC\":false}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop02": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false,\"keyC\":false}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop03": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop04": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop05": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false,\"keyC\":false}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop06": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":true,\"keyC\":false}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop07": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop08": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "boolean_prop09": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":false,\"keyB\":true}")); + assertTrue("Check entrySchema Property Type ", + pro.getSchema().getProperty().getType().equals("boolean")); + isPropertyAppear = true; + break; + case "float_prop01": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":1.2,\"keyB\":3.56,\"keyC\":33}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop02": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":0.0,\"keyB\":0.0,\"keyC\":0}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop03": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop04": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":1.2,\"keyB\":3.56,\"keyC\":33}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop05": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":33,\"keyB\":1.2,\"keyC\":3.607,\"keyD\":0}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop06": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":33,\"keyB\":1.2,\"keyC\":3.607}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop07": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop08": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertEquals("Check Property default values ", pro.getDefaultValue(), null); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop09": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":0.01,\"keyB\":null}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop10": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":0.00020}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + case "float_prop11": + assertTrue("Check Property Type ", pro.getType().equals("map")); + assertTrue("Check Property default values ", + pro.getDefaultValue().equals("{\"keyA\":3.56,\"keyB\":33}")); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float")); + isPropertyAppear = true; + break; + } + assertTrue(isPropertyAppear); + isPropertyAppear = false; + } + + } + + @Test + public void importToscaResourceAttributeSuccessFlow() throws Exception { + + String fileName = importAttributeSuccess; + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, + null); + ResourceRestUtils.checkCreateResponse(importResourceResponse); + Resource resourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + ToscaNodeTypeInfo parseToscaNodeYaml = utils + .parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData())); + + HashMap attr = new HashMap<>(); + + PropertyDefinition newAttr2 = new PropertyDefinition(); + newAttr2.setName("networks"); + newAttr2.setType("map"); + newAttr2.setDefaultValue("{\"keyA\" : val1 , \"keyB\" : val2}"); + SchemaDefinition schema = new SchemaDefinition(); + PropertyDataDefinition prop = new PropertyDataDefinition(); + prop.setType("string"); + schema.setProperty(prop); + newAttr2.setSchema(schema); + attr.put("networks", newAttr2); + + PropertyDefinition newAttr1 = new PropertyDefinition(); + newAttr1.setName("public_address"); + newAttr1.setType("string"); + attr.put("public_address", newAttr1); + + PropertyDefinition newAttr3 = new PropertyDefinition(); + newAttr3.setName("ports"); + newAttr3.setDescription("this is my description"); + attr.put("ports", newAttr3); + + PropertyDefinition newAttr = new PropertyDefinition(); + newAttr.setDefaultValue("myDefault"); + newAttr.setName("private_address"); + newAttr.setStatus("supported"); + newAttr.setType("string"); + attr.put("private_address", newAttr); + + // verify Resource Attributes + validateResourceAttribute(resourceJavaObject, attr); + + // TO DO + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory + .getDefaultImportResourceAuditMsgSuccess(); + expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName()); + expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName()); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName()); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false); + } + + private void validateResourceAttribute(Resource resource, Map attr) { + List resList = resource.getAttributes(); + int size = resList.size(); + String attributeName; + for (int i = 0; i < size; i++) { + attributeName = resList.get(i).getName(); + assertEquals(attr.get(attributeName).getDefaultValue(), resList.get(i).getDefaultValue()); + assertEquals(attr.get(attributeName).getName(), resList.get(i).getName()); + assertEquals(attr.get(attributeName).getDescription(), resList.get(i).getDescription()); + assertEquals(attr.get(attributeName).getStatus(), resList.get(i).getStatus()); + } + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java new file mode 100644 index 0000000000..464ebe12ed --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java @@ -0,0 +1,283 @@ +/*- + * ============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.ci.tests.execute.imports; + +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.assertEquals; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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.BaseRestUtils; +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.common.api.Constants; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class ImportUpdateResourseCsarTest extends ComponentBaseTest { + @Rule + public static TestName name = new TestName(); + + Gson gson = new Gson(); + public static String userDefinedNodeYaml = "mycompute2.yml"; + public static String rootPath = System.getProperty("user.dir"); + public static String csarFolderPath = "/src/test/resources/CI/csars/"; + + public ImportUpdateResourseCsarTest() { + super(name, ImportUpdateResourseCsarTest.class.getName()); + } + + @Test + public void createUpdateImportResourceFromCsarTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + RestResponse updateResource = null; + RestResponse createResource = null; + Resource resource = null; + String payloadName = "orig2G.csar"; + String rootPath = System.getProperty("user.dir"); + Path path = Paths.get(rootPath + csarFolderPath + "orig2G.csar"); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setName("TEST01"); + resourceDetails.setCsarUUID("orig2G.csar"); + resourceDetails.setCsarVersion("1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + // create new resource from Csar + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + // update scar with new artifacts + path = Paths.get(rootPath + csarFolderPath + "orig2G_update.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + resourceDetails.setDescription("update"); + resourceDetails.setCsarVersion("2"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + } + + @Test + public void createUpdateImportResourceFromCsarWithArtifactsGroupNamingTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes; + ResourceReqDetails resourceDetails; + RestResponse updateResource; + RestResponse createResource; + Resource resource; + + // back original scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "VF_RI2_G4_withArtifacts_group_naming_a.csar", "VF_RI2_G4_withArtifacts_group_naming.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("TEST01"); + resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts_group_naming.csar"); + resourceDetails.setCsarVersion("1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + // create new resource from Csar + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + List groups = resource.getGroups(); + assertTrue(groups != null && groups.size() == 6); + assertTrue(groups.stream() + .filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) + && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(g.getName()).matches()) + .count() == 0); + // update scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "VF_RI2_G4_withArtifacts_group_naming_delete_update.csar", "VF_RI2_G4_withArtifacts_group_naming.csar"); + BaseRestUtils.checkSuccess(copyRes); + resourceDetails.setDescription("BLA BLA BLA"); + resourceDetails.setCsarVersion("2"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + groups = resource.getGroups(); + assertTrue(groups != null && groups.size() == 5); + // back original scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "VF_RI2_G4_withArtifacts_group_naming_a.csar", "VF_RI2_G4_withArtifacts_group_naming.csar"); + BaseRestUtils.checkSuccess(copyRes); + resourceDetails.setDescription("BLA BLA BLA"); + resourceDetails.setCsarVersion("3"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + groups = resource.getGroups(); + assertTrue(groups != null && groups.size() == 6); + assertTrue(groups.stream() + .filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) + && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(g.getName()).matches()) + .count() == 0); + } + + @Test + public void createUpdateDeleteAllRequiredArtifactsTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes; + ResourceReqDetails resourceDetails; + RestResponse updateResource; + RestResponse createResource; + Resource resource; + String artifactName = "heatnested7"; + + ImportReqDetails resourceDetails0 = ElementFactory.getDefaultImportResource(); + createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, resourceDetails0); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + + // back original scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig2GV001_a.csar", "orig2GV001.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("TEST01"); + resourceDetails.setCsarUUID("orig2GV001.csar"); + resourceDetails.setCsarVersion("1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + // create new resource from Csar + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 2); + List groups = resource.getGroups(); + // update scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "orig2GV006-remove-all-nested-artifacts.csar", "orig2GV001.csar"); + BaseRestUtils.checkSuccess(copyRes); + resourceDetails.setDescription("BLA BLA BLA"); + resourceDetails.setCsarVersion("2"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 0); + groups = resource.getGroups(); + // back original scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig2GV001_a.csar", "orig2GV001.csar"); + BaseRestUtils.checkSuccess(copyRes); + } + + // First create from orig2GV006-remove-all-nested-artifacts.csar (without + // requiredArtifact) + // Submit for testing + // Login as tester -> Certification + // Login as designer + // then update to orig2GV008-change-nested-oam-fileContent.csar (with + // requiredArtifact) + // Expected: requiredArtifact: ["hot-nimbus-psm_v1.0.yaml", + // "hot-nimbus-swift-container_v1.0.yaml"] + // Actual: no requiredArtifact + @Test + public void createUpdateAddRequiredArtifactsTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse copyRes; + ResourceReqDetails resourceDetails; + RestResponse updateResource; + RestResponse createResource; + Resource resource; + String artifactName = "heatnested7"; + + ImportReqDetails resourceDetails0 = ElementFactory.getDefaultImportResource(); + createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, resourceDetails0); + BaseRestUtils.checkCreateResponse(createResource); + createResource = LifecycleRestUtils.certifyResource(resourceDetails0); + BaseRestUtils.checkSuccess(createResource); + + // back original scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "orig2GV006-remove-all-nested-artifacts.csar", "orig2GV001.csar"); + BaseRestUtils.checkSuccess(copyRes); + + resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("TEST01"); + resourceDetails.setCsarUUID("orig2GV001.csar"); + resourceDetails.setCsarVersion("1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + // create new resource from Csar + createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + createResource = LifecycleRestUtils.certifyResource(resourceDetails); + BaseRestUtils.checkSuccess(createResource); + + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 0); + List groups = resource.getGroups(); + // update scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, + "orig2GV008-change-nested-oam-fileContent.csar", "orig2GV001.csar"); + BaseRestUtils.checkSuccess(copyRes); + resourceDetails.setDescription("BLA BLA BLA"); + resourceDetails.setCsarVersion("2"); + updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(updateResource); + resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class); + assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 2); + groups = resource.getGroups(); + // back original scar + copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig2GV001_a.csar", "orig2GV001.csar"); + BaseRestUtils.checkSuccess(copyRes); + } + + private RestResponse importUserDefinedNodeType(String payloadName, User sdncModifierDetails, + ImportReqDetails resourceDetails) throws Exception { + + Path path = Paths.get(rootPath + csarFolderPath + payloadName); + byte[] data = Files.readAllBytes(path); + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(ResourceTypeEnum.VFC.name()); + return ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java new file mode 100644 index 0000000000..345b81eb3e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java @@ -0,0 +1,225 @@ +/*- + * ============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.ci.tests.execute.inputs; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.InputDefinition; +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.ServiceReqDetails; +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; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.InputsRestUtils; +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.BaseValidationUtils; +import org.testng.annotations.Test; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import fj.data.Either; + +/** + * CI-Tests for inputs + * @author il0695 + * + */ +public class InputsApiTests extends ComponentBaseTest { + + private static String inputCsar1 = "FCGI_with_inputs.csar"; + private static String inputCsar2 = "LDSA1_with_inputs.csar"; + private static User sdncDesignerDetails = null; + + @Rule + public static TestName name = new TestName(); + + /** + * Constructor + */ + public InputsApiTests() { + super(name, InputsApiTests.class.getName()); + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + } + + /** + * Create VF with inputs from CSAR file + * + * @throws Exception + */ + @Test + public void testCreateResourceInstanceWithInputsFromCsar() throws Exception { + Resource vf = AtomicOperationUtils.importResourceFromCSAR(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, inputCsar1); + assertTrue("Success creating VF from CSAR", !vf.getInputs().isEmpty()); + } + + /** + * Create service and add to it VF instance with inputs + * + * @throws Exception + */ + @Test + public void testAddVfInstanceWithInputsToService() throws Exception { + createServiceWithVFInstanceWithInputs(); + } + + /** + * General test to check most functionality of inputs + *
    + *
  • Create service with VF instance that has inputs)
  • + *
  • Get all inputs of VF instance
  • + *
  • Add inputs to service
  • + *
  • Get service inputs
  • + *
  • Delete service inputs
  • + *
+ * + * @throws Exception + */ + @Test + public void testInputsMainFunctionality() throws Exception { + Service service = createServiceWithVFInstanceWithInputs(); + int totalInputsBeforeAdd = service.getInputs().size(); + + // Get component instances + RestResponse getInstancesResponse = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE, service.getUniqueId(), sdncDesignerDetails); + BaseValidationUtils.checkSuccess(getInstancesResponse); + List serviceInstances = new Gson().fromJson(getInstancesResponse.getResponse(), new TypeToken>(){}.getType()); + + // Get all inputs of first instance + ComponentInstance vfInstance = serviceInstances.get(0); + RestResponse getComponentInstanceInputsResponse = InputsRestUtils.getComponentInstanceInputs(service, vfInstance); + BaseValidationUtils.checkSuccess(getComponentInstanceInputsResponse); + List instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken>(){}.getType()); + + // Take only the 2 first inputs + List inputsToAdd = instanceInputs.stream().limit(2).collect(Collectors.toList()); + + // Build component instances input map to add to server + ComponentInstInputsMap buildComponentInstInputsMap = buildComponentInstInputsMap(vfInstance.getUniqueId(), inputsToAdd); + RestResponse addInputResponse = InputsRestUtils.addInput(service, buildComponentInstInputsMap, UserRoleEnum.DESIGNER); + BaseValidationUtils.checkSuccess(addInputResponse); + + // Get service inputs count + RestResponse getComponentInputsResponse = InputsRestUtils.getComponentInputs(service); + BaseValidationUtils.checkSuccess(getComponentInputsResponse); + List serviceInputsAfterAdd = new Gson().fromJson(getComponentInputsResponse.getResponse(), new TypeToken>(){}.getType()); + if (serviceInputsAfterAdd.size()-totalInputsBeforeAdd!=2) { + assertTrue("Error adding inputs to service (service should have 2 inputs)", false); + } + + // Delete 1 input from service + RestResponse deleteInputFromComponentResponse = InputsRestUtils.deleteInputFromComponent(service, serviceInputsAfterAdd.get(0).getUniqueId()); + BaseValidationUtils.checkSuccess(deleteInputFromComponentResponse); + + // Get service inputs count after delete + RestResponse getComponentInputsResponseAfterDelete = InputsRestUtils.getComponentInputs(service); + BaseValidationUtils.checkSuccess(getComponentInputsResponseAfterDelete); + List serviceInputsAfterDelete = new Gson().fromJson(getComponentInputsResponseAfterDelete.getResponse(), new TypeToken>(){}.getType()); + if (serviceInputsAfterDelete.size()-totalInputsBeforeAdd!=1) { + assertTrue("Error deleting inputs from service (service should have 1 input)", false); + } + + assertTrue("Success testing inputs main functionality", true); + } + + /** + * Private method to create service with VF instance that has inputs + * This is private method to be used by multiple tests + * + * @return {@link org.openecomp.sdc.be.model} + * @throws Exception + * @throws IOException + */ + private Service createServiceWithVFInstanceWithInputs() throws Exception, IOException { + // Create default service + Either createDefaultServiceEither = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + if (createDefaultServiceEither.isRight()){ + assertTrue("Error creating default service", false); + } + Service service = createDefaultServiceEither.left().value(); + + // Create VF from CSAR file + Resource vfWithInputs = AtomicOperationUtils.importResourceFromCSAR(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, inputCsar2); + + // Certify VF + Pair changeComponentState = AtomicOperationUtils.changeComponentState(vfWithInputs, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + // Add VF instance to service + Either addComponentInstanceToComponentContainerEither = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfWithInputs, service, UserRoleEnum.DESIGNER, true); + if (addComponentInstanceToComponentContainerEither.isRight()){ + assertTrue("Error adding VF to service", false); + } + + // Get service response + ServiceReqDetails serviceDetails = new ServiceReqDetails(service); + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + + // Get VF instance from service + ComponentInstance vfInstance = service.getComponentInstances().get(0); + if (vfInstance!=null){ + assertTrue("Success creating service with VF instance", true); + } else { + assertTrue("Error creating service with VF instance", false); + } + return service; + } + + /** + * Return default ComponentInstInputsMap + * + * @param addToInput + * @param inputs + * @return {@link org.openecomp.sdc.be.model.ComponentInstInputsMap} + */ + private ComponentInstInputsMap buildComponentInstInputsMap (String addToInput, List inputs) { + Map> map = new HashMap<>(); + map.put(addToInput, inputs); + ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap(); + componentInstInputsMap.setComponentInstanceInputsMap(map); + return componentInstInputsMap; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java new file mode 100644 index 0000000000..e15652dddf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java @@ -0,0 +1,274 @@ +/*- + * ============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.ci.tests.execute.lifecycle; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.NormativeTypesEnum; +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.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +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.ComponentInstanceRestUtils; +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.annotations.BeforeMethod; + +/** + * + * @author al714h + * + * resourceDetails - create, Add Heat, certify resourceDetails1 - create + * resource, LCS - CheckOut serviceDetails - create, add RI from + * resourceDetails serviceDetails2 - create, add RI from resourceDetails + * serviceDetailsEmpty - create, LCS - CheckOut serviceDetailsEmpty2 - + * create, LCS - CheckOut + * + */ +public abstract class LCSbaseTest extends ComponentBaseTest { + + protected ResourceReqDetails resourceDetails; + protected ResourceReqDetails resourceDetails1; + protected ServiceReqDetails serviceDetails; + protected ServiceReqDetails serviceDetails2; + protected ServiceReqDetails serviceDetailsEmpty; + protected ServiceReqDetails serviceDetailsEmpty2; + protected ComponentInstanceReqDetails componentInstanceReqDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails2; + protected User sdncDesignerDetails1; + protected User sdncDesignerDetails2; + protected static User sdncTesterDeatails1; + protected User sdncAdminDetails1; + protected ArtifactReqDetails heatArtifactDetails; + protected ArtifactReqDetails heatVolArtifactDetails; + protected ArtifactReqDetails heatNetArtifactDetails; + + protected ArtifactReqDetails defaultArtifactDetails; + protected ResourceUtils resourceUtils; + protected ArtifactUtils artifactUtils; + + // protected static ServiceUtils serviceUtils = new ServiceUtils(); + public LCSbaseTest(TestName testName, String className) { + super(testName, className); + } + + @BeforeMethod + public void before() throws Exception { + + initializeMembers(); + + createComponents(); + + } + + public void initializeMembers() throws IOException, Exception { + resourceDetails = ElementFactory.getDefaultResource(); + // resourceDetails = + // ElementFactory.getDefaultResource("myNewResource1234567890", + // NormativeTypesEnum.ROOT, ResourceServiceCategoriesEnum.ROUTERS, + // UserRoleEnum.DESIGNER.getUserId()); + resourceDetails1 = ElementFactory.getDefaultResource("secondResource", NormativeTypesEnum.ROOT); + serviceDetails = ElementFactory.getDefaultService(); + serviceDetails2 = ElementFactory.getDefaultService("newTestService2", ServiceCategoriesEnum.MOBILITY, "al1976"); + serviceDetailsEmpty = ElementFactory.getDefaultService("newEmptyService", ServiceCategoriesEnum.MOBILITY, + "al1976"); + serviceDetailsEmpty2 = ElementFactory.getDefaultService("newEmptyService2", ServiceCategoriesEnum.MOBILITY, + "al1976"); + sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2); + sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + heatNetArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType()); + heatVolArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_VOL.getType()); + componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + resourceInstanceReqDetails2 = ElementFactory.getDefaultComponentInstance(); + + } + + protected void createComponents() throws Exception { + + RestResponse response = ResourceRestUtils.createResource(resourceDetails1, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetails1.getUniqueId()); + + response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId()); + + response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId()); + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, + resourceDetails.getUniqueId()); + assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + // certified resource + response = LCSbaseTest.certifyResource(resourceDetails, sdncDesignerDetails1); + assertTrue("certify resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + // add resource instance with HEAT deployment artifact to the service + componentInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(componentInstanceReqDetails, sdncDesignerDetails1, + serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201); + + response = ServiceRestUtils.createService(serviceDetails2, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("service uniqueId is null:", serviceDetails2.getUniqueId()); + + componentInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(componentInstanceReqDetails, sdncDesignerDetails1, + serviceDetails2.getUniqueId(), ComponentTypeEnum.SERVICE); + assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201); + + response = ServiceRestUtils.createService(serviceDetailsEmpty, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("service uniqueId is null:", serviceDetailsEmpty.getUniqueId()); + + response = ServiceRestUtils.createService(serviceDetailsEmpty2, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("service uniqueId is null:", serviceDetailsEmpty2.getUniqueId()); + + DbUtils.cleanAllAudits(); + + } + + public static RestResponse certifyResource(ResourceReqDetails resourceDetails, User user) throws Exception { + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user.getUserId(), + LifeCycleStatesEnum.CHECKIN); + // if (restResponseResource.getErrorCode() == 200){ + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user.getUserId(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // }else + // return restResponseResource; + sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + sdncTesterDeatails1.getUserId(), LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponseResource; + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + sdncTesterDeatails1.getUserId(), LifeCycleStatesEnum.CERTIFY); + } + return restResponseResource; + } + + public static RestResponse certifyService(ServiceReqDetails serviceDetails, User user) throws Exception { + RestResponse restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, user, + LifeCycleStatesEnum.CHECKIN); + // if (restResponseService.getErrorCode() == 200){ + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, user, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // }else + // return restResponseService; + + sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + if (restResponseService.getErrorCode() == 200) { + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDeatails1, + LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponseService; + if (restResponseService.getErrorCode() == 200) { + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDeatails1, + LifeCycleStatesEnum.CERTIFY); + } + return restResponseService; + } + + protected static RestResponse raiseResourceToTargetVersion(ResourceReqDetails resourceDetails, String targetVersion, + User user) throws Exception { + return raiseResourceToTargetVersion(resourceDetails, targetVersion, null, user); + } + + protected static RestResponse raiseResourceToTargetVersion(ResourceReqDetails resourceDetails, String targetVersion, + RestResponse prevResponse, User user) throws Exception { + + String[] splitParts = targetVersion.split("\\."); + + int version = Integer.parseInt(splitParts[1]); + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + + if (prevResponse != null) { + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(prevResponse.getResponse()); + if (resourceRespJavaObject.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) { + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + user.getUserId(), LifeCycleStatesEnum.CHECKOUT); + } + } + + RestResponse restResponseResource = null; + for (int i = 0; i < (version - 1); i++) { + + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, null, + LifeCycleStatesEnum.CHECKIN, checkinComentJson); + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user.getUserId(), + LifeCycleStatesEnum.CHECKOUT); + if (restResponseResource.getErrorCode() == 200) { + + } else + break; + + } else + break; + + } + + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, null, + LifeCycleStatesEnum.CHECKIN, checkinComentJson); + assertEquals("Check response code ", 200, restResponseResource.getErrorCode().intValue()); + return restResponseResource; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java new file mode 100644 index 0000000000..6a4fa3ba55 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java @@ -0,0 +1,1478 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS_DELETE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +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.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class ChangeServiceInstanceVersionTest extends ComponentInstanceBaseTest { + + protected ArtifactReqDetails heatArtifactDetails; + public String firstVfInstanceUniqueId; + public String firstVfInstanceName; + public String secondVfInstanceUniqueId; + public String secoundVfInstanceName; + public String serviceInstanceToReplaceUniqueId; + public String expectedServiceName; + public String expectedPosX; + public String expectedPosY; + public String actualServiceInstanceName; + public String actualPosX; + public String actualPosY; + + @Rule + public static TestName name = new TestName(); + + public ChangeServiceInstanceVersionTest() { + super(name, ChangeServiceInstanceVersionTest.class.getName()); + } + + @BeforeMethod + public void before() throws Exception { + firstVfInstanceName = null; + secoundVfInstanceName = null; + firstVfInstanceUniqueId = null; + secondVfInstanceUniqueId = null; + serviceInstanceToReplaceUniqueId = null; + expectedServiceName = null; + expectedPosX = null; + expectedPosY = null; + actualServiceInstanceName = null; + actualPosX = null; + actualPosY = null; + init(); + createComponents(); + } + + private void createComponents() throws Exception { + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + createAtomicResource(resourceDetailsVFC_01); + changeResourceStateToCertified(resourceDetailsVFC_01); + createAtomicResource(resourceDetailsCP_01); + changeResourceStateToCertified(resourceDetailsCP_01); + createAtomicResource(resourceDetailsVL_01); + changeResourceStateToCertified(resourceDetailsVL_01); + createAtomicResource(resourceDetailsVFC_02); + changeResourceStateToCertified(resourceDetailsVFC_02); + createAtomicResource(resourceDetailsCP_02); + changeResourceStateToCertified(resourceDetailsCP_02); + createAtomicResource(resourceDetailsVL_02); + changeResourceStateToCertified(resourceDetailsVL_02); + createVF(resourceDetailsVF_02); + createVF(resourceDetailsVF_01); + // create check-In services + createService(serviceDetails_01); + createService(serviceDetails_02); + createService(serviceDetails_03); + createProduct(productDetails_01); + createProduct(productDetails_02); + + // add resourceDetailsCP_01 ,resourceDetailsVFC_01 and + // resourceDetailsCP_01 to resourceDetailsVF_01 and certify + // resourceDetailsVF_01 + certifyVf(resourceDetailsVF_01, resourceDetailsVFC_02, resourceDetailsCP_01); + // add resourceDetailsCP_02 ,resourceDetailsVFC_02 and + // resourceDetailsVL_02 to resourceDetailsVF_02 and certify + // resourceDetailsVF_02 + certifyVf(resourceDetailsVF_02, resourceDetailsVFC_02, resourceDetailsCP_02); + RestResponse createVFInstanceResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); // serviceDetails_01 has certified + // resourceDetailsVF_01 + firstVfInstanceName = ResponseParser.getNameFromResponse(createVFInstanceResponse); + createVFInstanceResponse = createVFInstanceDuringSetup(serviceDetails_02, resourceDetailsVF_02, + sdncDesignerDetails); // serviceDetails_01 has certified + // resourceDetailsVF_02 + secoundVfInstanceName = ResponseParser.getUniqueIdFromResponse(createVFInstanceResponse); + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + } + + @Test + public void changeServiceInstanceVersionByPm() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // get the new VF instance uniqueId after checkout service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + @Test + public void changeServiceInstanceVersionByAdmin() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // get the new VF instance uniqueId after checkout service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // service [0.2] state to CERTIFICATIONREQUEST + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ResourceRestUtils.checkSuccess(changeStatusResponse); + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncAdminDetails, ComponentTypeEnum.PRODUCT, + true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + @Test + public void changeServiceInstanceToOlderVersion() throws Exception { + // Get VF Instance UniquId [Service version 0.1] + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + ComponentInstance actualComponentInstance = service.getComponentInstances().get(0); + firstVfInstanceUniqueId = actualComponentInstance.getUniqueId(); + String serviceOlderVersionUniquId = ResponseParser.getUniqueIdFromResponse(getServiceResponse); + + // Checkout service [0.2] + RestResponse changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, + sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // get the new VF instance uniqueId after checkout service + getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // Adding service instance (serviceDetails_01 V0.2) to product without + // saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to Older version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceOlderVersionUniquId, sdncPmDetails1, ComponentTypeEnum.PRODUCT, + true); + // RestResponse changeServiceInstanceVersionResponse = + // changeServiceInstanceVersion(productDetails_01.getUniqueId(), + // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid, + // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + // DE190201 + @Test + public void changeServiceInstanceVersionToCertifiedVersion() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + /* + * String serviceNewUniqueUid = + * ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + * serviceDetails_01.setUniqueId(serviceNewUniqueUid); + */ + // get the new VF instance uniqueId after checkout service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ResourceRestUtils.checkSuccess(changeStatusResponse); + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + ResourceRestUtils.checkSuccess(changeStatusResponse); + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.CERTIFY); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + // RestResponse changeServiceInstanceVersionResponse = + // changeServiceInstanceVersion(productDetails_01.getUniqueId(), + // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid, + // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + // DE191927 + @Test(enabled = false) + public void changeServiceInstanceVersionThenReCheckInProduct() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // get the new VF instance uniqueId after checkout service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + ///////////////////// + productOldUniqueId = productDetails_01.getUniqueId(); + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + ///////////////////////////////////////////// + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + @Test + public void changeServiceInstanceToHisVersion() throws Exception { + // Get VF Instance UniquId [Service version 0.1] + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + String serviceOlderVersionUniquId = ResponseParser.getUniqueIdFromResponse(getServiceResponse); + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // get the new VF instance uniqueId after checkout service + getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceOlderVersionUniquId, sdncPmDetails1, ComponentTypeEnum.PRODUCT, + true); + // RestResponse changeServiceInstanceVersionResponse = + // changeServiceInstanceVersion(productDetails_01.getUniqueId(), + // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid, + // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + @Test + public void changeServiceInstanceVersionByAdminNotByProductOwner() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncAdminDetails, ComponentTypeEnum.PRODUCT, + true); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + + } + + @Test + public void changeServiceInstanceVersionByPmNotByProductOwner() throws Exception { + // Adding service instance (serviceDetails_01) to product AND ---> + // saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // change uniqueId after product check-out in expected Req&Cap + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + updateNewComponentInstanceId(createServiceInstanceResp, productNewUniqueId); + // CHANGE Service Instance VERSION BY NON PRODUCT OWNER (sdncPmDetails1 + // instead sdncPmDetails1) + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion( + productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails2, + ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void changeServiceInstanceVersionByTester() throws Exception { + // Adding service instance (serviceDetails_01) to product AND ---> + // saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // change uniqueId after product check-out in expected Req&Cap + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // CHANGE Service Instance VERSION BY NON PRODUCT OWNER (sdncPmDetails1 + // instead sdncPmDetails1) + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion( + productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, + sdncTesterDetails, ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void changeServiceInstanceVersionProductIsNotCheckOut() throws Exception { + // Adding service instance (serviceDetails_01) to product AND ---> + // saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // CHANGE Service Instance VERSION for Non checkedOut product + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productOldUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeServiceInstanceVersionResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + // DE191727 + @Test(enabled = false) + public void changeServiceInstanceVersionServiceIsInCheckOutState() throws Exception { + // Adding service instance (serviceDetails_01) to product AND ---> + // saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // change uniqueId after product check-out in expected Req&Cap + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // CHANGE Service Instance VERSION to service in checkOut state + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion( + productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, + ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(serviceNewUniqueUid); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + + } + + @Test + public void changeServiceInstanceVersionServiceInstanceDoesNotExist() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // change service instance to newer version + String serviceUniqueUidNotExist = "1234567890"; + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceUniqueUidNotExist, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(serviceUniqueUidNotExist); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name(), varibales, + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + // DE189392 + @Test(enabled = false) + public void changeServiceInstanceNonExistingProduct() throws Exception { + // Adding service instance (serviceDetails_01) to product saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // change service instance to newer version - Non existing Product + String productNewUniqueIdNotExist = "1234567890"; + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueIdNotExist, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(productNewUniqueIdNotExist); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name(), varibales, + changeServiceInstanceVersionResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void changeServiceInstanceVersionToNonExisitingServiceVersion() throws Exception { + // Adding service instance (serviceDetails_01) to product saving Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + updateNewComponentInstanceId(createServiceInstanceResp, productNewUniqueId); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // change service instance to Non-existing version + String serviceUniqueUidNotExist = "1234567890"; + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceUniqueUidNotExist, sdncPmDetails1, ComponentTypeEnum.PRODUCT, + true); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(serviceUniqueUidNotExist); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), varibales, + changeServiceInstanceVersionResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void changeServiceInstanceComponentTypeIsNotProduct() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version for NON-Component Type = + // Product (e.g. service) + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.SERVICE, true); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, + changeServiceInstanceVersionResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void changeServiceInstanceComponentTypeNotSupported() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version for NON-Component Type = + // Product (e.g. service) + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, + ComponentTypeEnum.SERVICE_INSTANCE, true); + assertEquals("Check response code ", STATUS_CODE_UNSUPPORTED_ERROR, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("null"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, + changeServiceInstanceVersionResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void SeveralServiceInstanceFromSameServiceVersionChangeVersionOnlyForOneServiceInstance() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + serviceDetails_01.setUniqueId(serviceNewUniqueUid); + // get the new VF instance uniqueId after checkout service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + List serviceComponentInstances = service.getComponentInstances(); + for (ComponentInstance component : serviceComponentInstances) { + if (component.getName().equals(firstVfInstanceName)) { + firstVfInstanceUniqueId = component.getUniqueId(); + } + } + assertTrue(firstVfInstanceUniqueId != null); + // delete resource instance (resourceDetailsVF_01) from Service + RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId, + serviceDetails_01, sdncDesignerDetails); + assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Add different VF instance (resourceDetailsVF_02) to Service + RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(restResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get service instance new uniqueId , name and position after checkout + // product + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true); + ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse); + actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse); + actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posX"); + actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(), + "posY"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Verify that Service instance name and position didn't change after + // changing service instance version + assertTrue(actualServiceInstanceName.equals(expectedServiceName)); + assertTrue(actualPosX.equals(expectedPosX)); + assertTrue(actualPosY.equals(expectedPosY)); + } + + @Test + public void changeServiceInstanceVersionByNonAsdcUser() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + nonAsdcUser.setUserId("bt760h"); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, nonAsdcUser, ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void changeServiceInstanceVersionEmptyUserId() throws Exception { + // Adding service instance (serviceDetails_01) to product without saving + // Req&Cap + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, + sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Adding service instance (serviceDetails_02) to product AND ---> Save + // Req&Cap + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // check-in product + RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Checkout service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeStatusResponse); + String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + // Check-In service [0.2] + changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeStatusResponse); + // check-out product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeStatusResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + nonAsdcUser.setUserId(""); + // change service instance to newer version + RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId, + serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, nonAsdcUser, ComponentTypeEnum.PRODUCT, true); + assertEquals("Check response code ", STATUS_CODE_MISSING_INFORMATION, + changeServiceInstanceVersionResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), + changeServiceInstanceVersionResponse.getResponse()); + // Check-in product + changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeStatusResponse); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + //////////////////////////////////// + private void updateNewComponentInstanceId(RestResponse createServiceInstanceResp, String productNewUniqueId) + throws Exception { + String firstServiceInstanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId()); + Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class); + List componentInstances = product.getComponentInstances(); + for (ComponentInstance component : componentInstances) { + if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) { + serviceInstanceToReplaceUniqueId = component.getUniqueId(); + expectedServiceName = component.getName(); + expectedPosX = component.getPosX(); + expectedPosY = component.getPosY(); + } + } + assertTrue(serviceInstanceToReplaceUniqueId != null); + } + + private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponse; + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, + LifeCycleStatesEnum.CERTIFY); + if (restResponse.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponse); + resourceDetails.setVersion(newVersion); + resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); + resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), + "uniqueId"); + resourceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponse; + } + + private void certifyVf(ResourceReqDetails resource, ResourceReqDetails computeResource, + ResourceReqDetails cpResource) throws Exception { + RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, cpResource, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, computeResource, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, + sdncDesignerDetails, resource.getUniqueId()); + ResourceRestUtils.checkSuccess(response); + + String capOwnerId = toCompInstId; + User user = sdncDesignerDetails; + ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE; + + fulfillCpRequirement(resource, fromCompInstId, toCompInstId, capOwnerId, user, containerCompType); + + RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource); + ResourceRestUtils.checkSuccess(changeResourceStateToCertified); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java new file mode 100644 index 0000000000..623b29b8e6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java @@ -0,0 +1,200 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.annotations.BeforeMethod; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +public abstract class ProductBaseTest extends ComponentBaseTest { + User productStrategistUser1; + User productStrategistUser2; + User productStrategistUser3; + User productManager1; + User productManager2; + User adminUser; + User designerUser; + + // Category1->Subcategory1->Grouping1 + protected List defaultCategories; + + protected static String auditAction; + protected static ComponentOperationEnum operation; + + public ProductBaseTest(TestName testName, String className) { + super(testName, className); + } + + @BeforeMethod + public void beforeProductTest() throws IOException, Exception { + productStrategistUser1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + productStrategistUser2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2); + productStrategistUser3 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST3); + productManager1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + productManager2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2); + adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + createDefaultChain(); + } + + private void createDefaultChain() throws Exception { + CategoryDefinition productCategoryDefinition = ElementFactory.getDefaultCategory(); + SubCategoryDefinition productSubCategoryDefinition = ElementFactory.getDefaultSubCategory(); + GroupingDefinition productGroupingDefinition = ElementFactory.getDefaultGroup(); + productCategoryDefinition.addSubCategory(productSubCategoryDefinition); + productSubCategoryDefinition.addGrouping(productGroupingDefinition); + List definitionsList = new ArrayList<>(); + definitionsList.add(productCategoryDefinition); + defaultCategories = createCategoriesChain(definitionsList); + } + + private List createCategoriesChain(List categoryDefinitions) + throws Exception { + for (CategoryDefinition categoryDefinition : categoryDefinitions) { + RestResponse createCategory = CategoryRestUtils.createCategory(categoryDefinition, productStrategistUser1, + PRODUCT_COMPONENT_TYPE); + int status = createCategory.getErrorCode().intValue(); + if (status == BaseRestUtils.STATUS_CODE_CREATED) { + String categoryId = ResponseParser.getUniqueIdFromResponse(createCategory); + categoryDefinition.setUniqueId(categoryId); + } + List subcategories = categoryDefinition.getSubcategories(); + for (SubCategoryDefinition subCategoryDefinition : subcategories) { + RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryDefinition, + categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE); + status = createSubCategory.getErrorCode().intValue(); + if (status == BaseRestUtils.STATUS_CODE_CREATED) { + String subCategoryId = ResponseParser.getUniqueIdFromResponse(createSubCategory); + subCategoryDefinition.setUniqueId(subCategoryId); + } + List groupings = subCategoryDefinition.getGroupings(); + for (GroupingDefinition groupingDefinition : groupings) { + RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition, + subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE); + status = createGroupingRest.getErrorCode().intValue(); + if (status == BaseRestUtils.STATUS_CODE_CREATED) { + String groupingId = ResponseParser.getUniqueIdFromResponse(createGroupingRest); + groupingDefinition.setUniqueId(groupingId); + } + } + } + } + RestResponse allCategories = CategoryRestUtils.getAllCategories(productStrategistUser1, PRODUCT_COMPONENT_TYPE); + Gson gson = new Gson(); + List res = gson.fromJson(allCategories.getResponse(), + new TypeToken>() { + }.getType()); + return res; + } + + // Category1->Subcategory1->[Grouping1, Grouping11] + protected List addSecondGroupingToDefaultCategory() throws Exception { + GroupingDefinition productGroupingDefinition = ElementFactory.getDefaultGroup(); + productGroupingDefinition.setName("Grouping11"); + defaultCategories.get(0).getSubcategories().get(0).addGrouping(productGroupingDefinition); + return createCategoriesChain(defaultCategories); + } + + // Category1->[Subcategory1->[Grouping1, + // Grouping11],Subcategory2->[Grouping12]] + protected List addSubcategoryAndGroupingToDefaultCategory() throws Exception { + GroupingDefinition groupingDefinition1 = ElementFactory.getDefaultGroup(); + groupingDefinition1.setName("Grouping11"); + defaultCategories.get(0).getSubcategories().get(0).addGrouping(groupingDefinition1); + + SubCategoryDefinition subCategory2 = ElementFactory.getDefaultSubCategory(); + subCategory2.setName("Subcategory2"); + GroupingDefinition groupingDefinition2 = ElementFactory.getDefaultGroup(); + groupingDefinition2.setName("Grouping12"); + subCategory2.addGrouping(groupingDefinition2); + defaultCategories.get(0).addSubCategory(subCategory2); + return createCategoriesChain(defaultCategories); + } + + // [Category1->[Subcategory1->[Grouping1, + // Grouping11],Subcategory2->[Grouping12]], + // Category2->[Subcategory1->[Grouping1],Subcategory2->[Grouping1]], + // Category3->[Subcategory1->[Grouping11],Subcategory2->[Grouping11, + // Grouping22]]] + protected List addManyGroupingsDiffCategories() throws Exception { + CategoryDefinition category2 = ElementFactory.getDefaultCategory(); + category2.setName("Category2"); + CategoryDefinition category3 = ElementFactory.getDefaultCategory(); + category3.setName("Category3"); + SubCategoryDefinition subCategory1 = ElementFactory.getDefaultSubCategory(); + subCategory1.setName("Subcategory1"); + SubCategoryDefinition subCategory2 = ElementFactory.getDefaultSubCategory(); + subCategory2.setName("Subcategory2"); + SubCategoryDefinition subCategory1_2 = ElementFactory.getDefaultSubCategory(); + subCategory1_2.setName("Subcategory1"); + SubCategoryDefinition subCategory2_2 = ElementFactory.getDefaultSubCategory(); + subCategory2_2.setName("Subcategory2"); + SubCategoryDefinition subCategory1_3 = ElementFactory.getDefaultSubCategory(); + subCategory1_3.setName("Subcategory1"); + SubCategoryDefinition subCategory2_3 = ElementFactory.getDefaultSubCategory(); + subCategory2_3.setName("Subcategory2"); + + GroupingDefinition groupingDefinition1 = ElementFactory.getDefaultGroup(); + groupingDefinition1.setName("Grouping1"); + GroupingDefinition groupingDefinition11 = ElementFactory.getDefaultGroup(); + groupingDefinition11.setName("Grouping11"); + GroupingDefinition groupingDefinition12 = ElementFactory.getDefaultGroup(); + groupingDefinition12.setName("Grouping12"); + GroupingDefinition groupingDefinition22 = ElementFactory.getDefaultGroup(); + groupingDefinition22.setName("Grouping22"); + + defaultCategories.get(0).getSubcategories().get(0).addGrouping(groupingDefinition11); + subCategory2.addGrouping(groupingDefinition12); + defaultCategories.get(0).addSubCategory(subCategory2); + + defaultCategories.add(category2); + defaultCategories.add(category3); + category2.addSubCategory(subCategory1_2); + category2.addSubCategory(subCategory2_2); + subCategory1_2.addGrouping(groupingDefinition1); + subCategory2_2.addGrouping(groupingDefinition1); + category3.addSubCategory(subCategory1_3); + category3.addSubCategory(subCategory2_3); + subCategory1_3.addGrouping(groupingDefinition11); + subCategory2_3.addGrouping(groupingDefinition11); + subCategory2_3.addGrouping(groupingDefinition22); + return createCategoriesChain(defaultCategories); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java new file mode 100644 index 0000000000..1820315841 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java @@ -0,0 +1,199 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.testng.AssertJUnit.assertEquals; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.enums.AuditJsonKeysEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class ProductCheckinTest extends ProductLifecycleTest { + + @Rule + public static TestName name = new TestName(); + + public ProductCheckinTest() { + super(name, ProductCheckinTest.class.getName()); + } + + @BeforeClass + public static void staticInit() { + auditAction = CHECKIN_ACTION; + operation = ComponentOperationEnum.CHANGE_STATE_CHECKIN; + } + + @Test + public void checkInProductByCreator() throws Exception { + + String checkinComment = "good checkin"; + RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN, checkinComment); + assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue()); + Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(checkInResponse.getResponse(), + Product.class); + + expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct, + auditAction, productManager1, ActionStatus.OK, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID()); + expectedProductAudit.setCOMMENT(checkinComment); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT); + } + + @Test + public void checkInProductByPM() throws Exception { + + String checkinComment = "good checkin"; + RestResponse response = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN, checkinComment); + assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue()); + + User checkoutUser = productManager2; + response = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue()); + expectedProduct = ResponseParser.parseToObjectUsingMapper(response.getResponse(), Product.class); + + DbUtils.cleanAllAudits(); + checkinComment = "good checkin no 2"; + response = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKIN, + checkinComment); + assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue()); + + Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(response.getResponse(), Product.class); + + expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + expectedProduct.setVersion("0.2"); + expectedProduct.setLastUpdaterUserId(checkoutUser.getUserId()); + expectedProduct.setLastUpdaterFullName(checkoutUser.getFullName()); + + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct, + auditAction, checkoutUser, ActionStatus.OK, "0.2", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID()); + expectedProductAudit.setCOMMENT(checkinComment); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT); + } + + @Test + public void checkInProductByAdmin() throws Exception { + + String checkinComment = "good checkin"; + RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, adminUser, + LifeCycleStatesEnum.CHECKIN, checkinComment); + assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue()); + Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(checkInResponse.getResponse(), + Product.class); + + expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + expectedProduct.setLastUpdaterUserId(adminUser.getUserId()); + expectedProduct.setLastUpdaterFullName(adminUser.getFullName()); + + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct, + auditAction, adminUser, ActionStatus.OK, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID()); + expectedProductAudit.setCOMMENT(checkinComment); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT); + } + + @Test + public void checkInProductByPMNotOwner() throws Exception { + + RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager2, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 403, checkInResponse.getErrorCode().intValue()); + String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(), + productManager1.getLastName(), productManager1.getUserId() }; + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, productManager2, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, "0.1", "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + expectedProduct.getUUID(), auditParameters); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + @Test + public void checkInProductByPsRoleNotAllowed() throws Exception { + + RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productStrategistUser1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 409, checkInResponse.getErrorCode().intValue()); + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, productStrategistUser1, ActionStatus.RESTRICTED_OPERATION, "0.1", "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + expectedProduct.getUUID()); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + @Test + public void checkInProductNotExist() throws Exception { + String notExisitingUuid = "1234"; + expectedProduct.setUniqueId(notExisitingUuid); + RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 404, checkInResponse.getErrorCode().intValue()); + String[] auditParameters = new String[] { "", "product" }; + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, productManager1, ActionStatus.PRODUCT_NOT_FOUND, Constants.EMPTY_STRING, + Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, auditParameters); + expectedProductAudit.setCURR_STATE(Constants.EMPTY_STRING); + expectedProductAudit.setRESOURCE_NAME(notExisitingUuid); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + @Test + public void checkInProductAlreadyCheckedIn() throws Exception { + RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue()); + DbUtils.cleanAllAudits(); + checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager2, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 409, checkInResponse.getErrorCode().intValue()); + String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(), + productManager1.getLastName(), productManager1.getUserId() }; + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, productManager2, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, "0.1", "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + expectedProduct.getUUID(), auditParameters); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java new file mode 100644 index 0000000000..efb4a15255 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java @@ -0,0 +1,147 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.FileNotFoundException; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class ProductCheckoutTest extends ProductLifecycleTest { + + @Rule + public static TestName name = new TestName(); + + @BeforeClass + public static void staticInit() { + auditAction = CHECKOUT_ACTION; + operation = ComponentOperationEnum.CHANGE_STATE_CHECKOUT; + } + + public ProductCheckoutTest() { + super(name, ProductCheckoutTest.class.getName()); + } + + @Test + public void checkOutProductByPmNotInContacts() throws Exception { + checkOutProductSuccess(productManager2); + } + + @Test + public void checkOutProductByPmInContacts() throws Exception { + checkOutProductSuccess(productManager1); + } + + @Test + public void checkOutProductByAdmin() throws Exception { + checkOutProductSuccess(adminUser); + } + + @Test + public void checkOutProductByPs() throws Exception { + // Changed in 1604 patch - now it's restricted + checkOutProductRestricted(productStrategistUser3); + // checkOutProductSuccess(productStrategistUser3); + } + + @Test + public void checkOutProductByDesignerRoleNotAllowed() throws Exception { + checkOutProductRestricted(designerUser); + } + + @Test + public void checkOutProductAlreadyCheckedOut() throws Exception { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); + Product checkedOutProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + + DbUtils.cleanAllAudits(); + + lcsResponse = LifecycleRestUtils.changeProductState(checkedOutProduct, productManager2, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkin resource", 403, lcsResponse.getErrorCode().intValue()); + String[] auditParameters = new String[] { checkedOutProduct.getName(), "product", productManager1.getFirstName(), productManager1.getLastName(), productManager1.getUserId() }; + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedOutProduct, auditAction, productManager2, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, "0.2", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, checkedOutProduct.getUUID(), auditParameters); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + private void checkOutProductSuccess(User checkoutUser) throws Exception, FileNotFoundException { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); + + // 0.1 is not highest now + RestResponse prevVersionProductResp = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), productStrategistUser1.getUserId()); + Product prevVersionProduct = ResponseParser.parseToObjectUsingMapper(prevVersionProductResp.getResponse(), Product.class); + Boolean falseParam = false; + assertEquals(falseParam, prevVersionProduct.isHighestVersion()); + + Product checkedOutProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + + expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + expectedProduct.setVersion("0.2"); + expectedProduct.setLastUpdaterUserId(checkoutUser.getUserId()); + expectedProduct.setLastUpdaterFullName(checkoutUser.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedOutProduct, operation); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedOutProduct, auditAction, checkoutUser, ActionStatus.OK, "0.1", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, checkedOutProduct.getUUID()); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + private void checkOutProductRestricted(User checkoutUser) throws Exception, FileNotFoundException { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue()); + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkin resource", 409, lcsResponse.getErrorCode().intValue()); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, auditAction, checkoutUser, ActionStatus.RESTRICTED_OPERATION, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, expectedProduct.getUUID()); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java new file mode 100644 index 0000000000..596825875d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java @@ -0,0 +1,1175 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS_DELETE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +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.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.ErrorValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest { + + protected ArtifactReqDetails heatArtifactDetails; + @Rule + public static TestName name = new TestName(); + + public ProductComponentInstanceCRUDTest() { + super(name, ProductComponentInstanceCRUDTest.class.getName()); + } + + @BeforeMethod + public void before() throws Exception { + init(); + createComponents(); + } + + private void createComponents() throws Exception { + + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + createAtomicResource(resourceDetailsVFC_01); + changeResourceStateToCertified(resourceDetailsVFC_01); + createAtomicResource(resourceDetailsCP_01); + changeResourceStateToCertified(resourceDetailsCP_01); + createAtomicResource(resourceDetailsVL_01); + changeResourceStateToCertified(resourceDetailsVL_01); + createAtomicResource(resourceDetailsVFC_02); + changeResourceStateToCertified(resourceDetailsVFC_02); + createAtomicResource(resourceDetailsCP_02); + changeResourceStateToCertified(resourceDetailsCP_02); + createAtomicResource(resourceDetailsVL_02); + changeResourceStateToCertified(resourceDetailsVL_02); + createVF(resourceDetailsVF_02); + createVF(resourceDetailsVF_01); + // create check-In services + createService(serviceDetails_01); + createService(serviceDetails_02); + createService(serviceDetails_03); + createProduct(productDetails_01); + createProduct(productDetails_02); + + // addresourceDetailsCP_02 ,resourceDetailsVFC_02 and + // resourceDetailsVL_02 to resourceDetailsVF_02 check-in VF + RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsCP_02, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVL_02, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + // addresourceDetailsCP_01 ,resourceDetailsVFC_01 and + // resourceDetailsVL_01 to resourceDetailsVF_01 and certify + // resourceDetailsVF_01 + certifyVf(resourceDetailsVF_01); + createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); // serviceDetails_01 + // has + // certified + // VF + createVFInstanceDuringSetup(serviceDetails_02, resourceDetailsVF_02, sdncDesignerDetails); // serviceDetails_02 + // has + // check-in + // VF + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + } + + // pass + @Test + public void createServiceInstanceTest() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + // DE189427 + @Test(enabled = false) + public void createServiceInstanceFromCheckedOutState() throws Exception { + // can't create instance of checked-out component + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceInToAnotherServiceInstance() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String uniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, uniqueIdFromResponse, ComponentTypeEnum.PRODUCT); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_NOT_FOUND); + } + + @Test + public void createSeveralServiceInstanceFromSameServices() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void createSeveralServiceInstanceFromDifferentServices() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void createCertifiedServiceInstance() throws Exception { + changeServiceStateToCertified(serviceDetails_01); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceByPm() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceWithoutVf() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncAdminDetails, "0.1", LifeCycleStatesEnum.CHECKIN); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_02, serviceDetails_03, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_02, 1, 0); + } + + @Test + public void createServiceInstanceByNonProductOwner() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails2); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceByNonAsdcUser() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + ; + nonExistingSdncUser.setUserId("bt1234"); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonExistingSdncUser); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceToNotCheckOutProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + // pass + @Test + public void createServiceInstanceNameIsEmpty() throws Exception { + String expectedServiceInstanceName = serviceDetails_01.getName() + " 1"; + String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1"; + serviceDetails_01.setName(""); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName); + getComponentAndValidateRIs(productDetails_01, 1, 0); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(expectedServiceInstanceName, actualComponentInstance.getName()); + assertEquals((expectedServiceInstancenormalizedName).toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + // pass + @Test + public void createServiceInstanceNameIsNull() throws Exception { + serviceDetails_01.setName(null); + String expectedServiceInstanceName = (serviceDetails_01.getName() != null ? serviceDetails_01.getName() : "resourceInstanceName") + " 1"; + String expectedServiceInstancenormalizedName = (serviceDetails_01.getName() != null ? serviceDetails_01.getName() : "resourceInstanceName") + "1"; + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName); + getComponentAndValidateRIs(productDetails_01, 1, 0); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(expectedServiceInstanceName, actualComponentInstance.getName()); + assertEquals((expectedServiceInstancenormalizedName).toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + @Test(enabled = false) + public void createServiceInstanceToNonExistingProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, "blabla", ComponentTypeEnum.PRODUCT); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, createServiceInstanceResp.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("blabla"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceToNonSupportedComponentType() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.RESOURCE_INSTANCE); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR); + ArrayList varibales = new ArrayList(); + varibales.add("null"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + // pass + @Test + public void createServiceInstancePositionIsEmpty() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + serviceInstanceReqDetails.setPosX(""); + serviceInstanceReqDetails.setPosY(""); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstancePositionIsNull() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + serviceInstanceReqDetails.setPosX(null); + serviceInstanceReqDetails.setPosY(null); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceByDesigner() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncDesignerDetails); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void createServiceInstanceUserIdIsEmpty() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + nonSdncDetails.setUserId(""); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonSdncDetails); + assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), createServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + //// Update Service instance + + @Test + public void updateServiceInstanceNameByPm() throws Exception { + // Check-in Product by PM and Check-out by PM + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + // Create service instance by PM + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "abcD"; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance Name ", newName, instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(newName, actualComponentInstance.getName()); + assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + @Test + public void updateServiceInstanceNewNameAndLocation() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "updaatedName100"; + serviceInstanceReqDetails.setPosX("100"); + serviceInstanceReqDetails.setPosY("100"); + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); + assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); + assertEquals(newName, actualComponentInstance.getName()); + assertEquals(newName.toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + @Test(enabled = false) + public void updateServiceInstanceNameRemoveSpacesFromBiginningAndEnd() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = " Abcd "; + String expectedNewName = " Abcd "; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (expectedNewName).toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance Name ", expectedNewName, instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(expectedNewName, actualComponentInstance.getName()); + assertEquals((expectedNewName).toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + // pass + @Test + public void updateServiceInstanceNameAllowedCharacters() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "cier-TYUIOP_asd_0987654321.Abcd"; + String ExpectedNormalizName = "ciertyuiop_asd_0987654321abcd"; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", ExpectedNormalizName, instanceNormalizedName); + assertEquals("check Resource Instance Name ", newName, instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(newName, actualComponentInstance.getName()); + assertEquals(ExpectedNormalizName, actualComponentInstance.getNormalizedName()); + + } + + @Test + public void updateInstanceNameInvalidCharacters() throws Exception { + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',' }; + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "Abcd1"; + String updateName; + for (int i = 0; i < invalidChars.length; i++) { + updateName = newName + invalidChars[i]; + serviceInstanceReqDetails.setName(updateName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT, updateServiceInstanceResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("Service Instance"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), varibales, updateServiceInstanceResponse.getResponse()); + } + } + + // pass + @Test + public void updateInstanceNameMaxLength() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl12345"; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance Name ", newName, instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(newName, actualComponentInstance.getName()); + assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + @Test + public void updateInstanceNameExceedMaxLength() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String expectedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name"); + String expectedNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName"); + String newName = "Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ciertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456Ahjklzxcvbnmasdfghjkl123456"; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT, updateServiceInstanceResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("Service Instance"); + varibales.add("1024"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), varibales, updateServiceInstanceResponse.getResponse()); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(expectedName, actualComponentInstance.getName()); + assertEquals(expectedNormalizedName, actualComponentInstance.getNormalizedName()); + } + + @Test + public void updateServiceInstanceNameEmpty() throws Exception { + // see US534663 In case a PS/PM removes the current service instance + // name then BE has to generate again the "default" service instance + // name + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = ""; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(instanceName, actualComponentInstance.getName()); + assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName()); + } + + // pass + @Test + public void updateServiceInstanceNameNull() throws Exception { + // see US534663 In case a PS/PM removes the current service instance + // name then BE has to generate again the "default" service instance + // name + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = null; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "1").toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 1"), instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(instanceName, actualComponentInstance.getName()); + assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName()); + } + + @Test + public void updateServiceInstanceCheckedByOtherUser() throws Exception { + // see US534663 In case a PS/PM removes the current service instance + // name then BE has to generate again the "default" service instance + // name + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "blabla"; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails2, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, updateServiceInstanceResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateServiceInstanceResponse.getResponse()); + } + + @Test + public void updateServiceInstance_UserIdIsNonAsdcUser() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "blabla"; + serviceInstanceReqDetails.setName(newName); + User nonSdncUserDetails = new User(); + nonSdncUserDetails.setUserId("bt4567"); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, nonSdncUserDetails, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, updateServiceInstanceResponse.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), updateServiceInstanceResponse.getResponse()); + } + + @Test + public void updateServiceInstanceNameToAlreadyExisting() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String ServiceName1 = ResponseParser.getNameFromResponse(createServiceInstanceResp); + createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // Update service instance2 name to service instance1 + serviceInstanceReqDetails.setName(ServiceName1); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS, updateServiceInstanceResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("Service Instance"); + varibales.add(ServiceName1); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales, updateServiceInstanceResponse.getResponse()); + } + + @Test + public void updateServiceInstanceForNonExistingProduct() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "blabla"; + serviceInstanceReqDetails.setName(newName); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, "blablabla", ComponentTypeEnum.PRODUCT); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, updateServiceInstanceResponse.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, updateServiceInstanceResponse.getResponse()); + + } + + @Test + public void updateNonExistingServiceInstance() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String newName = "blabla"; + serviceInstanceReqDetails.setName(newName); + serviceInstanceReqDetails.setUniqueId("11111111"); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ArrayList varibales = new ArrayList(); + varibales.add(newName); + varibales.add("service instance"); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, updateServiceInstanceResponse.getErrorCode().intValue()); + // need to change ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name() to + // ActionStatus.SERVICE_INSTANCE_NOT_FOUND.name() + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND.name(), varibales, updateServiceInstanceResponse.getResponse()); + } + + @Test + public void updateServiceInstanceLocation() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + serviceInstanceReqDetails.setPosX("50"); + serviceInstanceReqDetails.setPosY("100"); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); + assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); + } + + @Test + public void updateServiceInstanceToNonExistingLocation() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + String nameFromResponse = ResponseParser.getNameFromResponse(createServiceInstanceResp); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + serviceInstanceReqDetails.setPosX("-50"); + serviceInstanceReqDetails.setPosY("-100"); + serviceInstanceReqDetails.setName(nameFromResponse); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); + assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); + assertEquals(nameFromResponse, actualComponentInstance.getName()); + } + + @Test (enabled = false) + public void updateServiceInstanceLocationNameIsEmpty() throws Exception { + String expectedServiceInstanceName = serviceDetails_01.getName() + " 2"; + String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "2"; + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + serviceInstanceReqDetails.setPosX("100"); + serviceInstanceReqDetails.setPosY("200"); + serviceInstanceReqDetails.setName(""); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String nameFromResponse = ResponseParser.getNameFromResponse(updateServiceInstanceResponse); + String postX = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posX"); + String postY = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posY"); + assertEquals(nameFromResponse, expectedServiceInstanceName); + assertEquals(postX, "100"); + assertEquals(postY, "200"); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX()); + assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY()); + assertEquals(nameFromResponse, actualComponentInstance.getName()); + assertEquals(expectedServiceInstancenormalizedName.toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + // pass + @Test + public void updateServiceInstanceNameToProductName() throws Exception { + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_01); + RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // ComponentInstance componentInstance = + // ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), + // ComponentInstance.class); + // addCompInstReqCapToExpected(componentInstance, + // ComponentTypeEnum.PRODUCT); + serviceInstanceReqDetails.setName(productDetails_01.getName()); + RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ResourceRestUtils.checkSuccess(updateServiceInstanceResponse); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "name"); + assertEquals("check Resource Instance normalizedName ", (serviceInstanceReqDetails.getName()).toLowerCase(), instanceNormalizedName); + assertEquals("check Resource Instance Name ", serviceInstanceReqDetails.getName(), instanceName); + // get product and verify that service instanceName is correct + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + assertEquals(serviceInstanceReqDetails.getName(), actualComponentInstance.getName()); + assertEquals((serviceInstanceReqDetails.getName()).toLowerCase(), actualComponentInstance.getNormalizedName()); + } + + //// Delete Service Instance + + @Test + public void deleteAllServiceInstanceFromProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 0, 0); + } + + @Test + public void deleteServiceWhileServiceInstanceExistInProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + // Delete service while service instance of it exist in product + RestResponse deleteServiceResponse = ServiceRestUtils.deleteServiceById(serviceDetails_01.getUniqueId(), sdncDesignerDetails.getUserId()); + assertTrue(deleteServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + // Get product and verify that service instance still exists + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + // ComponentInstance actualComponentInstance = + // actualProduct.getComponentInstances().get(0); + // assertTrue(serviceInstanceUniqueIdFromResponse == + // actualComponentInstance.getUniqueId()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + // pass + @Test + public void deleteServiceInstanceByPm() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void deleteServiceInstanceByPmCreatedByPm() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void deleteServiceInstanceByPmWhichIsCheckedOutByAnotherPm() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails2); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + // DE190189 + @Test + public void deleteServiceInstanceByPmCreatedByPs() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + String productOldUniqueId = productDetails_01.getUniqueId(); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get product and get service instance new uniquId + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPmDetails1.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + String serviceInstanceUniqueId = actualComponentInstance.getUniqueId(); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 0, 0); + } + + // DE190189 + @Test + public void deleteServiceInstanceByAdminCreatedByPs() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + String productOldUniqueId = productDetails_01.getUniqueId(); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse); + updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId); + // get product and get service instance new uniquId + RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncAdminDetails.getUserId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(), Product.class); + ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0); + String serviceInstanceUniqueId = actualComponentInstance.getUniqueId(); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncAdminDetails); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 0, 0); + } + + @Test + public void createAndDeleteServiceInstanceByAdmin() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + // productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncAdminDetails); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void deleteServiceInstanceFromNonCheckOutProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void deleteServiceInstanceByDesigner() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncDesignerDetails); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteServiceInstanceByTester() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncTesterDetails); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteServiceInstanceByPsWhichIsCheckedOutByAnotherPs() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPsDetails2); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + // pass + @Test + public void deleteServiceInstanceByNonAsdcUser() throws Exception { + User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + ; + nonExistingSdncUser.setUserId("bt1234"); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, nonExistingSdncUser); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteServiceInstanceFromNonExistingProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, "1234567890", serviceInstanceUniqueId, ComponentTypeEnum.PRODUCT); + assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND); + ArrayList varibales = new ArrayList(); + varibales.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteNonExistingServiceInstanceFromProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + // String serviceInstanceUniqueId = + // ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), "1234567890123456unExistingServiceInstance", ComponentTypeEnum.PRODUCT); + assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND); + ArrayList varibales = new ArrayList(); + varibales.add("1234567890123456unExistingServiceInstance"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteServiceInstanceFromNonSupportedComponentType() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.RESOURCE_INSTANCE); + assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR); + ArrayList varibales = new ArrayList(); + varibales.add("null"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales, deleteResourceInstanceResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteServiceInstanceComponentTypeIsNotProduct() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1, productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.SERVICE); + assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND); + ArrayList varibales = new ArrayList(); + varibales.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales, deleteResourceInstanceResponse.getResponse()); + getComponentAndValidateRIs(productDetails_01, 2, 0); + } + + @Test + public void deleteServiceInstanceUserIdIsEmpty() throws Exception { + User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + nonSdncDetails.setUserId(""); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, nonSdncDetails); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), deleteServiceInstanceResp.getResponse()); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + @Test + public void deleteCertifiedServiceInstance() throws Exception { + changeServiceStateToCertified(serviceDetails_01); + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01, sdncPmDetails1); + assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE); + getComponentAndValidateRIs(productDetails_01, 1, 0); + } + + //////////////////////////////////// + + private void certifyVf(ResourceReqDetails resource) throws Exception { + RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_02, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String vlCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + // Fixing Vl/Cp req/cap + ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE; + User user = sdncDesignerDetails; + fulfillCpRequirement(resource, cpCompInstId, computeCompInstId, computeCompInstId, user, containerCompType); + consumeVlCapability(resource, cpCompInstId, vlCompInstId, cpCompInstId, user, containerCompType); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails, resource.getUniqueId()); + ResourceRestUtils.checkSuccess(response); + RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource); + ResourceRestUtils.checkSuccess(changeResourceStateToCertified); + } + + private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponse; + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, LifeCycleStatesEnum.CERTIFY); + if (restResponse.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponse); + resourceDetails.setVersion(newVersion); + resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); + resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), "uniqueId"); + resourceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponse; + } + + private RestResponse changeServiceStateToCertified(ServiceReqDetails serviceDetails) throws Exception { + /* + * RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); ResourceRestUtils.checkSuccess(restResponse); + */ + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponse; + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, LifeCycleStatesEnum.CERTIFY); + if (restResponse.getErrorCode() == 200) { + serviceDetails.setVersion("1.0"); + serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + serviceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); + serviceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), "uniqueId"); + serviceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponse; + } + + @Test + public void deleteServiceInstanceTest() throws Exception { + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + String compInstId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + + createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 2, 0); + String compInstId2 = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + + RestResponse deleteServiceInstanceResp = deleteServiceInstance(compInstId, productDetails_01, sdncPmDetails1); + ResourceRestUtils.checkDeleteResponse(deleteServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 1, 0); + + deleteServiceInstanceResp = deleteServiceInstance(compInstId2, productDetails_01, sdncPmDetails1); + ResourceRestUtils.checkDeleteResponse(deleteServiceInstanceResp); + getComponentAndValidateRIs(productDetails_01, 0, 0); + } + + @Test + public void returnedServiceInstanceTypeAttributeTest() throws Exception { + String expectedServiceType = ComponentTypeEnum.SERVICE.getValue().toUpperCase(); + + RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1); + ResourceRestUtils.checkCreateResponse(createServiceInstanceResp); + String serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp); + ComponentInstanceRestUtils.checkComponentInstanceType(createServiceInstanceResp, expectedServiceType); + + RestResponse getProductResp = ProductRestUtils.getProduct(productDetails_01.getUniqueId(), sdncPsDetails1.getUserId()); + ProductRestUtils.checkSuccess(getProductResp); + Product productObject = ResponseParser.parseToObjectUsingMapper(getProductResp.getResponse(), Product.class); + List productComponentInstances = productObject.getComponentInstances(); + for (ComponentInstance comp : productComponentInstances) { + String actualOriginType = comp.getOriginType().getValue().toUpperCase(); + assertTrue(expectedServiceType.equals(actualOriginType)); + } + + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory.getComponentResourceInstance(serviceDetails_02); + serviceInstanceReqDetails.setUniqueId(serviceUniqueIdFromResponse); + serviceInstanceReqDetails.setComponentUid(serviceDetails_01.getUniqueId()); + RestResponse updateResourceInstance = ComponentInstanceRestUtils.updateComponentInstance(serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT); + ComponentInstanceRestUtils.checkSuccess(updateResourceInstance); + ComponentInstanceRestUtils.checkComponentInstanceType(updateResourceInstance, expectedServiceType); + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java new file mode 100644 index 0000000000..45d3b23983 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java @@ -0,0 +1,1718 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.Arrays; + +import org.json.JSONArray; +import org.json.JSONException; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +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.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.testng.annotations.Test; + +public class ProductCreateWithValidationsTest extends ProductBaseTest { + @Rule + public static TestName name = new TestName(); + + public static String INITIAL_PRODUCT_VERSION = "0.1"; + public static String CREATE_AUDIT_ACTION = "Create"; + public String normalizedName; + + public ProductCreateWithValidationsTest() { + super(name, ProductCreateWithValidationsTest.class.getName()); + } + + @Test // (enabled = false) + public void createProductSuccessValidation() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNotByPmUser() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productStrategistUser1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + productStrategistUser1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productStrategistUser1, ActionStatus.RESTRICTED_OPERATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNotByAsdcUser() throws Exception { + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + nonAsdcUser.setUserId("bt750k"); + nonAsdcUser.setFirstName(null); + nonAsdcUser.setLastName(null); + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, nonAsdcUser); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + nonAsdcUser); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, nonAsdcUser, ActionStatus.RESTRICTED_OPERATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductUserIdIsEmpty() throws Exception { + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + nonAsdcUser.setUserId(""); + nonAsdcUser.setFirstName(null); + nonAsdcUser.setLastName(null); + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, nonAsdcUser); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + nonAsdcUser); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, nonAsdcUser, ActionStatus.MISSING_INFORMATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNameValidationLessThanMinCharacters() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("Pro"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, + null, null, Constants.EMPTY_STRING, "Product", "abbreviated"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductNameValidationMaxLength() throws Exception { + // Max length = 25 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); +// productReqDetails.setName("Qwertyuiop1234567890asdfA"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNameValidationExceedMaxLength() throws Exception { + // Max length = 25 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("Qwertyuiop1234567890asdfAa"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, + null, null, Constants.EMPTY_STRING, "Product", "abbreviated"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNameValidationEmptyName() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName(""); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", + "abbreviated"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductNameAlreadyExist() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + // // productReqDetails.setName("CIProduct1"); + DbUtils.deleteFromEsDbByPattern("_all"); + createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_ALREADY_EXISTS, + createProduct.getErrorCode().intValue()); + productReqDetails.setVersion("0.1"); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", + productReqDetails.getName()); + constructFieldsForAuditValidation.setCURR_VERSION("0.1"); + constructFieldsForAuditValidation.setCURR_STATE(""); + constructFieldsForAuditValidation.setCURR_STATE("NOT_CERTIFIED_CHECKOUT"); + constructFieldsForAuditValidation.setSERVICE_INSTANCE_ID(null); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNameValidationNameIsNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName(null); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", + "abbreviated"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + // DE193857 + @Test (enabled = false) + public void createProductNameValidationAllowedCharacters() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("Ci_2@3:4& m=n+b-u.j-u'g#b"); // Bug @:&=+'# + normalizedName = "ci234mnbujugb"; + String expectedProductName = "Ci_2@3:4& M=n+b-u.j-u'g#b"; + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + productReqDetails.setName(expectedProductName); + productReqDetails.setName("Ci_2@3:4& M=n+b-u.j-u'g#b"); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setNormalizedName(normalizedName); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + // DE193857 + @Test + public void createProductNameValidationREmoveExtraNonAlphanumericChars() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("Ci____222----333......asd"); +// productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setName("Ci_222-333.asd"); + normalizedName = "ci222333asd"; + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNameValidationNotAllowedCharacters() throws Exception { + ExpectedProductAudit constructFieldsForAuditValidation; + char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', + '\\', ',', '$' }; + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("abc" + invalidChars[i]); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", + productManager1); + constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, + CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", + "abbreviated"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + } + + @Test + public void createProductFullNameContainSpecialCharacters() throws Exception { + char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', + '\\', ',', '$' }; + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + for (int i = 0; i < invalidChars.length; i++) { + DbUtils.deleteFromEsDbByPattern("_all"); + productReqDetails.setFullName("abc" + invalidChars[i]); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + RestResponse deleteProduct = ProductRestUtils.deleteProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, + deleteProduct.getErrorCode().intValue()); + } + } + + // Already enabled = false + @Test + public void createProductNameValidationRemoveSpaceFromBeginning() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName(" Ciertyuiop1234567890asdfA"); +// productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); + normalizedName = productReqDetails.getName().trim().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + productReqDetails.setName(" Ciertyuiop1234567890asdfA".trim()); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + // Already enabled = false + @Test + public void createProductNameValidationRemoveSpaceFromTheEnd() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("Ciertyuiop1234567890asdfA "); +// productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); + normalizedName = productReqDetails.getName().trim().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + productReqDetails.setName("Ciertyuiop1234567890asdfA ".trim()); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductNameValidationStartWithNumber() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("1Qwert"); +// productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); + normalizedName = productReqDetails.getName().trim().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + productReqDetails.setName("Ci1Qwert"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + + } + + @Test + public void createProductNameValidationStartWithNonAlphaNumeric() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("_Qwert"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim())); + normalizedName = productReqDetails.getName().trim().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, Constants.EMPTY_STRING, Constants.EMPTY_STRING, + null, null, Constants.EMPTY_STRING, "Product", "abbreviated"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + // productReqDetails.setTags(Arrays.asList("abba")); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + // // productReqDetails.setName("Abba"); + /* + * String actualNormalizedNameFromResponse = + * ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), + * "normalizedName"); + * assertTrue(actualNormalizedNameFromResponse.equals(normalizedName)); + */ + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductFullNameValidationIsEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setFullName(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "full"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductFullNameValidationIsNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setFullName(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "full"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductFullNameLessThanMinLength() throws Exception { + // Min is 4 characters + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setFullName("abc"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, + null, null, Constants.EMPTY_STRING, "Product", "full"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductFullNameHasMinLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setFullName("abcd"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductFullNameHasMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setFullName( + "Abba1234567890asdfghjk l123zxcvbnm432adfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductFullNameExceedMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setFullName( + "Abba1234567890asdfghjk l123zxcvbnm432adfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.123"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, + ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING, + null, null, Constants.EMPTY_STRING, "Product", "full"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductFullNameRemoveExtraSpaces() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setFullName("Abbaaa a1"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setFullName("Abbaaa a1"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductDescriptionValidationIsEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setDescription(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_DESCRIPTION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductDescriptionValidationIsNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setDescription(null); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_DESCRIPTION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductDescriptionValidCharacters01() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductDescriptionValidCharacters02() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductDescriptionInValidCharacters() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription("מה"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_DESCRIPTION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductDescriptionRemoveSpacesFromBeginning() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription(" abcd12345"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setDescription("abcd12345"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductDescriptionRemoveSpacesFromTheEnd() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription("abcd 12345 xcvb "); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setDescription("abcd 12345 xcvb"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductDescriptionMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription( + "Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12asdfghjklzxcvbnmqwertyui"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductDescriptionExceedMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("Abba"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setDescription( + "Abxba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12asdfghjklzxcvbnmqwertyui"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "1024"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductTagIsEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setName("Product"); + productReqDetails.setTags(Arrays.asList("")); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_FIELD_FORMAT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "tag"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + // DE192351 + @Test // (enabled = false) + public void createProductTagValidationAllowedCharacters() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Acde2@3:4& m=n+b-u.j-u'g#b")); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductTagsNameValidationProductNameIsNotInTag() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); +// productReqDetails.setName("Qwertyuiop1234567890asdfA"); + productReqDetails.setTags(Arrays.asList("Abc")); + normalizedName = productReqDetails.getName().trim().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductSingleTagMaxLength() throws Exception { + // SingleTagMaxLength = 50 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345678")); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductSingleTagExceedMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Axbba1234567890asdfghjkl123zxcvbnm432asdfgh12345678")); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "50"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductAllTagsMaxLength() throws Exception { + // AllTagsMaxLength = 1024 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345")); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductAllTagsExceedMaxLength() throws Exception { + // AllTagsMaxLength = 1024 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456")); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "1024"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductDuplicateTagRemoved() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductContactsIsEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + productReqDetails.setContacts(Arrays.asList("")); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_CONTACT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductContactsInvalidFormat() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + productReqDetails.setContacts(Arrays.asList("bt750345")); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_CONTACT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductConvertContactsToLowerCase() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + productReqDetails.setContacts(Arrays.asList(productManager1.getUserId().toUpperCase())); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setContacts(Arrays.asList(productManager1.getUserId().toLowerCase())); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductContactsDoexNotContainTheProductCreator() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + productReqDetails.setContacts(Arrays.asList(productManager2.getUserId())); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setContacts(Arrays.asList(productManager2.getUserId(), productManager1.getUserId())); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductContactsNotAllowedAsdcUsers() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + productReqDetails.setContacts(Arrays.asList(designerUser.getUserId())); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PRODUCT_CONTACT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, + designerUser.getUserId()); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductContactsNotAsdcUser() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); // Bug @:&=+'# + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase(); + String nonAsdcUser = "bh1234"; + productReqDetails.setContacts(Arrays.asList(nonAsdcUser)); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PRODUCT_CONTACT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, nonAsdcUser); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeIsEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_PROJECT_CODE, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeIsNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode(null); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_PROJECT_CODE, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeIsNotNumeric() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode("asdfgh"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeHasnMinCharacters() throws Exception { + // Min =5 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode("12345"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeHasnMaxCharacters() throws Exception { + // Max =10 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode("1234567890"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeExceedMaxCharacters() throws Exception { + // Max =10 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode("12345678901"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductProjectCodeLessThanMinCharacters() throws Exception { + // Max =10 + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setProjectCode("1234"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIconIsEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setIcon(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_ICON, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIconIsNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setIcon(null); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_ICON, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIconMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setIcon("asdfghjklqwertyuiozxcvbfv"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIconExceedMaxLength() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setIcon("asdfghjklqwertyuiozxcvbf12"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "25"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIconAllowedCharacters() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setIcon("a--s-fghjk_q__r1234567890"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test (enabled = false) + public void createProductIconInValidCharacters() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + String icon = "asdfg"; + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', + '|', '\\', ',' }; + RestResponse createProduct; + for (int i = 0; i < invalidChars.length; i++) { + productReqDetails.setIcon(icon + invalidChars[i]); + createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", + productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_ICON, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product"); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + } + + @Test // (enabled = false) + public void createProductIsActiveisEmpty() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setActive(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setActive("false"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIsActiveisNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setActive(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + productReqDetails.setActive("false"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIsActiveisFalse() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setActive("false"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test + public void createProductIsActiveisHasInvalidValue() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setActive("xfalse"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_CONTENT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + constructFieldsForAuditValidation.setRESOURCE_NAME(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled = false) + public void createProductIsActiveisTrue() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + // productReqDetails.setName("CIProduct1"); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + productReqDetails.setActive("true"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + ////////////////////////////////////////////// + // DE192424 + @Test // (enabled = false) + public void createProductNameValidationNormalizationNameWithSpaces() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); +// productReqDetails.setName("Abba Emma"); + // productReqDetails.setName("abba emma"); + // productReqDetails.setTags(Arrays.asList("abba emma")); + normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", ""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + String actualNormalizedNameFromResponse = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), + "normalizedName"); + assertTrue(actualNormalizedNameFromResponse.equals(normalizedName)); + // productReqDetails.setName("Abba Emma"); + String productUuid = ResponseParser.getUuidFromResponse(createProduct); + compareExpectedAndActualProducts(productReqDetails, createProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProductRes); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + private void compareExpectedAndActualProducts(ProductReqDetails productReqDetails, RestResponse createProduct) + throws JSONException { + String productName = ResponseParser.getNameFromResponse(createProduct); + assertTrue(productReqDetails.getName().equals(productName)); + String productIcon = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "icon"); + assertTrue(productReqDetails.getIcon().equals(productIcon)); + String productFullName = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "fullName"); + assertTrue(productReqDetails.getFullName().equals(productFullName)); + String productProjectCode = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "projectCode"); + assertTrue(productReqDetails.getProjectCode().equals(productProjectCode)); + String productIsActive = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "isActive"); + String expectedIsActive = (productReqDetails.getActive() != null ? productReqDetails.getActive() : "false"); + assertTrue(productIsActive.equals(expectedIsActive)); + String productdescription = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "description"); + assertTrue(productReqDetails.getDescription().equals(productdescription)); + String productNormalizedName = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), + "normalizedName"); + assertTrue(normalizedName.equals(productNormalizedName)); + String productContacts = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "contacts"); + JSONArray reciviedContacts = new JSONArray(productContacts); + String actualContact = null; + for (int i = 0; i < reciviedContacts.length(); i++) { + actualContact = reciviedContacts.getString(i); + assertEquals(productReqDetails.getContacts().get(i), actualContact); + } + String productTags = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "tags"); + JSONArray reciviedTages = new JSONArray(productTags); + String actualTag = null; + for (int i = 0; i < reciviedTages.length(); i++) { + actualTag = reciviedTages.getString(i); + assertEquals(productReqDetails.getTags().get(i), actualTag); + } + } + + // END + /////////////////////////////////////////////////////// + @Test + public void createProductSuccessFlow() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, + getProductRes.getErrorCode().intValue()); + + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(false)); + } + + @Test + public void createProductSetIsActive() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setActive("true"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, + getProductRes.getErrorCode().intValue()); + + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + assertEquals(actualProduct.getIsActive(), new Boolean(true)); + } + + @Test + public void createProductNoIcon() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setIcon(null); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_DATA, + createProduct.getErrorCode().intValue()); + + } + + @Test + public void createProductNoProjectCode() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + productReqDetails.setProjectCode(null); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_DATA, + createProduct.getErrorCode().intValue()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java new file mode 100644 index 0000000000..2044d213e6 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java @@ -0,0 +1,2551 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +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.ExpectedProductAudit; +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.general.Convertor; +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.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class ProductCrudTest extends ProductBaseTest { + private static Logger log = LoggerFactory.getLogger(ProductCrudTest.class.getName()); + @Rule + public static TestName name = new TestName(); + + public static String INITIAL_PRODUCT_VERSION = "0.1"; + public static String CREATE_AUDIT_ACTION = "Create"; + public static String UPDATE_AUDIT_ACTION = "Update"; + public static String COMPONENT_TYPE = "Product"; + + private ProductReqDetails productReqDetails; + private RestResponse createProduct; + private Product product; + + public ProductCrudTest() { + super(name, ProductCrudTest.class.getName()); + } + + @Test // (enabled=false) + public void createAndGetAll() throws Exception { + createProductAndGet(UserRoleEnum.DESIGNER); + } + + private void createProductAndGet(UserRoleEnum user) throws Exception, IOException { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + RestResponse catalog = CatalogRestUtils.getCatalog(user.getUserId()); + assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_SUCCESS, + catalog.getErrorCode().intValue()); + + try { + JsonElement jElement = new JsonParser().parse(catalog.getResponse()); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray products = (JsonArray) jObject.get("products"); + assertEquals("Check product array size", 1, products.size()); + Iterator iter = products.iterator(); + while (iter.hasNext()) { + JsonElement next = iter.next(); + Product product = ResponseParser.parseToObjectUsingMapper(next.toString(), Product.class); + assertNotNull(product); + assertEquals("Check product name", productReqDetails.getName(), product.getName()); + // Map allVersions = product.getAllVersions(); + // assertEquals("Check product name", 1, allVersions.size()); + } + + } catch (Exception e) { + log.debug("exception", e); + } + } + + @Test + public void getAllNoProcduts() throws Exception { + + RestResponse catalog = CatalogRestUtils.getCatalog(); + assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_SUCCESS, + catalog.getErrorCode().intValue()); + + try { + JsonElement jElement = new JsonParser().parse(catalog.getResponse()); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray products = (JsonArray) jObject.get("products"); + assertEquals("Check product array size", 0, products.size()); + } catch (Exception e) { + log.debug("exception", e); + } + + } + + @Test + public void getAllNoAttHeader() throws Exception { + String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort()); + + List headersToRemove = new ArrayList(); + headersToRemove.add(HttpHeaderEnum.USER_ID.getValue()); + + RestResponse catalog = CatalogRestUtils.sendGetAndRemoveHeaders(url, null, headersToRemove); + assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, + catalog.getErrorCode().intValue()); + + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), + catalog.getResponse()); + } + + @Test + public void getAllWrongUser() throws Exception { + RestResponse catalog = CatalogRestUtils.getCatalog("kj8976"); + assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + catalog.getErrorCode().intValue()); + + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + catalog.getResponse()); + } + + @Test // (enabled=false) + public void getAllWithProductStrategist_User() throws Exception { + createProductAndGet(UserRoleEnum.PRODUCT_STRATEGIST1); + } + + @Test // (enabled=false) + public void getAllWithProductManager_User() throws Exception { + createProductAndGet(UserRoleEnum.PRODUCT_MANAGER1); + } + + @Test // (enabled=false) + public void createProductNoCategories() throws Exception { + createProductWithCategories(null); + } + + @Test // (enabled=false) + public void createProductOneGrouping() throws Exception { + // Category1->[Subcategory1->[Grouping1]] + createProductWithCategories(defaultCategories); + } + + @Test // (enabled=false) + public void createProductTwoGroupingsSameSubCategory() throws Exception { + // Category1->Subcategory1->[Grouping1, Grouping11] + List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); + createProductWithCategories(addSecondGroupingToDefaultCategory); + } + + @Test // (enabled=false) + public void createProductTwoSubsDifferentGroupings() throws Exception { + // Category1->[Subcategory1->[Grouping1, + // Grouping11],Subcategory2->[Grouping12]] + List addSubcategoryAndGroupingToDefaultCategory = addSubcategoryAndGroupingToDefaultCategory(); + createProductWithCategories(addSubcategoryAndGroupingToDefaultCategory); + } + + @Test // (enabled=false) + public void createManyGroupingsDiffCategories() throws Exception { + // [Category1->[Subcategory1->[Grouping1, + // Grouping11],Subcategory2->[Grouping12]], + // Category2->[Subcategory1->[Grouping1],Subcategory2->[Grouping1]], + // Category3->[Subcategory1->[Grouping11],Subcategory2->[Grouping11, + // Grouping22]]] + List addSubcategoryAndGroupingToDefaultCategory = addManyGroupingsDiffCategories(); + createProductWithCategories(addSubcategoryAndGroupingToDefaultCategory); + } + + @Test // (enabled=false) + public void createProductEmptyUserId() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + User emptyUser = new User(); + emptyUser.setUserId(""); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, emptyUser); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + emptyUser); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, emptyUser, ActionStatus.MISSING_INFORMATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled=false) + public void createProductNonExistingUserId() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + User notExistingUser = new User(); + notExistingUser.setUserId("jj6444"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, notExistingUser); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + notExistingUser); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, notExistingUser, ActionStatus.RESTRICTED_OPERATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled=false) + public void createProductInvalidJson() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct_Invalid_Json(productManager1.getUserId()); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + productManager1); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_CONTENT, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setRESOURCE_NAME(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled=false) + public void createProductAdminRoleNotAllowed() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + User wrongRole = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, wrongRole); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + wrongRole); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, wrongRole, ActionStatus.RESTRICTED_OPERATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled=false) + public void createProductProductStrategistRoleNotAllowed() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + User wrongRole = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST3); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, wrongRole); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + createProduct.getErrorCode().intValue()); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + wrongRole); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, wrongRole, ActionStatus.RESTRICTED_OPERATION, + Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING); + constructFieldsForAuditValidation.setCURR_VERSION(""); + constructFieldsForAuditValidation.setCURR_STATE(""); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + @Test // (enabled=false) + public void getProductSuccessFlow() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, + getProductRes.getErrorCode().intValue()); + + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + } + + @Test // (enabled=false) + public void getNonExistedProduct() throws Exception { + + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, + getProductRes.getErrorCode().intValue()); + + Product product = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class); + assertEquals("Assert on product icon", productReqDetails.getName(), product.getName()); + + RestResponse deleteProductRes = ProductRestUtils.deleteProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code for deletign Product", BaseRestUtils.STATUS_CODE_SUCCESS, + deleteProductRes.getErrorCode().intValue()); + + RestResponse getProductAfterDeleteRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting deleted Product", BaseRestUtils.STATUS_CODE_NOT_FOUND, + getProductAfterDeleteRes.getErrorCode().intValue()); + } + + @Test // (enabled=false) + public void getProductMissingHeader() throws Exception { + + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + productManager1.setUserId(null); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting created Producuct with userId extracted from header", + BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, getProductRes.getErrorCode().intValue()); + + } + + @Test // (enabled=false) + public void getProductNonExistingUser() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + + productManager1.setUserId("bt1111"); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + assertEquals("Check response code after getting created Producuct with non exsisting user", + BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, getProductRes.getErrorCode().intValue()); + } + + @Test // (enabled=false) + public void createProductAndGetProductWithDifferentUser() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + User sdncProductStrategistUserAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + sdncProductStrategistUserAdminDetails.getUserId()); + assertEquals("Check response code after getting created Product different user role", + BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue()); + } + + // US594753 - Update Product metadata + + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductAllFieldsByPM() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + // Update product + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("NewProductName"); + List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); + productReqDetails.setFullName("New Full name"); + productReqDetails.setActive("false"); + productReqDetails.setContacts( + Arrays.asList(productManager2.getUserId().toLowerCase(), productManager1.getUserId().toLowerCase())); + productReqDetails.setDescription("New Product Description"); + productReqDetails.setIcon("asdfghjklqwertyuiozxcvbfv"); + productReqDetails.setProjectCode("98765"); + productReqDetails.setCategories(addSecondGroupingToDefaultCategory); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), + // productOldName)); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductByPS() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("New discription"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productStrategistUser1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updateProduct.getResponse()); + } + + @Test // (enabled=false) + public void updateProductByAdmin() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("New discription"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, designerUser); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updateProduct.getResponse()); + } + + @Test // (enabled=false) + public void updateProductByNonPmUser() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + // Update product name + productReqDetails.setDescription("New discription"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, designerUser); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updateProduct.getResponse()); + } + + @Test // (enabled=false) + public void updateProductByNonAsdcUser() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + // Update product name + productReqDetails.setDescription("New discription"); + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + nonAsdcUser.setUserId("bt789k"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, nonAsdcUser); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updateProduct.getResponse()); + } + + @Test // (enabled=false) + public void updateProductUserIdIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + // Update product name + productReqDetails.setDescription("New discription"); + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + nonAsdcUser.setUserId(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, nonAsdcUser); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList(), + updateProduct.getResponse()); + } + + @Test // (enabled=false) + public void updateProductByNonProductOwner() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("New discription"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.GET_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNotInCheckoutState() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + // Update product name + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(changeProductLifeCycle.getResponse(), + "lastUpdateDate"); + expectedProduct.setLastUpdateDate(Long.parseLong(valueFromJsonResponse)); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNameIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("abbreviated"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNameIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager2, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + // List tags = productReqDetails.getTags(); + // tags.removeAll(tags); + productReqDetails.setTags(new ArrayList<>()); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName(null); // no update will be performed + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); + ProductRestUtils.checkSuccess(updateProduct); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager2); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(product.getName().toLowerCase()); + expectedProduct.setName(product.getName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNameLessThanMinLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("ABC"); // no update will be performed + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("abbreviated"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), + varibales, updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductNameHasMinLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager2, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("NewP"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + productReqDetails.setLastUpdaterUserId(productManager2.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager2.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager2); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + // DE193857 - Normalized Name is not removing special characters + @Test(enabled = false) + public void updateProductNameMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + // Update product name + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("Ac_2B3U4k mSKnob-u.j-uGgP"); + String newNormalizedName = "ac2b3u4kmsknobujuggp"; + String newName = "Ac_2B3U4k MSKnob-u.j-uGgP"; + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setTags(Arrays.asList(newName)); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(newNormalizedName); + expectedProduct.setName(newName); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNameExceedMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("Ac_2B3U4k mSKnob-u.j-uGgPx"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("abbreviated"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), + varibales, updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNameAlreadyExist() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2); + ProductRestUtils.checkCreateResponse(createProduct); + Product product1 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product1, productManager2, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setName("Product2000"); + // productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2); + ProductRestUtils.checkCreateResponse(createProduct); + Product product2 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product2, productManager2, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product2, productManager2, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product2.getUniqueId()); + productReqDetails.setUUID(product2.getUUID()); + productReqDetails.setName(product1.getName()); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_ALREADY_EXISTS, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add(product1.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager2.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product2.getUniqueId()); + expectedProduct.setVersion(product2.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // DE193857 - Normalized Name is not removing special characters + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductNameAllowedCharacters() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + // Update product name + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("A_BU4k m&K=o#b-u.j-uG'g+P"); // Allowed + // characters + // [a-z,A-Z,0-9] + // , ‘ ‘ + // (space), + // ampersand + // "&", dash + // “-“, plus + // "+", period + // ".", + // apostrophe + // "'", hashtag + // "#", equal + // "=", period + // ":", at "@", + // and + // underscore + // "_" + String newNormalizedName = "abu4km&kobujuggp"; + String newName = "A_BU4k M&K=o#b-u.j-uG'g+P"; + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setTags(Arrays.asList(newName)); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(newNormalizedName); + expectedProduct.setName(newName); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductNameRemoveSpaceFromBeginning() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName(" asdfg"); + String newNormalizedName = "asdfg"; + String newName = "Asdfg"; + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // productReqDetails.setTags(Arrays.asList(newName, productOldName)); + productReqDetails.setTags(Arrays.asList(newName)); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(newNormalizedName); + expectedProduct.setName(newName); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductNameRemoveSpaceFromEnd() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("asdfg fc "); + String newNormalizedName = "asdfgfc"; + String newName = "Asdfg Fc"; + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // productReqDetails.setTags(Arrays.asList(newName, productOldName)); + productReqDetails.setTags(Arrays.asList(newName)); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(newNormalizedName); + expectedProduct.setName(newName); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + //// DE193857 - Normalized Name is not removing special characters + // If user update "product name" we need to remove the old product name from + //// "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductNameRemoveExtraNonAlphanumericChars() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("A__k &&==##---u..hG'''+++"); + String newNormalizedName = "akhg"; + String newName = "A_k &=#-u.hG'+"; + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // productReqDetails.setTags(Arrays.asList(newName, productOldName)); + productReqDetails.setTags(Arrays.asList(newName)); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(newNormalizedName); + expectedProduct.setName(newName); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // If user update "product name" we need to remove the old product name from + // "Tags" and add the new product name instead - will handled in mew US + @Test(enabled = false) + public void updateProductNameValidationStartWithNumber() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("1000Ab"); + String newNormalizedName = productReqDetails.getName().toLowerCase(); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName())); + // productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), + // productOldName)); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setNormalizedName(newNormalizedName); + expectedProduct.setName(productReqDetails.getName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductNameValidationStartWithNonAlphaNumeric() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setName("_1000Ab"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("abbreviated"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT.name(), + varibales, updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNameIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("full"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNameIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setNormalizedName(product.getNormalizedName()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setFullName(product.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNameHasMinLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName("asdc"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setNormalizedName(product.getNormalizedName()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setFullName(productReqDetails.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNameHasMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName( + "1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setNormalizedName(product.getNormalizedName()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setFullName(productReqDetails.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNamelessThanMinLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName("123"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("full"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), + varibales, updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNameExceedMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName( + "1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjkx"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("full"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), + varibales, updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + // DE193947 + @Test + public void updateProductFullNameWithSpecialCharacters() throws Exception { + char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', + '\\', ',', '$', '#', '@', '+' }; + String fullName = "avbng"; + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + for (int i = 0; i < invalidChars.length; i++) { + productReqDetails.setFullName(fullName + invalidChars[i]); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, + updateProduct.getErrorCode().intValue()); + } + } + + @Test // (enabled=false) + public void updateProductFullNameValidCharactersCharacters01() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setNormalizedName(product.getNormalizedName()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setFullName("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductFullNameRemoveExtraSpaces() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setFullName("Abbaaa a1"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setNormalizedName(product.getNormalizedName()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setFullName("Abbaaa a1"); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test(enabled = false) + public void updateProductDescriptionValidCharacters01() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#"); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionValidCharacters02() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold<"); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionInValidCharacters() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("מה"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionRemoveSpacesFromBeginning() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription(" abcd12345 g"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setDescription(" abcd12345 g"); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionRemoveSpacesFromTheEnd() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setDescription("abcd12345 gdf "); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setDescription("abcd12345 gdf "); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + String description = "1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfg"; + productReqDetails.setDescription(description); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setDescription(description); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductDescriptionExceedMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + String description = "01234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfg"; + productReqDetails.setDescription(description); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("1024"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT.name(), + varibales, updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductTagIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags(Arrays.asList("")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + varibales.add("tag"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductTagIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setTags(product.getTags()); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductTagsNameValidationProductNameIsNotInTag() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags(Arrays.asList("Abc")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME.name(), + new ArrayList(), updateProduct.getResponse()); + } + + @Test // (enabled=false) + public void createProductSingleTagMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345678")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setTags(productReqDetails.getTags()); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductSingleTagExceedMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), + "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("1024"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductAllTagsMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setTags(productReqDetails.getTags()); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductAllTagsExceedMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags( + Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619", + "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add("1024"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductTagsDuplicateTagRemoved() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "KoKo", "KoKo")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata updated + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setTags(Arrays.asList(productReqDetails.getName(), "KoKo")); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductContactsIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setContacts(Arrays.asList("")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductContactsIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setContacts(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductContactsInvalidFormat() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setContacts(Arrays.asList("bt750345")); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(COMPONENT_TYPE); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductConvertContactsToLowerCase() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setContacts(Arrays.asList(productManager2.getUserId().toUpperCase())); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct + .setContacts(Arrays.asList(productManager2.getUserId().toLowerCase(), productManager1.getUserId())); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductContactsNotAllowedAsdcUsers() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setContacts(Arrays.asList(productStrategistUser1.getUserId())); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(productStrategistUser1.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PRODUCT_CONTACT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductContactsNotAsdcUser() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + String nonAsdcUserUserId = "bt567h"; + productReqDetails.setContacts(Arrays.asList(nonAsdcUserUserId)); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(nonAsdcUserUserId); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PRODUCT_CONTACT.name(), varibales, + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_PROJECT_CODE.name(), new ArrayList(), + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setProjectCode(product.getProjectCode()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeLessThanMinCharacters() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode("9870"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList(), + updateProduct.getResponse()); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeHasnMinCharacters() throws Exception { // min + // =5 + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode("98700"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setProjectCode(productReqDetails.getProjectCode()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeHasnMaxCharacters() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode("1234567890"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setProjectCode(productReqDetails.getProjectCode()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeExceedMaxCharacters() throws Exception {// Max + // =10 + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode("12345678901"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList(), + updateProduct.getResponse()); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setProjectCode(product.getProjectCode()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductProjectCodeIsNotNumeric() throws Exception { + // Max =10 + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setProjectCode("1234a"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList(), + updateProduct.getResponse()); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setProjectCode(product.getProjectCode()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIconIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setIcon(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList variables = new ArrayList(); + variables.add(COMPONENT_TYPE); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables, + updateProduct.getResponse()); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIcon(product.getIcon()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIconIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setIcon(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + // Get Product and verify that metadata didn't change + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIcon(product.getIcon()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIconMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setIcon("A_a-1-2--b__BB1234567890A"); // Max length = + // 25 + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIcon(productReqDetails.getIcon()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIconExceedMaxLength() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setIcon("A_a-1-2--b__BB1234567890A_"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList variables = new ArrayList(); + variables.add(COMPONENT_TYPE); + variables.add("25"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT.name(), variables, + updateProduct.getResponse()); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIcon(product.getIcon()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIconInValidCharacters() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + String icon = "asdfg"; // Allowed characters [a-zA-Z0-9], dash (‘-‘), + // underscore (‘_’). + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', + '|', '\\', ',' }; + RestResponse updateProduct; + for (int i = 0; i < invalidChars.length; i++) { + productReqDetails.setIcon(icon + invalidChars[i]); + updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ArrayList variables = new ArrayList(); + variables.add(COMPONENT_TYPE); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), variables, + updateProduct.getResponse()); + } + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIcon(product.getIcon()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIsActiveIsEmpty() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setActive(""); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIsActive(false); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIsActiveIsTrue() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setActive("true"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIsActive(true); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIsActiveIsNull() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); + productReqDetails.setActive("true"); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setActive(null); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIsActive(true); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIsActiveIsFalse() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setActive("false"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + expectedProduct.setIsActive(false); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductIsActiveHasInvalidValue() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setActive("eeeee"); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + updateProduct.getResponse()); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, + updateProduct.getErrorCode().intValue()); + RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + ProductRestUtils.checkSuccess(getProduct); + Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + expectedProduct.setUniqueId(product.getUniqueId()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class); + expectedProduct.setVersion(product.getVersion()); + expectedProduct.setLastUpdaterUserId(productManager1.getUserId()); + expectedProduct.setLastUpdaterFullName(productManager1.getFullName()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductAssociations() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); + productReqDetails.setCategories(addSecondGroupingToDefaultCategory); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setCategories(productReqDetails.getCategories()); + expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductAssociations02() throws Exception { + List addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); // Category1->Subcategory1->[Grouping1, + // Grouping11] + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(addSecondGroupingToDefaultCategory); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + List defaultCategory = addSubcategoryAndGroupingToDefaultCategory(); // Category1->[Subcategory1->[Grouping1, + // Grouping11],Subcategory2->[Grouping12]] + productReqDetails.setCategories(defaultCategory); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setCategories(productReqDetails.getCategories()); + expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductRemoveAllAssociations() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + List defaultCategory = new ArrayList(); + productReqDetails.setCategories(defaultCategory); + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setCategories(productReqDetails.getCategories()); + expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + @Test // (enabled=false) + public void updateProductAssociationsCategotyIsNull() throws Exception { + createProducrByPSAndCheckIn(); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + productReqDetails.setUniqueId(product.getUniqueId()); + productReqDetails.setUUID(product.getUUID()); + productReqDetails.setCategories(null);// product categories will not be + // updated + RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1); + ProductRestUtils.checkSuccess(updateProduct); + productReqDetails.setLastUpdaterUserId(productManager1.getUserId()); + productReqDetails.setLastUpdaterFullName(productManager1.getFullName()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1); + expectedProduct.setUUID(product.getUUID()); + expectedProduct.setInvariantUUID(product.getInvariantUUID()); + expectedProduct.setCategories(product.getCategories()); + expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase()); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.UPDATE_COMPONENT); + } + + //////////////////////////////////////////////////////////////////////// + + private void createProductWithCategories(List categoryDefinitions) throws Exception { + ProductReqDetails productReqDetails = (categoryDefinitions != null + ? ElementFactory.getDefaultProduct(categoryDefinitions) : ElementFactory.getDefaultProduct()); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + String actualUuid = ResponseParser.getUuidFromResponse(createProduct); + Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, + productManager1); + String normalizedNameFomJsonResponse = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), + "normalizedName"); + expectedProduct.setNormalizedName(normalizedNameFomJsonResponse); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, + ComponentOperationEnum.CREATE_COMPONENT); + ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation( + expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, + "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, actualUuid); + AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION); + } + + private void createProducrByPSAndCheckIn() throws Exception { + productReqDetails = ElementFactory.getDefaultProduct(defaultCategories); + createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + ProductRestUtils.checkCreateResponse(createProduct); + product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, + LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.checkSuccess(changeProductLifeCycle); + } + + @Test + public void checkInvariantUuidIsImmutable() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!"; + productReqDetails.setInvariantUUID(invariantUuidDefinedByUser); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + BaseRestUtils.checkStatusCode(createProduct, "create request failed", false, 201); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + Product ProductCreation = ResponseParser.convertProductResponseToJavaObject(createProduct.getResponse()); + String invariantUUIDcreation = ProductCreation.getInvariantUUID(); + + // validate get response + RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), + productManager1.getUserId()); + BaseRestUtils.checkSuccess(getProductRes); + Product productGetting = ResponseParser.convertProductResponseToJavaObject(getProductRes.getResponse()); + String invariantUUIDgetting = productGetting.getInvariantUUID(); + assertEquals(invariantUUIDcreation, invariantUUIDgetting); + + // Update Product with new invariant UUID + RestResponse restResponseUpdate = ProductRestUtils.updateProduct(productReqDetails, productManager1); + BaseRestUtils.checkSuccess(restResponseUpdate); + Product updatedProduct = ResponseParser.convertProductResponseToJavaObject(restResponseUpdate.getResponse()); + String invariantUUIDupdating = updatedProduct.getInvariantUUID(); + assertEquals(invariantUUIDcreation, invariantUUIDupdating); + + // Do checkin + RestResponse restResponseCheckin = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, + LifeCycleStatesEnum.CHECKIN); + BaseRestUtils.checkSuccess(restResponseCheckin); + Product checkinProduct = ResponseParser.convertProductResponseToJavaObject(restResponseCheckin.getResponse()); + String invariantUUIDcheckin = checkinProduct.getInvariantUUID(); + String version = checkinProduct.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcheckin); + assertEquals(version, "0.1"); + + // Do checkout + RestResponse restResponseCheckout = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, + LifeCycleStatesEnum.CHECKOUT); + BaseRestUtils.checkSuccess(restResponseCheckout); + Product checkoutProduct = ResponseParser.convertProductResponseToJavaObject(restResponseCheckout.getResponse()); + String invariantUUIDcheckout = checkoutProduct.getInvariantUUID(); + version = checkoutProduct.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcheckout); + assertEquals(version, "0.2"); + + } + + // US672129 Benny + private void getProductValidateInvariantUuid(String productUniqueId, String invariantUUIDcreation) + throws Exception { + RestResponse getProduct = ProductRestUtils.getProduct(productUniqueId, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getProduct.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(getProduct)); + } + + @Test // invariantUUID generated when the component is created and never + // changed + public void productInvariantUuid() throws Exception { + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + String invariantUuidDefinedByUser = "12345"; + productReqDetails.setInvariantUUID(invariantUuidDefinedByUser); + RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1); + assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + // invariantUUID generated when the component is created and never + // changed + String invariantUUIDcreation = ResponseParser.getInvariantUuid(createProduct); + getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); + // Update Product with new invariant UUID + RestResponse restResponse = ProductRestUtils.updateProduct(productReqDetails, productManager1); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); + // Checkin + restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); + // Checkout + restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); + + // UnDo-CheckOut + restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, + LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java new file mode 100644 index 0000000000..aebea697b2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java @@ -0,0 +1,164 @@ +/*- + * ============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.ci.tests.execute.product; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +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.ProductRestUtils; +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.validation.ProductValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class ProductGetFollowedTest extends ProductBaseTest { + + protected Product product200; + protected Product product400; + + private ProductReqDetails productDetails200; + private ProductReqDetails productDetails400; + + @Rule + public static TestName name = new TestName(); + + public ProductGetFollowedTest() { + super(name, ProductGetFollowedTest.class.getName()); + } + + @BeforeMethod + public void init() throws Exception { + createProducts(); + } + + @Test + public void followedPageTest() throws Exception { // Actions + RestResponse changeLifeCycleResponse; + changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeLifeCycleResponse); + changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeLifeCycleResponse); + // Expected users Followed page + ProductValidationUtils.checkUserFollowedPage(productManager1, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); + ProductValidationUtils.checkUserFollowedPage(productManager2, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); + } + + @Test + public void followedPagePmCheckedOutProductWasCheckInByOtherPm() throws Exception { + ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.changeProductLifeCycle(product400, productManager1, LifeCycleStatesEnum.CHECKOUT); + RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager2, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeLifeCycleResponse); + + ProductValidationUtils.checkUserFollowedPage(productManager1, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); + } + + @Test + public void followedPagePmCheckInProduct02() throws Exception { + ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); + + ProductValidationUtils.checkUserFollowedPage(productManager1, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); + ProductValidationUtils.checkUserFollowedPage(productManager2, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); + } + + @Test + public void followedPageAdminCheckoutProductWasCheckedinByPm() throws Exception { + ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); + RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeLifeCycleResponse); + + ProductValidationUtils.checkUserFollowedPage(productManager1, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); + } + + @Test + public void followedPageAdminCheckInProduct() throws Exception { + ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKOUT); + RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(changeLifeCycleResponse); + + ProductValidationUtils.checkUserFollowedPage(productManager1, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); + } + + @Test + public void followedPagePmCheckoutProductWasCheckedinByAdmin() throws Exception { + ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN); + ProductRestUtils.changeProductLifeCycle(product200, adminUser, LifeCycleStatesEnum.CHECKOUT); + ProductRestUtils.changeProductLifeCycle(product200, adminUser, LifeCycleStatesEnum.CHECKIN); + RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager2, LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(changeLifeCycleResponse); + + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product200); + ProductValidationUtils.checkUserFollowedPage(productManager2, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400); + ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400); + } + + private void createProducts() throws Exception { + // PM1 (Product manager) create :PR200 (check In State) + // PM2 (Product manager) create :PR400 (check In State) + + productDetails200 = ElementFactory.getDefaultProduct("CiProd200", defaultCategories); + productDetails400 = ElementFactory.getDefaultProduct("CiProd400", defaultCategories); + + RestResponse createProduct = ProductRestUtils.createProduct(productDetails200, productManager1); + ResourceRestUtils.checkCreateResponse(createProduct); + product200 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + + createProduct = ProductRestUtils.createProduct(productDetails400, productManager2); + ResourceRestUtils.checkCreateResponse(createProduct); + product400 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java new file mode 100644 index 0000000000..26bb3e29e9 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.execute.product; + +import static org.testng.AssertJUnit.assertEquals; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.annotations.BeforeMethod; + +public abstract class ProductLifecycleTest extends ProductBaseTest { + + protected static final String CHECKIN_ACTION = "Checkin"; + protected static final String CHECKOUT_ACTION = "Checkout"; + protected static final String UNDO_CHECKOUT_ACTION = "UndoCheckout"; + + protected Product expectedProduct; + + public ProductLifecycleTest(TestName testName, String className) { + super(testName, className); + } + + @BeforeMethod + public void init() throws Exception { + ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories); + RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productManager1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java new file mode 100644 index 0000000000..479dbb9436 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java @@ -0,0 +1,148 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.Before; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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; + +public class ProductTestBase extends ProductBaseTest { + + public ProductTestBase(TestName testName, String className) { + super(testName, className); + } + + protected ResourceReqDetails downloadResourceDetails; + protected ServiceReqDetails serviceDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails; + protected User sdncUserDetails; + protected ArtifactReqDetails heatArtifactDetails; + protected ArtifactReqDetails defaultArtifactDetails; + protected ResourceUtils resourceUtils; + protected ArtifactUtils artifactUtils; + protected Resource resource; + protected Service service; + protected Product product; + + // protected static ServiceUtils serviceUtils = new ServiceUtils(); + + @Before + public void before() throws Exception { + + initializeMembers(); + createComponents(); + + } + + public void initializeMembers() throws IOException, Exception { + + downloadResourceDetails = ElementFactory.getDefaultResource(); + serviceDetails = ElementFactory.getDefaultService(); + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + + } + + protected void createComponents() throws Exception { + + RestResponse response = ResourceRestUtils.createResource(downloadResourceDetails, sdncUserDetails); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", downloadResourceDetails.getUniqueId()); + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncUserDetails, + downloadResourceDetails.getUniqueId()); + assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + // certified resource + response = LifecycleRestUtils.certifyResource(downloadResourceDetails); + assertTrue("certify resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + response = ResourceRestUtils.getResource(downloadResourceDetails.getUniqueId()); + assertTrue("response code is not 200, returned: " + response.getErrorCode(), response.getErrorCode() == 200); + resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + + response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId()); + + // add resource instance with HEAT deployment artifact to the service + resourceInstanceReqDetails.setComponentUid(downloadResourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncUserDetails, + serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201); + + // certified service + response = LifecycleRestUtils.certifyService(serviceDetails); + assertTrue("certify service request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + response = ServiceRestUtils.getService(serviceDetails, sdncUserDetails); + assertTrue("response code is not 200, returned: " + response.getErrorCode(), response.getErrorCode() == 200); + service = ResponseParser.convertServiceResponseToJavaObject(response.getResponse()); + + DbUtils.cleanAllAudits(); + + ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories); + RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productStrategistUser1); + assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, + createProduct.getErrorCode().intValue()); + product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class); + + // add service instance to product + // + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java new file mode 100644 index 0000000000..412e6fd92d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java @@ -0,0 +1,83 @@ +/*- + * ============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.ci.tests.execute.product; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.ArtifactUiDownloadData; +import org.openecomp.sdc.ci.tests.utils.Decoder; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class ProductToscaYamlGenerationTest extends ProductTestBase { + + @Rule + public static TestName name = new TestName(); + + public ProductToscaYamlGenerationTest() { + super(name, ProductToscaYamlGenerationTest.class.getName()); + } + + @Test + public void productToscaYamlFormat() throws IOException { + + String heatEnvArtifactHeader = (String) Utils.parseYamlConfig("heatEnvArtifactHeader"); + // System.out.println("heatEnvArtifactHeader = \n" + + // heatEnvArtifactHeader); + + String heatEnvArtifactFooter = (String) Utils.parseYamlConfig("heatEnvArtifactFooter"); + // System.out.println("heatEnvArtifactFooter = \n" + + // heatEnvArtifactFooter); + + // temporary commented + // RestResponse downloadResourceInstanceHeatArtifact = + // ArtifactRestUtils.downloadResourceInstanceArtifact(service.getUniqueId(), + // resourceInstanceId, sdncUserDetails, + // heatArtifactDefinition.getUniqueId()); + // assertTrue("expected request returned status:" + 200 + ", actual: " + + // downloadResourceInstanceHeatArtifact.getErrorCode(), + // downloadResourceInstanceHeatArtifact.getErrorCode()==200); + + // InputStream stream = + // getDecodedSteramFromString(downloadResourceInstanceHeatArtifact.getResponse()); + // System.out.println(Utils.getParamValueFromYamlByKey(stream, + // "description", String.class)); + + // node_types + + } + + private InputStream getDecodedSteramFromString(String encoded64Payload) throws IOException { + + Gson gson = new Gson(); + ArtifactUiDownloadData artifactUiDownloadData = gson.fromJson(encoded64Payload, ArtifactUiDownloadData.class); + String decodedPayload = Decoder.decode(artifactUiDownloadData.getBase64Contents()); + return new ByteArrayInputStream(decodedPayload.getBytes()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java new file mode 100644 index 0000000000..d4bfb62377 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java @@ -0,0 +1,216 @@ +/*- + * ============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.ci.tests.execute.product; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNull; + +import java.io.FileNotFoundException; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class ProductUndoCheckoutTest extends ProductLifecycleTest { + + @Rule + public static TestName name = new TestName(); + + @BeforeClass + public static void staticInit() { + auditAction = UNDO_CHECKOUT_ACTION; + operation = ComponentOperationEnum.CHANGE_STATE_UNDO_CHECKOUT; + } + + public ProductUndoCheckoutTest() { + super(name, ProductUndoCheckoutTest.class.getName()); + } + + @Test + public void undoCheckOutProductByPm() throws Exception { + undoCheckOutProductSuccess(productManager1, false); + } + + @Test + public void undoCheckOutProductByAdmin() throws Exception { + undoCheckOutProductSuccess(adminUser, true); + } + + @Test + public void undoCheckOutAfterCreate() throws Exception { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals("Check response code after undo checkout product", 200, lcsResponse.getErrorCode().intValue()); + + // Verify version was removed + lcsResponse = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), productManager1.getUserId()); + assertEquals("Check response code after get undone product", 404, lcsResponse.getErrorCode().intValue()); + + Product emptyProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + assertNull(emptyProduct); + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(emptyProduct, + auditAction, productManager1, ActionStatus.OK, "0.1", Constants.EMPTY_STRING, + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null, Constants.EMPTY_STRING); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + + } + + @Test + public void undoCheckOutNotExist() throws Exception { + String notExistId = "1234"; + expectedProduct.setUniqueId(notExistId); + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals("Check response code after undo checkout product", 404, lcsResponse.getErrorCode().intValue()); + expectedProduct.setName(notExistId); + String[] auditParameters = new String[] { Constants.EMPTY_STRING }; + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, productManager1, ActionStatus.PRODUCT_NOT_FOUND, Constants.EMPTY_STRING, + Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, auditParameters); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + + } + + @Test + public void undoCheckOutNotInCheckout() throws Exception { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals("Check response code after undo checkout product", 409, lcsResponse.getErrorCode().intValue()); + + String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(), + productManager1.getLastName(), productManager1.getUserId() }; + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, productManager1, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, "0.1", "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + expectedProduct.getUUID(), auditParameters); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + + } + + @Test + public void undoCheckOutProductByPsRoleNotAllowed() throws Exception { + undoCheckOutProductRestricted(productStrategistUser1); + } + + @Test + public void undoCheckOutProductByPmNotStateOwner() throws Exception { + undoCheckOutProductForbidden(productManager2); + } + + private void undoCheckOutProductSuccess(User user, boolean isAdmin) throws Exception, FileNotFoundException { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); + + // Checking undo checkout of admin even if not state owner + User checkoutUser = isAdmin ? productManager1 : user; + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue()); + Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + + lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, user, LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals("Check response code after undo checkout product", 200, lcsResponse.getErrorCode().intValue()); + + // Verify version was removed + lcsResponse = ProductRestUtils.getProduct(productToBeUndone.getUniqueId(), user.getUserId()); + assertEquals("Check response code after get undone product", 404, lcsResponse.getErrorCode().intValue()); + + lcsResponse = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), user.getUserId()); + assertEquals("Check response code after get latest version", 200, lcsResponse.getErrorCode().intValue()); + + Product latestProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + + expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, latestProduct, operation); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(latestProduct, + auditAction, user, ActionStatus.OK, "0.2", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, latestProduct.getUUID()); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + private void undoCheckOutProductRestricted(User undoCheckoutUser) throws Exception, FileNotFoundException { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue()); + Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + + lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, undoCheckoutUser, + LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals("Check response code after undocheckout product", 409, lcsResponse.getErrorCode().intValue()); + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(productToBeUndone, + auditAction, undoCheckoutUser, ActionStatus.RESTRICTED_OPERATION, "0.2", "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + productToBeUndone.getUUID()); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + + private void undoCheckOutProductForbidden(User undoCheckoutUser) throws Exception, FileNotFoundException { + RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue()); + + lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, + LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue()); + Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class); + + lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, undoCheckoutUser, + LifeCycleStatesEnum.UNDOCHECKOUT); + assertEquals("Check response code after undocheckout product", 403, lcsResponse.getErrorCode().intValue()); + String[] auditParameters = new String[] { productToBeUndone.getName(), "product", + productManager1.getFirstName(), productManager1.getLastName(), productManager1.getUserId() }; + + ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, + auditAction, undoCheckoutUser, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, "0.2", "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + productToBeUndone.getUUID(), auditParameters); + AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java new file mode 100644 index 0000000000..1cf16978e4 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java @@ -0,0 +1,2021 @@ +/*- + * ============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.ci.tests.execute.property; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +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 org.json.simple.parser.JSONParser; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.AdditionalInformationDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; +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.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.resource.ResourceApiTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.ComponentInstanceRestUtils; +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.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +public class AdditionalInformationServletTest extends ComponentBaseTest { + + protected Type constraintType = new TypeToken() { + }.getType(); + + protected Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + + @Rule + public static TestName name = new TestName(); + + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + protected JSONParser jsonParser = new JSONParser(); + + public AdditionalInformationServletTest() { + super(name, AdditionalInformationServletTest.class.getName()); + } + + // @Before + // public void deleteResources() { + // //TODO Evg : will be new API added for delete by name and version + // + // ResourceReqDetails resource = getResource(); + // User user = getUser(); + // + // try { + // String resourceName = resource.getResourceName(); + // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName, + // "0.1"); + // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName, + // "0.2"); + // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName, + // "1.0"); + // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName, + // "1.1"); + // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName + + // "aa", "0.1"); + // resourceUtils.deleteResource_allVersions(resource, user); + // + // } catch (IOException e) { + // assertTrue(false); + // } + // + // try { + // ServiceReqDetails serviceDetails = getServiceDetails(); + // + // RestResponse deleteServiceResponse = + // serviceUtils.deleteServiceByNameAndVersion(UserUtils.getAdminDetails(), + // serviceDetails.getServiceName(), "0.1"); + // + // assertNotNull("check response object is not null after delete + // service",deleteServiceResponse); + // assertNotNull("check error code exists in response after delete + // service",deleteServiceResponse.getErrorCode()); + // assertTrue("delete service failed status:" + + // deleteServiceResponse.getErrorCode(), + // deleteServiceResponse.getErrorCode() != 500); + // + // deleteServiceResponse = + // serviceUtils.deleteServiceByNameAndVersion(UserUtils.getAdminDetails(), + // serviceDetails.getServiceName(), "1.0"); + // + // assertNotNull("check response object is not null after delete + // service",deleteServiceResponse); + // assertNotNull("check error code exists in response after delete + // service",deleteServiceResponse.getErrorCode()); + // assertTrue("delete service failed status:" + + // deleteServiceResponse.getErrorCode(), + // deleteServiceResponse.getErrorCode() != 500); + // + // serviceUtils.deleteService_allVersions(serviceDetails, user); + // + // } catch (IOException e) { + // assertTrue(false); + // } + // } + + @Test + public void updateResourceAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + AssertJUnit.assertNotNull("check response object is not null after create resource", createResourceResponse); + AssertJUnit.assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + String updatedKey = "ZZZ ZZZ"; + String updatedValue = "JJJJ"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + AssertJUnit.assertNotNull("check response object is not null after create property", createProperty); + AssertJUnit.assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + AssertJUnit.assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + AssertJUnit.assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + fromJson.setKey(updatedKey); + fromJson.setValue(updatedValue); + + RestResponse updatedProperty = updateAdditionalInformation(resourceId, fromJson, user, fromJson.getUniqueId()); + AssertJUnit.assertNotNull("check response object is not null after update additional information", updatedProperty); + AssertJUnit.assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode()); + AssertJUnit.assertEquals("Check response code after additional information", 200, updatedProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo updatedJson = gson.fromJson(updatedProperty.getResponse(), AdditionalInfoParameterInfo.class); + AssertJUnit.assertFalse("check number of spaces", updatedJson.getKey().contains(" ")); + AssertJUnit.assertEquals("check returned key", "ZZZ ZZZ", updatedJson.getKey()); + AssertJUnit.assertEquals("check returned value", updatedValue, updatedJson.getValue()); + AssertJUnit.assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId()); + + } + + @Test + public void deleteResourceAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + AssertJUnit.assertNotNull("check response object is not null after create resource", createResourceResponse); + AssertJUnit.assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + AssertJUnit.assertNotNull("check response object is not null after create property", createProperty); + AssertJUnit.assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + AssertJUnit.assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + AssertJUnit.assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + RestResponse deletedProperty = deleteAdditionalInformation(resourceId, fromJson.getUniqueId(), user); + AssertJUnit.assertNotNull("check response object is not null after update additional information", deletedProperty); + AssertJUnit.assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + AssertJUnit.assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class); + AssertJUnit.assertFalse("check number of spaces", updatedJson.getKey().contains(" ")); + AssertJUnit.assertEquals("check returned key", "AAA AAA", updatedJson.getKey()); + AssertJUnit.assertEquals("check returned value", value, updatedJson.getValue()); + AssertJUnit.assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId()); + + deletedProperty = deleteAdditionalInformation(resourceId, fromJson.getUniqueId(), user); + AssertJUnit.assertNotNull("check response object is not null after update additional information", deletedProperty); + AssertJUnit.assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + AssertJUnit.assertEquals("Check response code after additional information", 409, deletedProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceAdditionalInformationTestDuringLifecycle() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + AssertJUnit.assertNotNull("check response object is not null after create resource", createResourceResponse); + AssertJUnit.assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + AssertJUnit.assertNotNull("check response object is not null after create property", createProperty); + AssertJUnit.assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + AssertJUnit.assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + AssertJUnit.assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + resource.setUniqueId(resourceId); + + // resourceUtils.addResourceMandatoryArtifacts(user, + // createResourceResponse); + + certifyResource(user, resource, null, 1); + + } + + public RestResponse createService() { + + User user = getUser(); + ServiceReqDetails serviceDetails = getServiceDetails(); + + RestResponse createServiceResponse = null; + try { + createServiceResponse = ServiceRestUtils.createService(serviceDetails, user); + AssertJUnit.assertNotNull("check response object is not null after create user", createServiceResponse); + AssertJUnit.assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after checkout resource", 201, createServiceResponse.getErrorCode().intValue()); + } catch (Exception e) { + AssertJUnit.assertTrue(false); + } + + return createServiceResponse; + + } + + protected User getUser() { + String adminFirstName = "Jimmy"; + String adminLastName = "Hendrix"; + String adminUserId = "jh0003"; + return new User(adminFirstName, adminLastName, adminUserId, null, null, null); + } + + protected ResourceReqDetails getResource() { + String resourceName = "ciResourceforproperty4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "pe0123"; + String icon = "myICON"; + ResourceReqDetails resource = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon); + resource.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); + return resource; + } + + protected RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws IOException { + + ResourceApiTest rat = new ResourceApiTest(); + ResourceReqDetails resourceObj = rat.getResourceObj(); + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + + return createResourceResponse; + + } + + protected RestResponse getResource(User sdncModifierDetails, String resourceUid) throws IOException { + + ResourceApiTest rat = new ResourceApiTest(); + ResourceReqDetails resourceObj = rat.getResourceObj(); + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid); + RestResponse createResourceResponse = http.httpSendGet(url, headersMap); + + return createResourceResponse; + + } + + protected RestResponse deleteResource(String resourceName, String resourceVersion, User sdncModifierDetails) throws IOException { + RestResponse deleteResourceResponse = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceName, resourceVersion); + + return deleteResourceResponse; + + } + + protected RestResponse updateAdditionalInformation(String resourceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails, String id) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String body = gson.toJson(additionalInfo); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id); + return http.httpSendPut(url, body, headersMap); + + } + + protected RestResponse updateServiceAdditionalInformation(String resourceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails, String id) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String body = gson.toJson(additionalInfo); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id); + return http.httpSendPut(url, body, headersMap); + + } + + protected RestResponse deleteAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.DELETE_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id); + return http.httpSendDelete(url, headersMap); + + } + + protected RestResponse deleteServiceAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.DELETE_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id); + return http.httpSendDelete(url, headersMap); + + } + + protected RestResponse getAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id); + return http.httpSendGet(url, headersMap); + + } + + protected RestResponse getServiceAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id); + return http.httpSendGet(url, headersMap); + + } + + protected RestResponse getResourceAllAdditionalInformation(String resourceId, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + return http.httpSendGet(url, headersMap); + + } + + protected RestResponse getServiceAllAdditionalInformation(String resourceId, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + return http.httpSendGet(url, headersMap); + + } + + protected RestResponse createResourceAdditionalInformation(String resourceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String body = gson.toJson(additionalInfo); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + return http.httpSendPost(url, body, headersMap); + + } + + protected RestResponse createServiceAdditionalInformation(String serviceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String body = gson.toJson(additionalInfo); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + return http.httpSendPost(url, body, headersMap); + + } + + protected ServiceReqDetails getServiceDetails() { + String serviceName = "ciNewTestService21"; + String category = ServiceCategoriesEnum.MOBILITY.getValue(); + ArrayList tags = new ArrayList(); + tags.add("serviceTag"); + tags.add(serviceName); + String description = "service Description"; + String vendorName = "Oracle"; + String vendorRelease = "0.1"; + String contactId = "al1976"; + String icon = "myIcon"; + + return new ServiceReqDetails(serviceName, category, tags, description, contactId, icon); + } + + // TODO Tal: Since Cashing change partial resource returned that causes null + // pointer exception in line: + // commented out till fixing + protected Resource certifyResource(User user, ResourceReqDetails resource, String resourceVersion, int numberOfAI) throws IOException { + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN); + + AssertJUnit.assertNotNull("check response object is not null after create user", checkInResponse); + AssertJUnit.assertNotNull("check error code exists in response after create user", checkInResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create user", 200, checkInResponse.getErrorCode().intValue()); + + Resource resourceAfterOperation = gson.fromJson(checkInResponse.getResponse(), Resource.class); + // TODO Tal: Since Cashing change partial resource returned that causes + // null pointer exception + /* + * AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + */ + /* + * AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0). getParameters().size()); + */ + + RestResponse req4certResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + + AssertJUnit.assertNotNull("check response object is not null after create user", req4certResponse); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, req4certResponse.getErrorCode().intValue()); + + resourceAfterOperation = gson.fromJson(req4certResponse.getResponse(), Resource.class); + // TODO Tal: Since Cashing change partial resource returned that causes + // null pointer exception + /* + * AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + */ + /* + * AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0). getParameters().size()); + */ + + // change modifier + user.setUserId(UserRoleEnum.TESTER.getUserId()); + // start certification + + RestResponse startCertResourceResponse3 = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + AssertJUnit.assertNotNull("check response object is not null after create user", startCertResourceResponse3); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, startCertResourceResponse3.getErrorCode().intValue()); + + resourceAfterOperation = gson.fromJson(startCertResourceResponse3.getResponse(), Resource.class); + // TODO Tal: Since Cashing change partial resource returned that causes + // null pointer exception + /* + * AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + */ + /* + * AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0). getParameters().size()); + */ + + // certify + + RestResponse certifyResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFY); + AssertJUnit.assertNotNull("check response object is not null after create user", certifyResponse); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, certifyResponse.getErrorCode().intValue()); + + resourceAfterOperation = gson.fromJson(certifyResponse.getResponse(), Resource.class); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + + Resource certifyResource = gson.fromJson(certifyResponse.getResponse(), Resource.class); + return certifyResource; + } + + protected Resource certifyService(User user, ServiceReqDetails service, String resourceVersion) throws Exception { + RestResponse checkInResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKIN); + + AssertJUnit.assertNotNull("check response object is not null after create user", checkInResponse); + AssertJUnit.assertNotNull("check error code exists in response after create user", checkInResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create user", 200, checkInResponse.getErrorCode().intValue()); + + Resource resourceAfterOperation = gson.fromJson(checkInResponse.getResponse(), Resource.class); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + + RestResponse req4certResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + + AssertJUnit.assertNotNull("check response object is not null after create user", req4certResponse); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, req4certResponse.getErrorCode().intValue()); + + resourceAfterOperation = gson.fromJson(req4certResponse.getResponse(), Resource.class); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + + // change modifier + user.setUserId(UserRoleEnum.TESTER.getUserId()); + // start certification + + RestResponse startCertResourceResponse3 = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + AssertJUnit.assertNotNull("check response object is not null after create user", startCertResourceResponse3); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, startCertResourceResponse3.getErrorCode().intValue()); + + resourceAfterOperation = gson.fromJson(startCertResourceResponse3.getResponse(), Resource.class); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + + // certify + + RestResponse certifyResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CERTIFY); + AssertJUnit.assertNotNull("check response object is not null after create user", certifyResponse); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, certifyResponse.getErrorCode().intValue()); + + resourceAfterOperation = gson.fromJson(certifyResponse.getResponse(), Resource.class); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + + Resource certifyResource = gson.fromJson(certifyResponse.getResponse(), Resource.class); + return certifyResource; + } + + @Test + public void createResourceAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceAdditionalInfoFormatWithTags() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "Bold<"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertEquals("check returned key", "Bold&lt;", fromJson.getValue()); + + } + + @Test + public void createServiceAdditionalInfoFormatWithTags() throws Exception { + User user = getUser(); + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + assertNotNull("check response object is not null after create resource", createServiceResponse); + assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createServiceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "Bold<"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertEquals("check returned key", "Bold&lt;", fromJson.getValue()); + + } + + @Test + public void createResourceAdditionalInfoFormatWithWhiteSpaces() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = " "; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + key = " "; + value = "AAA AAA"; + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceAdditionalInfoFormatWithWhiteSpaces() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + assertNotNull("check response object is not null after create resource", createServiceResponse); + assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createServiceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = " "; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + key = " "; + value = "AAA AAA"; + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceAndUpdateAdditionalInfo() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + key = "BBB BBB"; + value = "BBBB"; + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "BBB BBB", fromJson.getKey()); + + String updatedKey = "AAA AAA"; + String updatedValue = "JJJJ"; + + fromJson.setKey(updatedKey); + fromJson.setValue(updatedValue); + + RestResponse updatedProperty = updateAdditionalInformation(resourceId, fromJson, user, fromJson.getUniqueId()); + assertNotNull("check response object is not null after update additional information", updatedProperty); + assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 409, updatedProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceEmptyAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = ""; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + key = "BBBB"; + value = ""; + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceEmptyAdditionalInformationTest() throws Exception { + + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = ""; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceAllSpacesAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = " "; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceAllSpacesAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = " "; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceInvalidKeyAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "abc?"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceInvalidKeyAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "abc?"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceAdditionalInformationNullKeyTest() throws Exception { + + User user = getUser(); + ResourceReqDetails resource = getResource(); + + RestResponse createResourceResponse = createResource(resource, user); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + String key = null; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceAdditionalInformationNullKeyTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = null; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceMaximumInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + for (int i = 0; i < 50; i++) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + } + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceLifeCycleAndMaximumInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + resource.setUniqueId(resourceId); + + String key = "AAA AAA"; + String value = "BBBB"; + + for (int i = 0; i < 49; i++) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + } + + String resourceVersion = "0.1"; + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + + assertNotNull("check response object is not null after create property", checkInResponse); + assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode()); + assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue()); + + resourceVersion = "0.2"; + + RestResponse checkOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null); + + resourceId = ResponseParser.getUniqueIdFromResponse(checkOutResponse); + resource.setUniqueId(resourceId); + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value); + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value); + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + RestResponse checkUndoOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.UNDOCHECKOUT, null); + + resourceVersion = "0.1"; + + checkOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null); + resourceId = ResponseParser.getUniqueIdFromResponse(checkOutResponse); + resource.setUniqueId(resourceId); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value); + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value); + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createResourceLifeCycleCertifyAndMaximumInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + resource.setUniqueId(resourceId); + + String key = "AAA AAA"; + String value = "BBBB"; + + for (int i = 0; i < 49; i++) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + } + + String resourceVersion = "0.1"; + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + + // resourceUtils.addResourceMandatoryArtifacts(user, + // createResourceResponse); + + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + + assertNotNull("check response object is not null after create property", checkInResponse); + assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode()); + assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue()); + + RestResponse changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST, null); + changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION, null); + changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFY, null); + + assertNotNull("check response object is not null after create property", checkInResponse); + assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode()); + assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue()); + + resourceId = ResponseParser.getUniqueIdFromResponse(changeStateResponse); + resource.setUniqueId(resourceId); + + resourceVersion = "1.0"; + + changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null); + resourceId = ResponseParser.getUniqueIdFromResponse(changeStateResponse); + resource.setUniqueId(resourceId); + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value); + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value); + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceCycleAndMaximumInformationTest() throws Exception { + + User user = getUser(); + + ServiceReqDetails service = getServiceDetails(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + assertNotNull("check response object is not null after create resource", createServiceResponse); + assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createServiceResponse.getErrorCode().intValue()); + + service.setUniqueId(serviceId); + + String key = "AAA AAA"; + String value = "BBBB"; + + for (int i = 0; i < 49; i++) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + } + + String resourceVersion = "0.1"; + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + RestResponse checkInResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson); + + assertNotNull("check response object is not null after create property", checkInResponse); + assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode()); + assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue()); + + resourceVersion = "0.2"; + + RestResponse checkOutResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null); + + serviceId = ResponseParser.convertServiceResponseToJavaObject(checkOutResponse.getResponse()).getUniqueId(); + service.setUniqueId(serviceId); + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value); + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value); + createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + RestResponse checkUndoOutResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.UNDOCHECKOUT, null); + + resourceVersion = "0.1"; + + checkOutResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null); + serviceId = ResponseParser.convertServiceResponseToJavaObject(checkOutResponse.getResponse()).getUniqueId(); + service.setUniqueId(serviceId); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value); + createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value); + createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + } + + @Test + public void createServiceMaximumInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "AAA AAA"; + String value = "BBBB"; + + String lastCreatedProperty = null; + + for (int i = 0; i < 50; i++) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + lastCreatedProperty = fromJson.getUniqueId(); + + } + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue()); + + RestResponse deletedProperty = deleteServiceAdditionalInformation(serviceId, lastCreatedProperty, user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + } + + @Test + public void updateServiceAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "AAA AAA"; + String value = "BBBB"; + + String updatedKey = "ZZZ ZZZ"; + String updatedValue = "JJJJ"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + fromJson.setKey(updatedKey); + fromJson.setValue(updatedValue); + + RestResponse updatedProperty = updateServiceAdditionalInformation(serviceId, fromJson, user, fromJson.getUniqueId()); + assertNotNull("check response object is not null after update additional information", updatedProperty); + assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, updatedProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo updatedJson = gson.fromJson(updatedProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", updatedJson.getKey().contains(" ")); + assertEquals("check returned key", "ZZZ ZZZ", updatedJson.getKey()); + assertEquals("check returned value", updatedValue, updatedJson.getValue()); + assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId()); + + fromJson.setKey(updatedKey); + fromJson.setValue("\uC2B5"); + + updatedProperty = updateServiceAdditionalInformation(serviceId, fromJson, user, fromJson.getUniqueId()); + assertNotNull("check response object is not null after update additional information", updatedProperty); + assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 400, updatedProperty.getErrorCode().intValue()); + + } + + @Test + public void deleteServiceAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + RestResponse deletedProperty = deleteServiceAdditionalInformation(serviceId, fromJson.getUniqueId(), user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", updatedJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", updatedJson.getKey()); + assertEquals("check returned value", value, updatedJson.getValue()); + assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId()); + + deletedProperty = deleteServiceAdditionalInformation(serviceId, fromJson.getUniqueId(), user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 409, deletedProperty.getErrorCode().intValue()); + + } + + @Test + public void getResourceAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + RestResponse deletedProperty = getAdditionalInformation(resourceId, fromJson.getUniqueId(), user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", updatedJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", updatedJson.getKey()); + assertEquals("check returned value", value, updatedJson.getValue()); + assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId()); + + } + + @Test + public void getServiceAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + RestResponse deletedProperty = getServiceAdditionalInformation(serviceId, fromJson.getUniqueId(), user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", updatedJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", updatedJson.getKey()); + assertEquals("check returned value", value, updatedJson.getValue()); + assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId()); + + } + + @Test + public void getResourceAllAdditionalInformationTest() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + RestResponse deletedProperty = getResourceAllAdditionalInformation(resourceId, user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + AdditionalInformationDefinition updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInformationDefinition.class); + assertEquals("check number of parameters", 1, updatedJson.getParameters().size()); + AdditionalInfoParameterInfo info = updatedJson.getParameters().iterator().next(); + + assertFalse("check number of spaces", info.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", info.getKey()); + assertEquals("check returned value", value, info.getValue()); + assertEquals("check returned id", fromJson.getUniqueId(), info.getUniqueId()); + + } + + @Test + public void getServiceAllAdditionalInformationTest() throws Exception { + User user = getUser(); + + RestResponse createServiceResponse = createService(); + + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + RestResponse deletedProperty = getServiceAllAdditionalInformation(serviceId, user); + assertNotNull("check response object is not null after update additional information", deletedProperty); + assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode()); + assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue()); + + AdditionalInformationDefinition updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInformationDefinition.class); + assertEquals("check number of parameters", 1, updatedJson.getParameters().size()); + AdditionalInfoParameterInfo info = updatedJson.getParameters().iterator().next(); + + assertFalse("check number of spaces", info.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", info.getKey()); + assertEquals("check returned value", value, info.getValue()); + assertEquals("check returned id", fromJson.getUniqueId(), info.getUniqueId()); + + } + + @Test + public void createServiceAdditionalInformationTestDuringLifecycle() throws Exception { + + User user = getUser(); + RestResponse createServiceResponse = createService(); + String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId(); + String key = "AAA AAA"; + String value = "BBBB"; + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class); + assertFalse("check number of spaces", fromJson.getKey().contains(" ")); + assertEquals("check returned key", "AAA AAA", fromJson.getKey()); + + ServiceReqDetails serviceDetails = getServiceDetails(); + + serviceDetails.setUniqueId(serviceId); + + // serviceUtils.addServiceMandatoryArtifacts(user, + // createServiceResponse); + + certifyService(user, serviceDetails, null); + + } + + @Test + public void createCascadeResource() { + + // TODO: to check after rebase + + User user = getUser(); + ResourceReqDetails resource = getResource(); + String newResourceNameSuffix = "aa"; + + RestResponse createResourceResponse = null; + try { + + createResourceResponse = createResource(resource, user); + assertEquals("check invalid type", 201, createResourceResponse.getErrorCode().intValue()); + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + String resourceVersion = "0.1"; + // resourceUtils.addResourceMandatoryArtifacts(user, + // createResourceResponse); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + resource.setUniqueId(resourceId); + Resource certifiedResource = certifyResource(user, resource, resourceVersion, 1); + + ResourceReqDetails newResourceDetails = getResource(); + String newResourceName = newResourceDetails.getName() + newResourceNameSuffix; + newResourceDetails.setName(newResourceName); + List derivedFrom = new ArrayList<>(); + derivedFrom.add(certifiedResource.getName()); + newResourceDetails.setDerivedFrom(derivedFrom); + newResourceDetails.getTags().add(newResourceName); + + user.setUserId(UserRoleEnum.ADMIN.getUserId()); + RestResponse newCreateResourceResponse = createResource(newResourceDetails, user); + assertEquals("Check response code after creating resource", 201, newCreateResourceResponse.getErrorCode().intValue()); + Resource newResource = gson.fromJson(newCreateResourceResponse.getResponse(), Resource.class); + + RestResponse allAdditionalInformation = getResourceAllAdditionalInformation(newResource.getUniqueId(), user); + + assertNotNull("check response object is not null after update additional information", allAdditionalInformation); + assertNotNull("check error code exists in response after additional information", allAdditionalInformation.getErrorCode()); + assertEquals("Check response code after additional information", 200, allAdditionalInformation.getErrorCode().intValue()); + + AdditionalInformationDefinition updatedJson = gson.fromJson(allAdditionalInformation.getResponse(), AdditionalInformationDefinition.class); + assertEquals("check number of parameters", 0, updatedJson.getParameters().size()); + // AdditionalInfoParameterInfo info = + // updatedJson.getParameters().iterator().next(); + + String newResourceId = newResource.getUniqueId(); + createProperty = createResourceAdditionalInformation(newResourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + allAdditionalInformation = getResourceAllAdditionalInformation(newResourceId, user); + + assertNotNull("check response object is not null after update additional information", allAdditionalInformation); + assertNotNull("check error code exists in response after additional information", allAdditionalInformation.getErrorCode()); + assertEquals("Check response code after additional information", 200, allAdditionalInformation.getErrorCode().intValue()); + + updatedJson = gson.fromJson(allAdditionalInformation.getResponse(), AdditionalInformationDefinition.class); + assertEquals("check number of parameters", 1, updatedJson.getParameters().size()); + + } catch (IOException e) { + assertTrue(false); + } + + } + + @Test + public void createSamePropertyAfterCiCOResource() { + + User user = getUser(); + ResourceReqDetails resource = getResource(); + + RestResponse createResourceResponse = null; + try { + + createResourceResponse = createResource(resource, user); + assertEquals("check invalid type", 201, createResourceResponse.getErrorCode().intValue()); + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + String resourceVersion = "0.1"; + // resourceUtils.addResourceMandatoryArtifacts(user, + // createResourceResponse); + + String key = "AAA AAA"; + String value = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + resource.setUniqueId(resourceId); + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN); + + assertNotNull("check response object is not null after create user", checkInResponse); + assertNotNull("check error code exists in response after create user", checkInResponse.getErrorCode()); + assertEquals("Check response code after create user", 200, checkInResponse.getErrorCode().intValue()); + + Resource resourceAfterOperation = gson.fromJson(checkInResponse.getResponse(), Resource.class); + assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size()); + assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + + RestResponse checkOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT); + + assertNotNull("check response object is not null after create user", checkOutResponse); + assertNotNull("check error code exists in response after create user", checkOutResponse.getErrorCode()); + assertEquals("Check response code after create user", 200, checkOutResponse.getErrorCode().intValue()); + + Resource resourceAfterCoOperation = gson.fromJson(checkOutResponse.getResponse(), Resource.class); + assertEquals("check size of additional information", 1, resourceAfterCoOperation.getAdditionalInformation().size()); + assertEquals("check size of additional information", 1, resourceAfterCoOperation.getAdditionalInformation().get(0).getParameters().size()); + + String newResourceId = ResponseParser.getUniqueIdFromResponse(checkOutResponse); + + String key2 = "ZZZ"; + String value2 = "BBBB"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo2 = new AdditionalInfoParameterInfo(null, key2, value2); + + RestResponse createProperty2 = createResourceAdditionalInformation(newResourceId, additionalInfoParameterInfo2, user); + assertNotNull("check response object is not null after create property", createProperty2); + assertNotNull("check error code exists in response after create property", createProperty2.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty2.getErrorCode().intValue()); + + RestResponse afterCreateAI = ResourceRestUtils.getResource(user, newResourceId); + Resource resourceNew = gson.fromJson(afterCreateAI.getResponse(), Resource.class); + assertEquals("check size of additional information", 1, resourceNew.getAdditionalInformation().size()); + assertEquals("check size of additional information", 2, resourceNew.getAdditionalInformation().get(0).getParameters().size()); + + resource.setUniqueId(newResourceId); + Resource certifiedResource = certifyResource(user, resource, resourceVersion, 2); + assertEquals("check size of additional information", 1, certifiedResource.getAdditionalInformation().size()); + assertEquals("check size of additional information", 2, certifiedResource.getAdditionalInformation().get(0).getParameters().size()); + + user.setUserId(UserRoleEnum.DESIGNER.getUserId()); + resource.setUniqueId(certifiedResource.getUniqueId()); + RestResponse checkOutResponseAfterCertify = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT); + + assertNotNull("check response object is not null after create user", checkOutResponseAfterCertify); + assertNotNull("check error code exists in response after create user", checkOutResponseAfterCertify.getErrorCode()); + assertEquals("Check response code after create user", 200, checkOutResponseAfterCertify.getErrorCode().intValue()); + + Resource resourceAfterCertifyCoOperation = gson.fromJson(checkOutResponseAfterCertify.getResponse(), Resource.class); + assertEquals("check size of additional information", 1, resourceAfterCertifyCoOperation.getAdditionalInformation().size()); + assertEquals("check size of additional information", 2, resourceAfterCertifyCoOperation.getAdditionalInformation().get(0).getParameters().size()); + + } catch (IOException e) { + assertTrue(false); + } + + } + + // public Resource certifyService(User user, ServiceReqDetails service, + // String resourceVersion) throws Exception { + // + // RestResponse checkInResponse = + // LifecycleRestUtils.changeServiceState(service, user, resourceVersion, + // LifeCycleStates.CHECKIN); + // + // assertNotNull("check response object is not null after create user", + // checkInResponse); + // assertNotNull("check error code exists in response after create user", + // checkInResponse.getErrorCode()); + // assertEquals("Check response code after create user", 200, + // checkInResponse.getErrorCode().intValue()); + // + // Resource resourceAfterOperation = + // gson.fromJson(checkInResponse.getResponse(), Resource.class); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().size()); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + // + //// TODO Andrey + // createAndAddCertResourceToService(service, user); + // + // RestResponse req4certResponse = + // LifecycleRestUtils.changeServiceState(service, user, resourceVersion, + // LifeCycleStates.CERTIFICATIONREQUEST); + // + // assertNotNull("check response object is not null after create user", + // req4certResponse); + // assertEquals("Check response code after checkout resource", 200, + // req4certResponse.getErrorCode().intValue()); + // + // resourceAfterOperation = gson.fromJson(req4certResponse.getResponse(), + // Resource.class); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().size()); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + // + // //change modifier + // user.setUserId(UserRoleEnum.TESTER.getUserId()); + // + // //start certification + // RestResponse startCertResourceResponse3 = + // LifecycleRestUtils.changeServiceState(service, user, resourceVersion, + // LifeCycleStates.STARTCERTIFICATION); + // assertNotNull("check response object is not null after create user", + // startCertResourceResponse3); + // assertEquals("Check response code after checkout resource", 200, + // startCertResourceResponse3.getErrorCode().intValue()); + // + // resourceAfterOperation = + // gson.fromJson(startCertResourceResponse3.getResponse(), Resource.class); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().size()); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + // + // //certify + // + // RestResponse certifyResponse = + // LifecycleRestUtils.changeServiceState(service, user, resourceVersion, + // LifeCycleStates.CERTIFY); + // assertNotNull("check response object is not null after create user", + // certifyResponse); + // assertEquals("Check response code after checkout resource", 200, + // certifyResponse.getErrorCode().intValue()); + // + // resourceAfterOperation = gson.fromJson(certifyResponse.getResponse(), + // Resource.class); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().size()); + // assertEquals("check size of additional information", 1, + // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size()); + // + // Resource certifyResource = gson.fromJson(certifyResponse.getResponse(), + // Resource.class); + // return certifyResource; + // } + + private void createAndAddCertResourceToService(ServiceReqDetails serviceDetails, User user) throws Exception { + + User sdncTesterUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + + RestResponse response = ResourceRestUtils.createResource(resourceDetails, user); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId()); + + ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, user, resourceDetails.getUniqueId()); + assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), response.getErrorCode() == 200); + + // certified resource + // response = LCSbaseTest.certifyResource(resourceDetails); + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, LifeCycleStatesEnum.CHECKIN); + assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200); + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200); + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterUser, LifeCycleStatesEnum.STARTCERTIFICATION); + assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200); + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterUser, LifeCycleStatesEnum.CERTIFY); + assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200); + + // add resource instance with HEAT deployment artifact to the service + restResponseResource = LifecycleRestUtils.changeServiceState(serviceDetails, user, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200); + resourceInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, user, serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201); + } + + @Test + public void createResourceAdditionalInformationTestAddValue() throws Exception { + User user = getUser(); + ResourceReqDetails resource = getResource(); + + // deleteResource(resourceId, user); + RestResponse createResourceResponse = createResource(resource, user); + + String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse); + + assertNotNull("check response object is not null after create resource", createResourceResponse); + assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue()); + + String key = "AAA AAA"; + String value = "\uC2B5"; + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + value = ""; + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue()); + + value = "----<>;"; + + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value); + + createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user); + assertNotNull("check response object is not null after create property", createProperty); + assertNotNull("check error code exists in response after create property", createProperty.getErrorCode()); + assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue()); + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java new file mode 100644 index 0000000000..6ba1b2ccca --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java @@ -0,0 +1,1263 @@ +/*- + * ============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.ci.tests.execute.property; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +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.AtomicOperationUtils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import fj.data.Either; + +// open bug for this class: DE199108 - closed, DE199741 +public class ComponentInstancePropertyTest extends ComponentBaseTest { + + protected Resource basicVFC; + protected Resource vfc1FromBasicVFC; + protected Resource vfc2FromVfc1; + protected Resource vfResource; + + private List expectedPropertyList; + private List actualPropertyList; + // protected String updatedStringValue = "{Not Default String Value}"; + protected String updatedStringValue = "Not Default String Value"; + protected String updatedIntegerValue = "666"; + protected String updatedBooleanValue = "false"; + protected String newStringPropName = "stringProp2"; + protected String newIntegerPropName = "integerProp2"; + protected String newBooleanPropName = "booleanProp2"; + // bug DE199741 protected String newStringPropValue = ""; + protected String newStringPropValue = "second string value"; + protected String newIntegerPropValue = "888"; + protected String newBooleanPropValue = "false"; + + @BeforeMethod + public void init() { + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + } + + @Rule + public static TestName name = new TestName(); + + public ComponentInstancePropertyTest() { + super(name, ComponentInstancePropertyTest.class.getName()); + } + + // --------------Regular + // resource------------------------------------------------------------------------------- + + @Test + public void nestedResourceProperty3Levels() throws Exception { + + // first res + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + // second resource + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + // third resource + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + // verify property + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, actualPropertyList); + assertTrue("check list size failed, expected 3", actualPropertyList.size() == 3); + + } + + // --------------VF + // resource----------------------------------------------------------- + + @Test + public void nestedVfResourceProperty3Levels() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + // verify property + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + } + + @Test + public void nestedVfResourceProperty3LevelsAndCpWithProp() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // four resource + Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, + NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty(); + cpStringProperty.setName("Different Name"); + cpStringProperty.setPropertyDefaultValue("Different value from default"); + AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList); + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, cp, expectedPropertyList, + vfResource); + // verify property + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + } + + @Test + public void nestedCertifiedVfResourceProperty3Levels() throws Exception { + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CERTIFY, vfc1FromBasicVFC); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + // verify property + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + } + + @Test + public void nestedVfResourceProperty3Levels2SameResInstances() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + // verify property + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + } + + // ------------------update resource + // property----------------------------------- + + @Test + public void nestedVfResourceProperty3LevelsUpdateFirstLevelProperty() throws Exception { + // first res + basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + Either propDetailsToUpdate = AtomicOperationUtils + .addDefaultPropertyToResource(PropertyTypeEnum.STRING, basicVFC, UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + + // verify property + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedStringValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(vfResource, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + @Test + public void nestedVfResourceProperty3LevelsUpdateSecondLevelProperty() throws Exception { + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + + // second resource + vfc1FromBasicVFC = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, + basicVFC, ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true).left().value(); + Either propDetailsToUpdate = AtomicOperationUtils + .addCustomPropertyToResource(ElementFactory.getDefaultIntegerProperty(), vfc1FromBasicVFC, + UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(vfc1FromBasicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, + true); + + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + + // verify property + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedIntegerValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(vfResource, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue( + "expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS + + " ,but was " + updatePropertyValueOnResourceInstance.getErrorCode(), + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated properly", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + @Test + public void nestedVfResourceProperty3LevelsUpdateThirdLevelProperty() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + + // third resource + vfc2FromVfc1 = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, + vfc1FromBasicVFC, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value(); + Either propDetailsToUpdate = AtomicOperationUtils + .addCustomPropertyToResource(ElementFactory.getDefaultBooleanProperty(), vfc2FromVfc1, + UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(vfc2FromVfc1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, + true); + + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + + // verify property + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedBooleanValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(vfResource, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + // ---------------------Service------------------------------------------------------------------------ + + /** + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p3) (p2) (p1) + */ + @Test + public void serviceWithNestedResourceProperty3Levels() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + } + + /** + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) + */ + @Test + public void serviceWithNestedResourceProperty3LevelsAndVfProperty() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + PropertyReqDetails propDetails = ElementFactory.getDefaultBooleanProperty(); + propDetails.setName(newBooleanPropName); + propDetails.setPropertyDefaultValue(newBooleanPropValue); + AtomicOperationUtils.addCustomPropertyToResource(propDetails, vfResource, UserRoleEnum.DESIGNER, true); + propDetails = ElementFactory.getDefaultStringProperty(); + propDetails.setName(newStringPropName); + propDetails.setPropertyDefaultValue(newStringPropValue); + AtomicOperationUtils.addCustomPropertyToResource(propDetails, vfResource, UserRoleEnum.DESIGNER, true); + propDetails = ElementFactory.getDefaultIntegerProperty(); + propDetails.setName(newIntegerPropName); + propDetails.setPropertyDefaultValue(newIntegerPropValue); + AtomicOperationUtils.addCustomPropertyToResource(propDetails, vfResource, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfResource, expectedPropertyList); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + } + + /** + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) CP(VF inst) (p5) + */ + @Test + public void serviceWithNestedResourceProperty3LevelsAndCp() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // four resource + Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, + NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty(); + cpStringProperty.setName("Different Name"); + cpStringProperty.setPropertyDefaultValue("Different value from default"); + AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList); + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, cp, expectedPropertyList, + vfResource); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + } + + /** + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) CP(inst) (p5) + */ + @Test + public void serviceWithNestedResourceProperty3LevelsAndCpResInst() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + // expectedPropertyList = + // PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, + // expectedPropertyList); + + // four resource + Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, + NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty(); + cpStringProperty.setName("Different Name"); + cpStringProperty.setPropertyDefaultValue("Different value from default"); + AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(cp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER); + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + } + + /** + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) | (p3) (p2) (p1) + * | (VFC(inst)-->VFC-->VFC-->VFC) (p3) (p2) (p1) + * + * VF2(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) | (p3') (p2') (p1') | + * (VFC(inst)-->VFC-->VFC-->VFC) (p3) (p2) (p1) + */ + @Test + public void serviceNestedVfResourceProperty3Levels2SameResInstances() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + // verify property + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList, + vfResource); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + } + + // service test template + /** + * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) + */ + @Test + public void serviceNestedVfResourceProperty3LevelsAndSelfVfProperty() throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty(); + newProp.setName(newStringPropName); + newProp.setPropertyDefaultValue(newStringPropValue); + AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + } + + /** + * update property(p4) + * + * + * VFC(p1) ^ | VFC(p2) ^ | Service-->VF(inst)-->VF-->(VFC(inst)-->VFC(p3) + * (p4) + */ + @Test + public void serviceNestedVfResourceProperty3LevelsAndSelfVfProperty_UpdateVfproperty() throws Exception { + // Create VFC(check-in state) derived from another resource + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + + // add property to VF + PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty(); + newProp.setName(newStringPropName); + newProp.setPropertyDefaultValue(newStringPropValue); + Either propDetailsToUpdate = AtomicOperationUtils + .addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update VF instance property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedStringValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(service, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + /** + * update property(p1) + * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) + */ + @Test + public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance1LevelProperty() + throws Exception { + + basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + Either propDetailsToUpdate = AtomicOperationUtils + .addDefaultPropertyToResource(PropertyTypeEnum.STRING, basicVFC, UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + // verify property + PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty(); + newProp.setName(newStringPropName); + newProp.setPropertyDefaultValue(newStringPropValue); + AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update VF property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedStringValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(service, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + /** + * update property(p2) + * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) + */ + @Test + public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance2LevelProperty() + throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, + basicVFC, ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true).left().value(); + Either propDetailsToUpdate = AtomicOperationUtils + .addCustomPropertyToResource(ElementFactory.getDefaultIntegerProperty(), vfc1FromBasicVFC, + UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(vfc1FromBasicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, + true); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + + // verify property + PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty(); + newProp.setName(newStringPropName); + newProp.setPropertyDefaultValue(newStringPropValue); + AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update VF property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedIntegerValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(service, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + /** + * update property(p3) + * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) + */ + @Test + public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance3LevelProperty() + throws Exception { + + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, + vfc1FromBasicVFC, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value(); + Either propDetailsToUpdate = AtomicOperationUtils + .addCustomPropertyToResource(ElementFactory.getDefaultBooleanProperty(), vfc2FromVfc1, + UserRoleEnum.DESIGNER, true); + String propNameToUpdate = propDetailsToUpdate.left().value().getName(); + String propTypeToUpdate = propDetailsToUpdate.left().value().getType(); + AtomicOperationUtils.changeComponentState(vfc2FromVfc1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, + true); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + // verify property + PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty(); + newProp.setName(newStringPropName); + newProp.setPropertyDefaultValue(newStringPropValue); + AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + // update VF property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils + .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedBooleanValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(service, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + + } + + /** + * update property p5' + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) CP(inst on VF) (p5) CP(inst) (p5') + */ + @Test + public void serviceWithNestedResourceProperty3LevelsAndCpOnVfUpdateCpInstanceOfService() throws Exception { + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + // expectedPropertyList = + // PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, + // expectedPropertyList); + + // four resource + Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, + NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty(); + cpStringProperty.setName("Different Name"); + cpStringProperty.setPropertyDefaultValue("Different value from default"); + AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(cp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER); + // create VF + add RI + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + // service = AtomicOperationUtils.getServiceObject(service, + // UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + String propNameToUpdate = "cidr"; + String propTypeToUpdate = "string"; + + // update CP property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName( + service, componentInstDetails, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedStringValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + List path = expectedUpdatePropDetails.getPath(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(service, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, path); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + } + + /** + * update property p5 + * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2) + * (p1) CP(inst on VF) (p5) CP(inst) (p5') + */ + @Test + public void serviceWithNestedResourceProperty3LevelsAndCpOnVfUpdateCpInstanceOfVf() throws Exception { + basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY); + vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource( + ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC); + vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(), + LifeCycleStatesEnum.CERTIFY, vfc1FromBasicVFC); + vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER); + // expectedPropertyList = + // PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, + // expectedPropertyList); + + // four resource + Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, + NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty(); + cpStringProperty.setName("Different Name"); + cpStringProperty.setPropertyDefaultValue("Different value from default"); + AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(cp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + // create VF + add RI + cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER); + vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + ComponentInstance componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left() + .value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER); + + // Service + expectedPropertyList = new ArrayList(); + actualPropertyList = new ArrayList(); + expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList, + null); + expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList); + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left() + .value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + componentInstDetails = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value(); + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service, + expectedPropertyList); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false); + + String propNameToUpdate = "cidr"; + String propTypeToUpdate = "string"; + + // update CP property + ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName( + service, componentInstDetails, propNameToUpdate, propTypeToUpdate); + expectedUpdatePropDetails.setValue(updatedStringValue); + String propUniqeId = expectedUpdatePropDetails.getUniqueId(); + List path = expectedUpdatePropDetails.getPath(); + RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils + .updatePropertyValueOnResourceInstance(service, componentInstDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails); + assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS, + updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER); + + actualPropertyList = new ArrayList<>(); + actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null); + + ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils + .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, path); + assertTrue("property was not updated propely", + PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true)); + } + + // -------------------Methods-------------------------- + public static PropertyDataDefinition convertToPropertyDataDefinitionObject(PropertyReqDetails prop) { + PropertyDataDefinition propDataDef = new PropertyDataDefinition(); + propDataDef.setDefaultValue(prop.getPropertyDefaultValue()); + propDataDef.setType(prop.getPropertyType()); + propDataDef.setPassword(prop.getPropertyPassword()); + propDataDef.setDescription(prop.getPropertyDescription()); + return propDataDef; + } + + protected Resource createResourceWithPropertyDerivedFromOtherResource(PropertyReqDetails propertyReqDetails, + LifeCycleStatesEnum state, Resource derivedFromResource) throws Exception { + Resource resource = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, + derivedFromResource, ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true).left() + .value(); + if (propertyReqDetails != null) { + AtomicOperationUtils.addCustomPropertyToResource(propertyReqDetails, resource, UserRoleEnum.DESIGNER, true); + } + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, state, true); + return AtomicOperationUtils.getResourceObject(resource, UserRoleEnum.DESIGNER); + // return resource; + } + + protected Resource createResourceWithProperty(PropertyReqDetails propertyReqDetails, LifeCycleStatesEnum state) + throws Exception { + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + if (propertyReqDetails != null) { + AtomicOperationUtils.addCustomPropertyToResource(propertyReqDetails, resource, UserRoleEnum.DESIGNER, true); + } + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, state, true); + return AtomicOperationUtils.getResourceObject(resource, UserRoleEnum.DESIGNER); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java new file mode 100644 index 0000000000..7ecdcf457f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java @@ -0,0 +1,1796 @@ +/*- + * ============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.ci.tests.execute.property; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +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.AtomicOperationUtils; +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.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.validation.ErrorValidationUtils; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class ComponentProperty extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public ComponentProperty() { + super(name, ComponentProperty.class.getName()); + } + + @DataProvider + private static final Object[][] propertiesListDefaultValueSuccessFlow() throws IOException, Exception { + return new Object[][] { + // integer + { "integer", "[1,2]", "[1,2]" }, + { "tosca.datatypes.Credential", + "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token\":\"token2\"}]", + "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token\":\"token2\"}]" }, + { "tosca.datatypes.Credential", + "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol
2\",\"token\":\"token2 2\"}]", + "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token\":\"token2 2\"}]" }, + { "tosca.datatypes.Credential", null, null }, { "tosca.datatypes.Credential", "[]", "[]" }, + { "integer", "[1,2,1,2]", "[1,2,1,2]" }, { "integer", "[1,,2]", "[1,2]" }, + { "integer", "[1,null,2]", "[1,2]" }, { "integer", "[1,2,null]", "[1,2]" }, + { "integer", "[null,1,2]", "[1,2]" }, { "integer", "[1,,2]", "[1,2]" }, + { "integer", "[,1,2]", "[1,2]" }, + // {"integer", + // "[1000000000000000000000000000000000000000000000000000,2]" , + // "[1000000000000000000000000000000000000000000000000000,2]"}, + { "integer", "[100000000,2]", "[100000000,2]" }, // Andrey, in + // success + // flow + // integer + // max value + // is + // 2147483647 + { "integer", null, null }, // no default value + { "integer", + "[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]", + "[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]" }, + // boolean + { "boolean", "[true,false]", "[true,false]" }, + { "boolean", "[true,false,false]", "[true,false,false]" }, + { "boolean", "[null,true,false]", "[true,false]" }, { "boolean", "[true,false,null]", "[true,false]" }, + { "boolean", "[true,,false]", "[true,false]" }, { "boolean", "[true,false,]", "[true,false]" }, + { "boolean", "[,true,false]", "[true,false]" }, { "boolean", null, null }, + // DE199713 - Default value for property type Boolean should + // support also the following values: "true", "t" , "on" , "1" , + // "false", "f" , "off" , "0" + { "boolean", "[on,off]", "[true,false]" }, { "boolean", "[ON,OFF]", "[true,false]" }, + { "boolean", "[On,Off]", "[true,false]" }, { "boolean", "[yes,no]", "[true,false]" }, + { "boolean", "[YES,NO]", "[true,false]" }, { "boolean", "[Yes,No]", "[true,false]" }, + { "boolean", "[y,n]", "[true,false]" }, { "boolean", "[Y,N]", "[true,false]" }, + // float + { "float", "[10.0,0.0]", "[10.0,0.0]" }, { "float", "[10,0]", "[10,0]" }, // contain + // integer + { "float", "[-10,-5.30]", "[-10,-5.30]" }, // Negative numbers + { "float", "[10,null,0]", "[10,0]" }, { "float", "[null,10,0]", "[10,0]" }, + { "float", "[10,0,null]", "[10,0]" }, + { "float", "[10,0.1111111111111111111111111111111111111111]", + "[10,0.1111111111111111111111111111111111111111]" }, + { "float", "[10, ,7.3 ]", "[10,7.3]" }, { "float", "[10 , 7.3 , ]", "[10,7.3]" }, + { "float", "[, , 10 , 7.3 , ]", "[10,7.3]" }, { "float", "[4.7f, -5.5f ]", "[4.7,-5.5]" }, + { "float", "[4.7f, 6.3 ,6.3, 4.7f]", "[4.7,6.3,6.3,4.7]" }, // duplicate + // value + { "float", null, null }, { "string", "[aaaa , AAAA ]", "[\"aaaa\",\"AAAA\"]" }, + + { "string", + "[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]", + "[\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\"]" }, + { "string", "[aaaa , AAAA, 1, off , true, false ]", + "[\"aaaa\",\"AAAA\",\"1\",\"off\",\"true\",\"false\"]" }, + { "string", "[aaaa , AAAA, aaaa, Aaaa , aaaa ]", "[\"aaaa\",\"AAAA\",\"aaaa\",\"Aaaa\",\"aaaa\"]" }, + { "string", "[aaaa , AAAA, , ]", "[\"aaaa\",\"AAAA\"]" }, + { "string", "[ , aaaa , AAAA ]", "[\"aaaa\",\"AAAA\"]" }, + { "string", "[ aaaa , , AAAA ]", "[\"aaaa\",\"AAAA\"]" }, + { "string", "[ aaaa , AAAA, null ]", "[\"aaaa\",\"AAAA\"]" }, + { "string", "[ null, aaaa , AAAA ]", "[\"aaaa\",\"AAAA\"]" }, + { "string", "[ aaaa , null , AAAA ]", "[\"aaaa\",\"AAAA\"]" }, { "string", null, null }, // without + // default + // values + // - + // Property + // will + // be + // without + // default + // parameter + { "string", "[ AAA ]", "[\"AAA\"]" }, // BUG DE199715 - + // Error 400 + // response + // received + // while adding + // property with + // default value + // contain HTML + // tags. + // Need to check + // whether / is + // legal in yaml + + }; + } + + @DataProvider + private static final Object[][] invalidListProperties() throws IOException, Exception { + return new Object[][] { + + { "integer", "[1,aaa]" }, + { "tosca.datatypes.Credential", + "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token1\":\"token2\"}]" }, + { "integer", "[1,false]" }, { "integer", "[1,3.5]" }, { "integer", "[1,3#]" }, + { "boolean", "[true,3.5]" }, { "boolean", "[true,1000]" }, { "boolean", "[false,trueee]" }, + { "boolean", "[true,false!]" }, { "float", "[5.0000001,true]" }, { "float", "[0.0001,koko]" }, + { "float", "[0.0001,6.3@]" }, { "float", "[0.0001f,6.3x]" }, }; + } + + @DataProvider + private static final Object[][] updatePropertiesListDefaultValueSuccessFlow() throws IOException, Exception { + return new Object[][] { + // integer + // Setting --- update properties + // ----------------------------------------------------------------------- + { "integer", "[1,2]", "[1,2]", "integer", "[200,100]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[200,100,null]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[null, 200,100]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[200,null,100]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[200,100, ]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[ , 200,100 ]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[200 , ,100 ]", "[200,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", null, null }, + { "integer", "[1,2]", "[1,2]", "integer", "[200 , 100 , 200, 100]", "[200,100,200,100]" }, + // + // ////DE199829 update resource property schema_type is not + // updated + { "integer", "[1,2]", "[1,2]", "string", "[aaaa , bbbb ]", "[\"aaaa\",\"bbbb\"]" }, + { "integer", "[1,2]", "[1,2]", "boolean", "[true , false ]", "[true,false]" }, + { "integer", "[1,2]", "[1,2]", "float", "[3.5,4.8f ]", "[3.5,4.8]" }, + // {"string", "[aaa,bbb]" , "[\"aaa\",\"bbb\"]","integer","[100, + // 200]" , "[\"100\",\"200\"]"}, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "integer", "[100, 200]", "[100,200]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "float", "[0.1f, 3.01]", "[0.1,3.01]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "boolean", "[true, false]", "[true,false]" }, + { "float", "[1.2,2.3]", "[1.2,2.3]", "boolean", "[true, false]", "[true,false]" }, + { "float", "[1.2,2.3]", "[1.2,2.3]", "integer", "[100, 200]", "[100,200]" }, + { "float", "[1.2,2.3]", "[1.2,2.3]", "string", "[koko, moko]", "[\"koko\",\"moko\"]" }, + { "boolean", "[true,false]", "[true,false]", "string", "[koko, moko]", "[\"koko\",\"moko\"]" }, + // {"boolean", "[true,false]" , + // "[\"true\",\"false\"]","integer","[100, 300000000000000]" , + // "[\"100\",\"300000000000000\"]"},// Andrey, value not valid + // for integer success flow + { "boolean", "[true,false]", "[true,false]", "integer", "[100,2147483647]", "[100,2147483647]" }, // Andrey, + // in + // success + // flow + // integer + // max + // value + // is + // 2147483647 + { "boolean", "[true,false]", "[true,false]", "float", "[3.000000000000002, 5.67f]", + "[3.000000000000002,5.67]" }, + // ////DE199829 + // + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx, yyy]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx , yyy ,null]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[null, xxx, yyy]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx ,null,yyy]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx ,yyy, ]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[ , xxx,yyy ]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx , ,yyy ]", "[\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[ xxx , yyy , xxx , yyy]", + "[\"xxx\",\"yyy\",\"xxx\",\"yyy\"]" }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", null, null }, + { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx_-x, y__y--y]", + "[\"xxx_-x\",\"y__y--y\"]" }, + // DE199715 + // {"string", "[aaa,bbb]" , "[\"aaa\",\"bbb\"]", "string" , + // "[\"xxx\", \"yyy\"]" , "[\"xxx\",\"yyy\"]"}, + // + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1 , -0.1]", "[2.1,-0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1, 0.1 ,null]", "[2.1,0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[null , 2.1, 0.1]", "[2.1,0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1,null,0.1]", "[2.1,0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1,0.1, ]", "[2.1,0.1]" }, + // {"float", "[1.00,0.02]" , "[1.00,0.02]","float","[ , + // 2.00000000000001,0.00000000000000100 ]" , + // "[2.00000000000001,0.00000000000000100]"}, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1 , ,0.1 ]", "[2.1,0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", null, null }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1f , ,0.1f ]", "[2.1,0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1 , 0.1 , 2.1, 0.1]", "[2.1,0.1,2.1,0.1]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[200 , 100.11]", "[200,100.11]" }, + { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[-2.35 , 100.11]", "[-2.35,100.11]" }, + // + { "boolean", "[true,false]", "[true,false]", "boolean", "[false , false]", "[false,false]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", "[false, true ,null]", "[false,true]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", "[null , false, true]", "[false,true]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", "[false,null,true]", "[false,true]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", "[false ,true , ]", "[false,true]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", "[ , false, true ]", "[false,true]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", "[false , ,true ]", "[false,true]" }, + { "boolean", "[true,false]", "[true,false]", "boolean", null, null }, { "boolean", "[true,false]", + "[true,false]", "boolean", "[false , true , false, true]", "[false,true,false,true]" }, }; + } + + @DataProvider + private static final Object[][] updatePropertiesListDefaultValueFailureFlow() throws IOException, Exception { + return new Object[][] { + // integer + // Setting --- update properties + // ----------------------------------------------------------------------- + { "integer", "[1,2]", "[1,2]", "integer", "[aaa,bbb]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[true,false]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[1.0,100]" }, + { "integer", "[1,2]", "[1,2]", "integer", "[@12,100]" }, + { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[aaa, bbb]" }, + { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[0.88, false]" }, + { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[0.88g, 0.3]" }, + { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[@0.88, 0.3]" }, + { "boolean", "[true, false]", "[true,false]", "boolean", "[true, 100]" }, + { "boolean", "[true, false]", "[true,false]", "boolean", "[false, 0.01]" }, + { "boolean", "[true, false]", "[true,false]", "boolean", "[koko, true]" }, + { "boolean", "[true, false]", "[true,false]", "boolean", "[@false, true]" }, + + }; + } + + // Map properties + @DataProvider + private static final Object[][] updatePropertiesMapDefaultValueSuccessFlow() throws IOException, Exception { + return new Object[][] { + // entrySchemaType , propertyDefaultValues , + // expectedDefaultValue , newEntrySchemaType , + // newPropertyDefaultValue , newExpectedDefaultValue + // integer + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer", + "{\"key1\":200,\"key2\":null , \"key3\":300}", "{\"key1\":200,\"key2\":null,\"key3\":300}" }, + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer", + "{\"key1\":null,\"key2\":200 , \"key3\":100}", "{\"key1\":null,\"key2\":200,\"key3\":100}" }, + // string + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "string", + "{\"key1\":\"aaaa\" , \"key2\":\"aaaa\"}", "{\"key1\":\"aaaa\",\"key2\":\"aaaa\"}" }, + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "boolean", + "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}" }, + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "float", + "{\"key1\":3.5 , \"key2\":4.8f}", "{\"key1\":3.5,\"key2\":4.8}" }, + // string + { "string", "{\"key1\":aaa , \"key2\":bbb}", "{\"key1\":\"aaa\",\"key2\":\"bbb\"}", "string", + "{\"key1\":xxx , \"key2\":yyy}", "{\"key1\":\"xxx\",\"key2\":\"yyy\"}" }, + // float + { "float", "{\"key1\":1.00 , \"key2\":0.02}", "{\"key1\":1.00,\"key2\":0.02}", "float", + "{\"key1\":2.1, \"key2\":-0.1}", "{\"key1\":2.1,\"key2\":-0.1}" }, + { "float", "{\"key1\":1.00 , \"key2\":0.02}", "{\"key1\":1.00,\"key2\":0.02}", "float", + "{\"key1\":2.1 , \"key2\":0.1 , \"key3\":null}", "{\"key1\":2.1,\"key2\":0.1,\"key3\":null}" }, + // boolean + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":false , \"key2\":false}", "{\"key1\":false,\"key2\":false}" }, + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":false , \"key2\":true , \"key3\":null}", + "{\"key1\":false,\"key2\":true,\"key3\":null}" }, + // null + { "boolean", "{\"key1\":null , \"key2\":false}", "{\"key1\":null,\"key2\":false}", "boolean", + "{\"key1\":false , \"key2\":true , \"key3\":null}", + "{\"key1\":false,\"key2\":true,\"key3\":null}" }, + // tosca.datatypes.Credential + { "tosca.datatypes.Credential", + "{\"key1\":{\"protocol\":\"protocol
1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}", + "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}", + "tosca.datatypes.Credential", + "{\"key1\":{\"protocol\":\"protocol
1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}", + "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}" }, + + }; + } + + @DataProvider + private static final Object[][] propertiesMapDefaultValueSuccessFlow() throws IOException, Exception { + return new Object[][] { + + // entrySchemaType , propertyDefaultValues , + // expectedDefaultValue + // + // {"string", + // "{\"vf_module_id\":{\"get_input\":\"vf_module_id\"}, + // \"vnf_idw\": 2}", + // "{\"vf_module_id\":{\"get_input\":\"vf_module_id\"}, + // \"vnf_idw\": 2}"}, + + // tosca.datatypes.Credential + { "tosca.datatypes.Credential", + "{\"key1\":{\"protocol\":\"protocol
1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}", + "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}" }, + // integer + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}" }, + { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":2}", + "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":2}" }, + { "integer", "{\"key1\":1,\"key2\":null,\"key3\":1,\"key4\":2}", + "{\"key1\":1,\"key2\":null,\"key3\":1,\"key4\":2}" }, + { "integer", "{\"key1\":null,\"key2\":1,\"key3\":1,\"key4\":2}", + "{\"key1\":null,\"key2\":1,\"key3\":1,\"key4\":2}" }, + { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}", + "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" }, + { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":NULL}", + "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" }, + { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":Null}", + "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" }, + { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":nuLL}", + "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" }, + { "integer", null, null }, // no default value + // //BUG + //// {"integer", + // "{\"key1\":1000000000000000000000000000000000000000000000000000,\"key2\":2}" + // ,"{\"key1\":1000000000000000000000000000000000000000000000000000,\"key2\":2}"}, + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":true , \"key2\":false, \"key3\":false }", + "{\"key1\":true,\"key2\":false,\"key3\":false}" }, + { "boolean", "{\"key1\":null , \"key2\":true, \"key3\":false }", + "{\"key1\":null,\"key2\":true,\"key3\":false}" }, + { "boolean", "{\"key1\":true , \"key2\":Null, \"key3\":false }", + "{\"key1\":true,\"key2\":null,\"key3\":false}" }, + { "boolean", "{\"key1\":true , \"key2\":false, \"key3\":nULL }", + "{\"key1\":true,\"key2\":false,\"key3\":null}" }, + { "boolean", null, null }, + { "boolean", "{\"key1\":on , \"key2\":off}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":ON , \"key2\":OFF}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":On , \"key2\":Off}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":yes , \"key2\":no}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":YES , \"key2\":NO}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":Yes , \"key2\":No}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":y , \"key2\":n}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{\"key1\":Y , \"key2\":N}", "{\"key1\":true,\"key2\":false}" }, + { "boolean", "{null:false}", "{\"null\":false}" }, + // float + { "float", "{\"key1\":10.0 , \"key2\":0.0}", "{\"key1\":10.0,\"key2\":0.0}" }, + { "float", "{\"key1\":10 , \"key2\":0}", "{\"key1\":10,\"key2\":0}" }, // contain + // integer + { "float", "{\"key1\":null , \"key2\":Null}", "{\"key1\":null,\"key2\":null}" }, // contain + // null + { "float", "{\"key1\":3.5 , \"key2\":nULL}", "{\"key1\":3.5,\"key2\":null}" }, + // BUG + { "float", "{\"key1\":3.5 , \"key2\":0.1111111111111111111111111111111111111111}", + "{\"key1\":3.5,\"key2\":0.1111111111111111111111111111111111111111}" }, + { "float", "{\"key1\":4.7f , \"key2\":-5.5f}", "{\"key1\":4.7,\"key2\":-5.5}" }, + { "float", "{\"key1\":4.7f , \"key2\":-5.5f, \"key3\":-5.5f}", + "{\"key1\":4.7,\"key2\":-5.5,\"key3\":-5.5}" }, + { "boolean", null, null }, + { "string", "{\"key1\":aaaa , \"key2\":AAAA}", "{\"key1\":\"aaaa\",\"key2\":\"AAAA\"}" }, + { "string", "{\"key1\":off , \"key2\":true , \"key3\":1}", + "{\"key1\":\"off\",\"key2\":\"true\",\"key3\":\"1\"}" }, + { "string", "{\"key1\":aaaa , \"key2\":Aaaa , \"key3\":aaaa}", + "{\"key1\":\"aaaa\",\"key2\":\"Aaaa\",\"key3\":\"aaaa\"}" }, + { "string", "{\"key1\":aaaa , \"key2\":bbbb , \"key3\":null}", + "{\"key1\":\"aaaa\",\"key2\":\"bbbb\",\"key3\":null}" }, + { "string", "{\"key1\":NULL , \"key2\":bbbb , \"key3\":aaaa}", + "{\"key1\":null,\"key2\":\"bbbb\",\"key3\":\"aaaa\"}" }, + { "string", "{\"key1\":aaaa , \"key2\":Null , \"key3\":bbbb}", + "{\"key1\":\"aaaa\",\"key2\":null,\"key3\":\"bbbb\"}" }, + { "string", null, null }, // without default values - Property + // will be without default parameter + { "string", "{\"key1\":\"AAAA\" }", "{\"key1\":\"AAAA\"}" }, + + }; + } + + @DataProvider + private static final Object[][] updatePropertiesMapDefaultValueFailureFlow() throws IOException, Exception { + return new Object[][] { + + // integer + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer", + "{\"key1\":aaa , \"key2\":bbb}" }, + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer", + "{\"key1\":true , \"key2\":false}" }, + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer", + "{\"key1\":1.0 , \"key2\":100}" }, + { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer", + "{\"key1\":12@ , \"key2\":100}" }, + // float + { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float", + "{\"key1\":aaa , \"key2\":bbb}" }, + { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float", + "{\"key1\":0.88 , \"key2\":false}" }, + { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float", + "{\"key1\":0.88g , \"key2\":0.3}" }, + { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float", + "{\"key1\":@0.88g , \"key2\":0.3}" }, + // boolean + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":true , \"key2\":100}" }, + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":false , \"key2\":0.01}" }, + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":koko , \"key2\":true}" }, + { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":@false , \"key2\":true}" }, + { "boolean", "{\"key1\":true,\"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{:false , \"key2\":true}" }, + { "boolean", "{\"key1\":true,\"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean", + "{\"key1\":true , , \"key2\":false}" }, + // tosca.datatypes.Credential + { "tosca.datatypes.Credential", + "{\"key1\":{\"protocol\":\"protocol
1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}", + "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}", + "tosca.datatypes.Credential", + "{\"key1\":{\"protocol\":\"protocol
1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token2\":\"token2\"}}" }, + + }; + } + + // US594938 - UPDATE PROPERTY + // DE199718 + @Test(dataProvider = "updatePropertiesListDefaultValueFailureFlow") + public void updateDefaultValueOfResourcePropertyListFailureFlow(String entrySchemaType, String propertyDefaltValues, + String expecteddefaultValues, String newEntrySchemaType, String newPropertyDefaltValues) throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.setPropertyDefaultValue(propertyDefaltValues); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // verify properties return from response + assertEquals("list", resourcePropertiesFromResponse.getType()); + assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(propertyDetails.getSchema().getProperty().getType(), + resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + // Update resource property type = "list" + propertyDetails.setPropertyDefaultValue(newPropertyDefaltValues); + propertyDetails.getSchema().getProperty().setType(newEntrySchemaType); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add(propertyDetails.getName()); + variables.add(propertyDetails.getPropertyType()); + variables.add(propertyDetails.getSchema().getProperty().getType()); + variables.add(newPropertyDefaltValues); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, + updatePropertyResponse.getResponse()); + } + + @Test + public void updatePropertyOfDerivedResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String derivedResourcePropertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + // second resource derived from basicVFC + Resource vfc1FromBasicVFC = AtomicOperationUtils + .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC, + ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true) + .left().value(); + // add property Type list to second resource + PropertyReqDetails defaultListProperty = ElementFactory.getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(defaultListProperty, vfc1FromBasicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + // Update property (list) of derived resource + RestResponse updatePropertyResponse = AtomicOperationUtils.updatePropertyOfResource(propertyDetails, basicVFC, + derivedResourcePropertyUniqueId, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updatePropertyResponse.getResponse()); + // Verify resource's priority list did not changed + verifyResourcePropertyList(basicVFC, propertyDetails, "[\"a\",\"b\"]"); + } + + @Test + public void updatePropertyOfNonDerivedResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + // second resource derived from basicVFC + Resource vfc1FromBasicVFC = AtomicOperationUtils + .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC, + ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true) + .left().value(); + // add property Type list to second resource + PropertyReqDetails defaultListProperty = ElementFactory.getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(defaultListProperty, vfc1FromBasicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // Update property (list) of derived resource + defaultListProperty.setPropertyDefaultValue("[1,2,3,4]"); + String expectedDefaultValue = "[1,2,3,4]"; + ComponentInstanceProperty resourcePropertyAfterUpdate = AtomicOperationUtils + .updatePropertyOfResource(defaultListProperty, vfc1FromBasicVFC, propertyUniqueId, + UserRoleEnum.DESIGNER, true) + .left().value(); + assertEquals(resourcePropertyAfterUpdate.getType(), "list"); + assertEquals(resourcePropertyAfterUpdate.getDefaultValue(), expectedDefaultValue); + assertEquals(resourcePropertyAfterUpdate.getSchema().getProperty().getType(), + defaultListProperty.getSchema().getProperty().getType()); // string/integer/boolean/float + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(vfc1FromBasicVFC.getUniqueId()); + String expectedDefaultValueFromDerivedResource = "[\"a\",\"b\"]"; + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + resource.getProperties().get(0).getDefaultValue().equals(expectedDefaultValue); + resource.getProperties().get(1).getDefaultValue().equals(expectedDefaultValueFromDerivedResource); + } + + @Test + public void updateListPropertyToNonCheckedOutResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String PropertyDefaultValue = "[2,3]"; + propertyDetails.setPropertyDefaultValue(PropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType("integer"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + // Update resource property type = "list" + propertyDetails.setPropertyDefaultValue("[3,4]"); + propertyDetails.getSchema().getProperty().setType("integer"); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updatePropertyResponse.getResponse()); + // Verify resource's priority list did not changed + verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]"); + } + + @Test + public void updateListPropertyResourceByNonResouceOwner() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String PropertyDefaultValue = "[2,3]"; + propertyDetails.setPropertyDefaultValue(PropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType("integer"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // AtomicOperationUtils.changeComponentState(basicVFC, + // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + // Update resource property type = "list" + propertyDetails.setPropertyDefaultValue("[3,4]"); + propertyDetails.getSchema().getProperty().setType("integer"); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER2, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updatePropertyResponse.getResponse()); + // Verify resource's priority list did not changed + verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]"); + } + + @Test + public void updateListPropertyResourceByTester() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String PropertyDefaultValue = "[2,3]"; + propertyDetails.setPropertyDefaultValue(PropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType("integer"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // AtomicOperationUtils.changeComponentState(basicVFC, + // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + // Update resource property type = "list" + propertyDetails.setPropertyDefaultValue("[3,4]"); + propertyDetails.getSchema().getProperty().setType("integer"); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.TESTER, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + updatePropertyResponse.getResponse()); + // Verify resource's priority list did not changed + verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]"); + } + + // DE199964 + @Test(enabled = false) + public void updateListPropertyToNonExistingResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String PropertyDefaultValue = "[2,3]"; + propertyDetails.setPropertyDefaultValue(PropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType("integer"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + String resourceUniqueId = basicVFC.getUniqueId(); + basicVFC.setUniqueId("1111111"); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND)); + ArrayList variables = new ArrayList<>(); + variables.add(basicVFC.getUniqueId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables, + updatePropertyResponse.getResponse()); + // Verify resource's priority list did not changed + basicVFC.setUniqueId(resourceUniqueId); + verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]"); + } + + // DE199725 + @Test + public void updateResourcePropertyListNonSupportedPropertyType() throws Exception { // Not + // "list" + // type + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String PropertyDefaultValue = "[2,3]"; + propertyDetails.setPropertyDefaultValue(PropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType("integer"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // update resource property + String propertyType = "listttttttt"; + propertyDetails.setPropertyType(propertyType); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false) + .right().value(); + ArrayList variables = new ArrayList<>(); + variables.add(propertyDetails.getPropertyType()); // property data type + // (koko instead + // list) + variables.add(propertyDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables, + updatePropertyResponse.getResponse()); + // Verify resource's priority list did not changed + propertyDetails.setPropertyType("list"); + verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]"); + } + + @Test(enabled = false) // DE199732 + public void updateResourcePropertyListNonSupportedEntrySchemaType() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String PropertyDefaultValue = "[2,3]"; + propertyDetails.setPropertyDefaultValue(PropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType("integer"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // update resource property + String EntrySchemaType = "integerrrrrr"; + propertyDetails.getSchema().getProperty().setType(EntrySchemaType); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add(EntrySchemaType); + variables.add(propertyDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables, + updatePropertyResponse.getResponse()); + propertyDetails.getSchema().getProperty().setType("integer"); + verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]"); + } + + @Test(dataProvider = "updatePropertiesListDefaultValueSuccessFlow") + public void updateResourcePropertyListSuccessFlow(String entrySchemaType, String propertyDefaltValues, + String expecteddefaultValues, String newEntrySchemaType, String newPropertyDefaltValues, + String newExpecteddefaultValues) throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.setPropertyDefaultValue(propertyDefaltValues); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // verify properties return from response + assertEquals("list", resourcePropertiesFromResponse.getType()); + assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(propertyDetails.getSchema().getProperty().getType(), + resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + // Update resource property type = "list" + propertyDetails.setPropertyDefaultValue(newPropertyDefaltValues); + propertyDetails.getSchema().getProperty().setType(newEntrySchemaType); + ComponentInstanceProperty resourcePropertyAfterUpdate = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, true) + .left().value(); + assertEquals("list", resourcePropertyAfterUpdate.getType()); + assertEquals(newExpecteddefaultValues, resourcePropertyAfterUpdate.getDefaultValue()); + assertEquals(propertyDetails.getSchema().getProperty().getType(), + resourcePropertyAfterUpdate.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, newExpecteddefaultValues); + } + + // Add property type list to resource + // DE199718 + @Test(dataProvider = "invalidListProperties") // invalid default values + public void addListPropertyToResourceFailureFlow(String entrySchemaType, String propertyDefaltValues) + throws Exception { + // String propertyType = "list"; + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + propertyDetails.setPropertyDefaultValue(propertyDefaltValues); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + RestResponse addPropertyToResourceResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyToResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add(propertyDetails.getName()); + variables.add(propertyDetails.getPropertyType()); + variables.add(propertyDetails.getSchema().getProperty().getType()); + variables.add(propertyDefaltValues); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, + addPropertyToResourceResponse.getResponse()); + + } + + // DE199964 + @Test + public void addListPropertyToNonExistingResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType("integer"); + propertyDetails.setPropertyDefaultValue("[1,2]"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to non existing resource + basicVFC.setUniqueId("1111111"); + RestResponse addPropertyToResourceResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables, + addPropertyToResourceResponse.getResponse()); + } + + @Test + public void addListPropertyToNonCheckedOutResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType("integer"); + propertyDetails.setPropertyDefaultValue("[1,2]"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + // Add property type list to non Checked-Out resource + RestResponse addPropertyToResourceResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + addPropertyToResourceResponse.getResponse()); + } + + @Test + public void addListPropertyToResourceByNonResourceOwner() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType("integer"); + propertyDetails.setPropertyDefaultValue("[1,2]"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to non Checked-Out resource + RestResponse addPropertyToResourceResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER2, false).right().value(); + assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + addPropertyToResourceResponse.getResponse()); + } + + @Test + public void addListPropertyToResourcePropertyAlreadyExists01() throws Exception { + String propertyType = "list"; + String propertySchemaType = "integer"; + String defaultValues = "[1,2]"; + String expecteddefaultValues = "[1,2]"; + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType(propertySchemaType); + propertyDetails.setPropertyDefaultValue(defaultValues); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // check-in and check-out resource + RestResponse changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS)); + changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT); + assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS)); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + // verify properties return from response + assertEquals(resourcePropertiesFromResponse.getType(), propertyType); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expecteddefaultValues); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), propertySchemaType); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + // Add same property again to resource + RestResponse addPropertyRestResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyRestResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_ALREADY_EXISTS)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_ALREADY_EXIST.name(), variables, + addPropertyRestResponse.getResponse()); + // verify property not deleted + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + } + + @Test + public void addListPropertyToResourcePropertyAlreadyExists02() throws Exception { + String propertyType = "list"; + String propertySchemaType = "integer"; + String defaultValues = "[1,2]"; + String expecteddefaultValues = "[1,2]"; + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType(propertySchemaType); + propertyDetails.setPropertyDefaultValue(defaultValues); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + // verify properties return from response + assertEquals(resourcePropertiesFromResponse.getType(), propertyType); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expecteddefaultValues); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), propertySchemaType); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + // check-in and check-out resource + RestResponse changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS)); + changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT); + assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS)); + // Add same property again to resource + RestResponse addPropertyRestResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyRestResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_ALREADY_EXISTS)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_ALREADY_EXIST.name(), variables, + addPropertyRestResponse.getResponse()); + // verify property not deleted + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + } + + @Test // DE199725 + public void addListPropertyToResourceNonSupportedPropertyType() throws Exception { // Not + // "list" + // type + String propertyType = "listttttttt"; + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.setPropertyType(propertyType); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + RestResponse addPropertyRestResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyRestResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add(propertyDetails.getPropertyType()); // property data type + // (koko instead + // list) + variables.add(propertyDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables, + addPropertyRestResponse.getResponse()); + } + + @Test // DE199732 + public void addListPropertyToResourceNonSupportedEntrySchemaType() throws Exception { + String EntrySchemaType = "stringggg"; // instead "string" + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType(EntrySchemaType); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + RestResponse addPropertyRestResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyRestResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add(EntrySchemaType); + variables.add(propertyDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables, + addPropertyRestResponse.getResponse()); + } + + @Test + public void addHundredPropertyListToResourceSuccessFlow() throws Exception { + String propertyType = "list"; + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + String propertyName = propertyDetails.getName(); + int numberOfPropertiesToAddToResource = 100; + ComponentInstanceProperty resourcePropertiesFromResponse; + for (int x = 0; x < numberOfPropertiesToAddToResource; x++) { + propertyDetails.setName(propertyName + x); + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + // verify properties return from response + assertEquals(resourcePropertiesFromResponse.getName(), propertyName + x); + assertEquals(resourcePropertiesFromResponse.getType(), propertyType); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[\"a\",\"b\"]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetails.getSchema().getProperty().getType()); // string/integer/boolean/float + } + // get resource and verify that 100 properties exist + Resource resourceObject = AtomicOperationUtils.getResourceObject(basicVFC, UserRoleEnum.DESIGNER); + assertEquals(numberOfPropertiesToAddToResource, resourceObject.getProperties().size()); + + } + + @Test(dataProvider = "propertiesListDefaultValueSuccessFlow") + public void addListPropertyToResourceSuccessFlow(String entrySchemaType, String propertyDefaltValues, + String expecteddefaultValues) throws Exception { + String propertyType = "list"; + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + propertyDetails.setPropertyDefaultValue(propertyDefaltValues); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + // verify properties return from response + assertEquals(propertyType, resourcePropertiesFromResponse.getType()); + assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(entrySchemaType, resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + + assertEquals(resourcePropertiesFromResponse.getType(), propertyType); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expecteddefaultValues); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), entrySchemaType); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + } + + // Delete property type list + @Test + public void deleteOneOfTheListPropertiesFromResourceAndAddItAgain() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.STRING_LIST); + PropertyReqDetails propertyDetailsInteger = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[\"a\",\"b\"]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, "[\"a\",\"b\"]"); + // Add deleted property again to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + } + + @Test + public void deletePropertyListTypeInteger() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.STRING_LIST); + PropertyReqDetails propertyDetailsInteger = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[\"a\",\"b\"]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]"); + } + + @Test + public void deletePropertyListTypeBoolean() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.BOOLEAN_LIST); + PropertyReqDetails propertyDetailsInteger = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[true,false]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one property + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]"); + } + + @Test + public void deletePropertyListTypeFloat() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST); + PropertyReqDetails propertyDetailsInteger = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1.0,2.0]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one property + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]"); + } + + @Test + public void deletePropertyListAlreadyDeleted() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST); + PropertyReqDetails propertyDetailsInteger = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1.0,2.0]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]"); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one property + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]"); + // delete again the same property + deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_NOT_FOUND == deletePropertyOfResource.getErrorCode()); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables, + deletePropertyOfResource.getResponse()); + } + + @Test + public void deletePropertyListResourceIsNotCheckedOutState() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST); + String expectedDefaultvalues = "[1.0,2.0]"; + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expectedDefaultvalues); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + // Get resource and verify updated default value + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues); + // Check-in resource + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + // Delete property + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION == deletePropertyOfResource.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + deletePropertyOfResource.getResponse()); + // Get resource and verify property is not deleted + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues); + } + + @Test + public void deletePropertyListResourceByNotIsNonResouceOwner() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST); + String expectedDefaultvalues = "[1.0,2.0]"; + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expectedDefaultvalues); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + // Get resource and verify updated default value + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues); + // Delete property by non resource owner + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER2); + assertTrue(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION == deletePropertyOfResource.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + deletePropertyOfResource.getResponse()); + // Get resource and verify property is not deleted + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues); + } + + @Test + public void deletePropertyListFromNonExistingResource() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST); + String expectedDefaultvalues = "[1.0,2.0]"; + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + String actualResourceUniqueId = basicVFC.getUniqueId(); + // Add property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expectedDefaultvalues); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + // Get resource and verify updated default value + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues); + // Delete property from non existing resource + basicVFC.setUniqueId("1111111"); + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(deletePropertyOfResource.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables, + deletePropertyOfResource.getResponse()); + // Get resource and verify property is not deleted + basicVFC.setUniqueId(actualResourceUniqueId); + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues); + } + + @Test + public void deletePropertyOfDerivedResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String derivedResourcePropertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + // second resource derived from basicVFC + Resource vfc1FromBasicVFC = AtomicOperationUtils + .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC, + ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true) + .left().value(); + // Delete property (list) of derived resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource( + vfc1FromBasicVFC.getUniqueId(), derivedResourcePropertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(deletePropertyOfResource.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables, + deletePropertyOfResource.getResponse()); + // Verify resource's priority list did not changed + verifyResourcePropertyList(vfc1FromBasicVFC, propertyDetails, "[\"a\",\"b\"]"); + } + + @Test + public void deletePropertyOfNonDerivedResource() throws Exception { + PropertyReqDetails propertyListString = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyListString, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + // second resource derived from basicVFC + Resource vfc1FromBasicVFC = AtomicOperationUtils + .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC, + ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true) + .left().value(); + // add property Type list to second resource + PropertyReqDetails propertyListInteger = ElementFactory.getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST); + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyListInteger, vfc1FromBasicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // Delete property (list) of derived resource + RestResponse deletePropertyOfResource = AtomicOperationUtils + .deletePropertyOfResource(vfc1FromBasicVFC.getUniqueId(), propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyListString, "[\"a\",\"b\"]"); + } + + private void verifyResourcePropertyList(Resource resource, PropertyReqDetails expectedProperty, + String expecteddefaultValues) throws Exception { + // get resource and verify property from type list + Resource getResource = AtomicOperationUtils.getResourceObject(resource, UserRoleEnum.DESIGNER); + List actualResourceProperties = getResource.getProperties(); + boolean isPropertyAppear = false; + for (PropertyDefinition pro : actualResourceProperties) { + if (expectedProperty.getName().equals(pro.getName())) { + assertTrue("Check Property Type ", pro.getType().equals(expectedProperty.getPropertyType())); + assertEquals("Check Property default values ", expecteddefaultValues, pro.getDefaultValue()); + // assertTrue("Check Property default values ", + // pro.getDefaultValue().equals(expecteddefaultValues)); + assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType() + .equals(expectedProperty.getSchema().getProperty().getType())); + isPropertyAppear = true; + } + } + assertTrue(isPropertyAppear); + } + + // US656905 + // --------------------- Map Property + // ---------------------------------------------------------------- + @Test(dataProvider = "updatePropertiesMapDefaultValueFailureFlow") + public void updateDefaultValueOfResourcePropertyMapFailureFlow(String entrySchemaType, String propertyDefaultValues, + String expectedDefaultValue, String newEntrySchemaType, String newPropertyDefaultValue) throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultMapProperty(); + propertyDetails.setPropertyDefaultValue(propertyDefaultValues); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // verify properties return from response + assertEquals("map", resourcePropertiesFromResponse.getType()); + assertEquals(expectedDefaultValue, resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(propertyDetails.getSchema().getProperty().getType(), + resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expectedDefaultValue); + // Update resource property type = "map" + propertyDetails.setPropertyDefaultValue(newPropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType(newEntrySchemaType); + RestResponse updatePropertyResponse = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false) + .right().value(); + assertTrue(updatePropertyResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT)); + ArrayList variables = new ArrayList<>(); + variables.add(propertyDetails.getName()); + variables.add(propertyDetails.getPropertyType()); + variables.add(propertyDetails.getSchema().getProperty().getType()); + variables.add(newPropertyDefaultValue); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, + updatePropertyResponse.getResponse()); + } + + @Test(dataProvider = "updatePropertiesMapDefaultValueSuccessFlow") + public void updateResourcePropertyMapSuccessFlow(String entrySchemaType, String propertyDefaultValues, + String expectedDefaultValue, String newEntrySchemaType, String newPropertyDefaultValue, + String newExpectedDefaultValue) throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultMapProperty(); + propertyDetails.setPropertyDefaultValue(propertyDefaultValues); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + // verify properties return from response + assertEquals("map", resourcePropertiesFromResponse.getType()); + assertEquals(expectedDefaultValue, resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(propertyDetails.getSchema().getProperty().getType(), + resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expectedDefaultValue); + // Update resource property type = "map" + propertyDetails.setPropertyDefaultValue(newPropertyDefaultValue); + propertyDetails.getSchema().getProperty().setType(newEntrySchemaType); + ComponentInstanceProperty resourcePropertyAfterUpdate = AtomicOperationUtils + .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, true) + .left().value(); + assertEquals("map", resourcePropertyAfterUpdate.getType()); + assertEquals(newExpectedDefaultValue, resourcePropertyAfterUpdate.getDefaultValue()); + assertEquals(propertyDetails.getSchema().getProperty().getType(), + resourcePropertyAfterUpdate.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, newExpectedDefaultValue); + } + + @Test + public void deletePropertyMapTypeString() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultMapProperty(PropertyTypeEnum.STRING_MAP); + PropertyReqDetails propertyDetailsInteger = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals("{\"key1\":\"val1\",\"key2\":\"val2\"}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "{\"key1\":123,\"key2\":-456}"); + } + + @Test + public void deletePropertyMapTypeFloat() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeFloat = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.FLOAT_MAP); + PropertyReqDetails propertyDetailsInteger = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeFloat, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeFloat.getPropertyType()); + assertEquals("{\"key1\":0.2123,\"key2\":43.545}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeFloat.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "{\"key1\":123,\"key2\":-456}"); + } + + @Test + public void deletePropertyMapTypeBoolean() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeBoolean = ElementFactory + .getDefaultMapProperty(PropertyTypeEnum.BOOLEAN_MAP); + PropertyReqDetails propertyDetailsInteger = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeBoolean, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeBoolean.getPropertyType()); + assertEquals("{\"key1\":true,\"key2\":false}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeBoolean.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType()); + assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsInteger.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "{\"key1\":123,\"key2\":-456}"); + } + + @Test + public void deletePropertyMapTypeInteger() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeInteger = ElementFactory + .getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP); + PropertyReqDetails propertyDetailsBoolean = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.BOOLEAN_MAP); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeInteger, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeInteger.getPropertyType()); + assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeInteger.getSchema().getProperty().getType()); // string/integer/boolean/float + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsBoolean, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsBoolean.getPropertyType()); + assertEquals("{\"key1\":true,\"key2\":false}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsBoolean.getSchema().getProperty().getType()); + // Get resource and verify updated default value + RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(2, resource.getProperties().size()); + // Delete one resource + RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(), + propertyUniqueId, UserRoleEnum.DESIGNER); + assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode()); + // Get resource and verify updated default value + restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId()); + resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + assertEquals(1, resource.getProperties().size()); + verifyResourcePropertyList(basicVFC, propertyDetailsBoolean, "{\"key1\":true,\"key2\":false}"); + } + + @Test(dataProvider = "propertiesMapDefaultValueSuccessFlow") + public void addMapPropertyToResourceSuccessFlow(String entrySchemaType, String propertyDefaltValues, + String expecteddefaultValues) throws Exception { + String propertyType = "map"; + PropertyReqDetails propertyDetails = ElementFactory.getDefaultMapProperty(); + propertyDetails.getSchema().getProperty().setType(entrySchemaType); + propertyDetails.setPropertyDefaultValue(propertyDefaltValues); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to resource + ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value(); + // verify properties return from response + assertEquals(propertyType, resourcePropertiesFromResponse.getType()); + assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(entrySchemaType, resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float + verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues); + } + + @Test + public void addMapPropertyToNonExistingResource() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType("integer"); + propertyDetails.setPropertyDefaultValue("{\"key1\":1 , \"key2\":2}"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to non existing resource + basicVFC.setUniqueId("1111111"); + RestResponse addPropertyToResourceResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value(); + assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables, + addPropertyToResourceResponse.getResponse()); + } + + @Test + public void addMaptPropertyToResourceByNonResourceOwner() throws Exception { + PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(); + propertyDetails.getSchema().getProperty().setType("integer"); + propertyDetails.setPropertyDefaultValue("{\"key1\":1 , \"key2\":2}"); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add property type list to non Checked-Out resource + RestResponse addPropertyToResourceResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER2, false).right().value(); + assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION)); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + addPropertyToResourceResponse.getResponse()); + } + + @Test + public void addMapPropertyToResourcePropertyAlreadyExists() throws Exception { + ComponentInstanceProperty resourcePropertiesFromResponse; + PropertyReqDetails propertyDetailsTypeString = ElementFactory + .getDefaultListProperty(PropertyTypeEnum.STRING_MAP); + // create resource + Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left() + .value(); + // Add 2 property type list to resource + resourcePropertiesFromResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left() + .value(); + assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType()); + assertEquals("{\"key1\":\"val1\",\"key2\":\"val2\"}", resourcePropertiesFromResponse.getDefaultValue()); + assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), + propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float + // check-in and check-out resource + RestResponse changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS)); + changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT); + assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS)); + // Add same property again to resource + RestResponse addPropertyRestResponse = AtomicOperationUtils + .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, false).right() + .value(); + assertTrue(addPropertyRestResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_ALREADY_EXISTS)); + ArrayList variables = new ArrayList<>(); + variables.add(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_ALREADY_EXIST.name(), variables, + addPropertyRestResponse.getResponse()); + // verify property not deleted + verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, "{\"key1\":\"val1\",\"key2\":\"val2\"}"); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java new file mode 100644 index 0000000000..0586269a14 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java @@ -0,0 +1,384 @@ +/*- + * ============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.ci.tests.execute.property; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.preRequisites.SimpleOneRsrcOneServiceTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils; +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.UserRestUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class PropertyApisTest extends SimpleOneRsrcOneServiceTest { + + protected static final String RESOURCE_CATEGORY = "Generic/Databases"; + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json";; + + // protected User sdncDesignerDetails; + // protected ResourceReqDetails resourceDetails; + protected PropertyReqDetails property; + protected String body; + + protected HttpRequest httpRequest = new HttpRequest(); + protected Map headersMap = new HashMap(); + + @Rule + public static TestName testName = new TestName(); + + public PropertyApisTest() { + super(testName, PropertyApisTest.class.getName()); + } + + @BeforeMethod + public void init() throws Exception { + // + // //Delete resource + // + // resourceDetails = new ResourceReqDetails(); + // resourceDetails.setResourceName("testresourceDetails"); + // + // resourceUtils.deleteResource_allVersions(resourceDetails, + // sdncDesignerDetails); + // + // //Create resource + // resourceDetails = createResource(sdncDesignerDetails, + // "testresourceDetails"); + + // Create property + // property.setPropertyName("test"); + // property.setPropertyType("integer"); + // property.setPropertySource("A&AI"); + // property.setPropertyDescription("test property"); + + // body = gson.toJson(property); + property = ElementFactory.getDefaultProperty(); + body = property.propertyToJsonString(); + // System.out.println(body); + // HTTP (for negative tests) + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncDesignerDetails.getUserId()); + + } + + @Test + public void testPropertyApis() throws Exception { + // Create property + // System.out.println ("---- Create Property (POST) ----"); + + String propertyId = UniqueIdBuilder.buildComponentPropertyUniqueId(getResourceId(resourceDetails), property.getName()); + + PropertyRestUtils.deleteProperty(getResourceId(resourceDetails), propertyId, sdncDesignerDetails); + RestResponse createPropertyResponse = PropertyRestUtils.createProperty(getResourceId(resourceDetails), body, + sdncDesignerDetails); + AssertJUnit.assertTrue("Expected result code - 201, received - " + createPropertyResponse.getErrorCode(), + createPropertyResponse.getErrorCode() == 201); + + // Get property + // System.out.println ("---- Get Property (GET) ----"); + RestResponse getPropertyResponse = PropertyRestUtils.getProperty(getResourceId(resourceDetails), propertyId, + sdncDesignerDetails); + AssertJUnit.assertTrue("Expected result code - 200, received - " + getPropertyResponse.getErrorCode(), + getPropertyResponse.getErrorCode() == 200); + + JSONObject jsonResp = (JSONObject) JSONValue.parse(getPropertyResponse.getResponse()); + + // assertTrue("Wrong 'type' in the + // response",jsonResp.get("type").equals(property.getPropertyType())); + // assertTrue("Wrong 'source' in the + // response",jsonResp.get("name").equals(property.getPropertyName())); + // assertTrue("Wrong 'name' in the + // response",jsonResp.get("source").equals(property.getPropertySource())); + // assertTrue("Wrong 'description' in the + // response",jsonResp.get("description").equals(property.getPropertyDescription())); + + // Update property + // System.out.println ("---- Update Property (UPDATE) ----"); + property.setPropertyDescription("Updated description"); + // body = gson.toJson(property); + body = property.propertyToJsonString(); + + RestResponse updatePropertyResponse = PropertyRestUtils.updateProperty(getResourceId(resourceDetails), + propertyId, body, sdncDesignerDetails); + AssertJUnit.assertTrue("Expected result code - 200, received - " + updatePropertyResponse.getErrorCode(), + updatePropertyResponse.getErrorCode() == 200); + + // Get property + // System.out.println ("---- Get Property (GET) ----"); + getPropertyResponse = PropertyRestUtils.getProperty(getResourceId(resourceDetails), propertyId, + sdncDesignerDetails); + AssertJUnit.assertTrue("Expected result code - 200, received - " + getPropertyResponse.getErrorCode(), + getPropertyResponse.getErrorCode() == 200); + + jsonResp = (JSONObject) JSONValue.parse(getPropertyResponse.getResponse()); + + // assertTrue("Wrong 'type' in the + // response",jsonResp.get("type").equals(property.getPropertyType())); + // assertTrue("Wrong 'source' in the + // response",jsonResp.get("name").equals(property.getPropertyName())); + // assertTrue("Wrong 'name' in the + // response",jsonResp.get("source").equals(property.getPropertySource())); + // assertTrue("Wrong 'description' in the + // response",jsonResp.get("description").equals(property.getPropertyDescription())); + + // Delete property + // System.out.println ("---- Delete Property (DELETE) ----"); + RestResponse deletePropertyResponse = PropertyRestUtils.deleteProperty(getResourceId(resourceDetails), + propertyId, sdncDesignerDetails); + AssertJUnit.assertTrue("Expected result code - 204, received - " + deletePropertyResponse.getErrorCode(), + deletePropertyResponse.getErrorCode() == 204); + + // Get property - verify that the property doesn't exist. + // System.out.println("---- GET - Property Not Found ----"); + getPropertyResponse = PropertyRestUtils.getProperty(getResourceId(resourceDetails), propertyId, + sdncDesignerDetails); + List variables = Arrays.asList(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables, + getPropertyResponse.getResponse()); + + } + + // -------------------------------------------------------------------------------------- + + protected String getPropertyId(ResourceReqDetails resource, PropertyReqDetails property) { + // return + // resource.getResourceName().toLowerCase()+".0.1."+property.getPropertyName(); + return UniqueIdBuilder.buildComponentPropertyUniqueId(resource.getUniqueId(), property.getName()); + } + + protected String getResourceId(ResourceReqDetails resource) { + // String resourceUid = + // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(), + // "0.1"); + + return resource.getUniqueId(); + } + + protected User createUser(String cspUserId, String firstName, String lastName, String email, String role) + throws Exception { + User sdncUserDetails = new User(firstName, lastName, cspUserId, email, role, null); + + User adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + UserRestUtils.createUser(sdncUserDetails, adminUser); + + return sdncUserDetails; + } + + protected ResourceReqDetails createResource(User sdncUserDetails, String resourceName) throws Exception { + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + // String category = ResourceCategoryEnum.DATABASE.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.0"; + String contactId = sdncUserDetails.getUserId(); + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, + derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), + ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); + // deleteResource(resourceName.toLowerCase()+".0.1",sdncUserDetails.getUserId()); + // TODO delete by name + // deleteResource(UniqueIdBuilder.buildResourceUniqueId(resourceName, + // "0.1"), sdncUserDetails.getUserId()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails); + AssertJUnit.assertTrue(createResource.getErrorCode().intValue() == 201); + String resourceId = ResponseParser.getUniqueIdFromResponse(createResource); + resourceDetails.setUniqueId(resourceId); + + return resourceDetails; + + } + + @Test + public void putReqToCreateUriNotAllowed() throws Exception { + // System.out.println("---- PUT request to Create uri - Not Allowed + // ----"); + String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails)); + RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void getReqToCreateUriNotAllowed() throws Exception { + // System.out.println("---- GET request to Create uri - Not Allowed + // ----"); + String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails)); + RestResponse propertyErrorResponse = httpRequest.httpSendGet(url, headersMap); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void deleteReqToCreateUriNotAllowed() throws Exception { + // System.out.println("---- DELETE request to Create uri - Not Allowed + // ----"); + String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails)); + RestResponse propertyErrorResponse = httpRequest.httpSendDelete(url, headersMap); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void postReqToUpdateUriNotAllowed() throws Exception { + // System.out.println("---- POST request to Update uri - Not Allowed + // ----"); + String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails), getPropertyId(resourceDetails, property)); + RestResponse propertyErrorResponse = httpRequest.httpSendPost(url, body, headersMap); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void deleteReqPropertyNotFound() throws Exception { + // System.out.println("---- DELETE - Property Not Found ----"); + String unknownPropertyId = getPropertyId(resourceDetails, property) + "111"; + String url = String.format(Urls.DELETE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails), unknownPropertyId); + RestResponse propertyErrorResponse = httpRequest.httpSendDelete(url, headersMap); + List variables = Arrays.asList(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void updateReqPropertyNotFound() throws Exception { + // System.out.println("---- PUT - Property Not Found ----"); + String unknownPropertyId = getPropertyId(resourceDetails, property) + "111"; + String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails), unknownPropertyId); + RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap); + List variables = Arrays.asList(""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void modifierNotTheStateOwner() throws Exception { + // System.out.println("---- The modifier is not the state owner - + // Operation Not Allowed ----"); + User sdncUserDetails2 = createUser("tu5555", "Test", "User", "tu5555@intl.sdc.com", "DESIGNER"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails2.getUserId()); + property.setPropertyDescription("new description"); + // body = gson.toJson(property); + body = property.propertyToJsonString(); + String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails), getPropertyId(resourceDetails, property)); + RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap); + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + propertyErrorResponse.getResponse()); + + } + + @Test + public void postReqInvalidContent() throws Exception { + // System.out.println("---- POST - Invalid Content ----"); + body = "invalid"; + String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails), getPropertyId(resourceDetails, property)); + RestResponse propertyErrorResponse = httpRequest.httpSendPost(url, body, headersMap); + + // System.out.println(propertyErrorResponse.getResponse()+" "+ + // propertyErrorResponse.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, + propertyErrorResponse.getResponse()); + } + + @Test + public void putReqInvalidContent() throws Exception { + + // Create property + // System.out.println ("---- Create Property (POST) ----"); + RestResponse createPropertyResponse = PropertyRestUtils.createProperty(getResourceId(resourceDetails), body, + sdncDesignerDetails); + assertTrue("Expected result code - 201, received - " + createPropertyResponse.getErrorCode(), + createPropertyResponse.getErrorCode() == 201); + + // System.out.println("---- PUT - Invalid Content ----"); + body = "invalid"; + + String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + getResourceId(resourceDetails), getPropertyId(resourceDetails, property)); + + // System.out.println(url + "\n" + body); + + RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap); + + // System.out.println(propertyErrorResponse.getResponse()+" "+ + // propertyErrorResponse.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, + propertyErrorResponse.getResponse()); + } + + // -------------------------------------------------------------------------------------- + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java new file mode 100644 index 0000000000..0ec6b00fdc --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java @@ -0,0 +1,53 @@ +/*- + * ============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.ci.tests.execute.resource; + +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.common.util.SerializationUtils; +import org.testng.annotations.Test; + +import fj.data.Either; + +public class CheckGetResource { + + public void checkGetVmmsc6() throws Exception { + + try { + + System.out.println("dddd"); + RestResponse getResource = ResourceRestUtils.getResource("96eb6583-2822-448b-a284-bfc144fa627e"); + + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + + Either serialize = SerializationUtils.serializeExt(resource); + + SerializationUtils.deserializeExt(serialize.left().value(), Resource.class, "ffff"); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java new file mode 100644 index 0000000000..d05dd1039a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java @@ -0,0 +1,1408 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.apache.http.client.ClientProtocolException; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapReqDef; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.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.NormativeTypesEnum; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils; +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.validation.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class ComponentRelationshipInVfTest extends ComponentBaseTest { + + public ComponentRelationshipInVfTest() { + super(new TestName(), ComponentRelationshipInVfTest.class.getName()); + } + + private ResourceReqDetails resourceDetailsVF; + private User designerUser; + private User adminUser; + private User testerUser; + private ResourceReqDetails resourceDetailsReq; + private ResourceReqDetails resourceDetailsCap; + + @BeforeMethod + public void before() throws Exception { + designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + + resourceDetailsVF = ElementFactory.getDefaultResourceByType("VF100", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, designerUser.getUserId(), ResourceTypeEnum.VF.toString()); + createResource(resourceDetailsVF, designerUser); + + resourceDetailsReq = ElementFactory.getDefaultResourceByType("SoftCompRouter", + NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, + designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType + // = + // VFC + resourceDetailsCap = ElementFactory.getDefaultResourceByType("MyCompute", NormativeTypesEnum.COMPUTE, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType + // = + // VFC + + } + + private void createResource(ResourceReqDetails resourceDetails, User user) throws Exception, IOException { + RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, user); + ResourceRestUtils.checkCreateResponse(createResourceResponse); + if (!resourceDetails.getResourceType().equals("VF")) + LifecycleRestUtils.changeResourceState(resourceDetails, user, "0.1", LifeCycleStatesEnum.CHECKIN); + } + + private void createAtomicResource(ResourceReqDetails resourceDetails, User user) throws Exception { + createResource(resourceDetails, user); + } + + private RequirementCapabilityRelDef setRelationshipBetweenInstances(ComponentInstance riReq, + ComponentInstance riCap, CapReqDef capReqDef) throws Exception { + + String capbilityUid = capReqDef.getCapabilities().get("tosca.capabilities.Container").get(0).getUniqueId(); + String requirementUid = capReqDef.getRequirements().get("tosca.capabilities.Container").get(0).getUniqueId(); + + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + requirementDef.setFromNode(riReq.getUniqueId()); + requirementDef.setToNode(riCap.getUniqueId()); + + RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(); + pair.setRequirementOwnerId(riReq.getUniqueId()); + pair.setCapabilityOwnerId(riCap.getUniqueId()); + pair.setRequirement("host"); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("tosca.capabilities.Container"); + pair.setRelationships(relationship); + pair.setCapabilityUid(capbilityUid); + pair.setRequirementUid(requirementUid); + List relationships = new ArrayList<>(); + relationships.add(pair); + requirementDef.setRelationships(relationships); + return requirementDef; + } + + private ComponentInstance createComponentInstance(ResourceReqDetails res) throws Exception { + return createComponentInstance(res, designerUser); + } + + private ComponentInstance createComponentInstance(ResourceReqDetails res, User user, ResourceReqDetails vf) + throws Exception { + RestResponse response = ResourceRestUtils.createResourceInstance(res, user, vf.getUniqueId()); + ResourceRestUtils.checkCreateResponse(response); + ComponentInstance compInstance = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class); + return compInstance; + } + + private ComponentInstance createComponentInstance(ResourceReqDetails res, User user) throws Exception { + return createComponentInstance(res, user, resourceDetailsVF); + } + + private void createTwoAtomicResourcesByType(String reqType, String capType, User user1, User user2) + throws Exception { + resourceDetailsReq.setResourceType(reqType); + createAtomicResource(resourceDetailsReq, user1); + resourceDetailsCap.setResourceType(capType); + createAtomicResource(resourceDetailsCap, user2); + } + + private void createTwoAtomicResourcesByType(String reqType, String capType) throws Exception { + createTwoAtomicResourcesByType(reqType, capType, designerUser, designerUser); + } + + @Test + public void associateInVF() throws Exception { + + createTwoAtomicResourcesByType(ResourceTypeEnum.VFC.toString(), ResourceTypeEnum.VFC.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDef = getResourceReqCap(); + + List capList = capReqDef.getCapabilities().get("tosca.capabilities.Container"); + List reqList = capReqDef.getRequirements().get("tosca.capabilities.Container"); + + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + requirementDef.setFromNode(riReq.getUniqueId()); + requirementDef.setToNode(riCap.getUniqueId()); + + RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(); + pair.setRequirementOwnerId(riReq.getUniqueId()); + pair.setCapabilityOwnerId(riCap.getUniqueId()); + pair.setRequirement("host"); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("tosca.capabilities.Container"); + pair.setRelationships(relationship); + pair.setCapabilityUid(capList.get(0).getUniqueId()); + pair.setRequirementUid(reqList.get(0).getUniqueId()); + List relationships = new ArrayList<>(); + relationships.add(pair); + requirementDef.setRelationships(relationships); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(designerUser, + resourceDetailsVF); + capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + + List list = capReqDef.getRequirements().get("tosca.capabilities.Container"); + assertEquals("Check requirement", null, list); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue()); + + getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(designerUser, resourceDetailsVF); + capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + + list = capReqDef.getRequirements().get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, list.size()); + } + + //////////////////////////////// Q A ////////////////////////////// + private boolean checkRealtionship(String fromNode, String toNode, String resourceUniqueId) throws Exception { + List componentInstancesRelations = getComponentInstancesRelations( + resourceUniqueId); + RequirementCapabilityRelDef requirementCapabilityRelDef = componentInstancesRelations.get(0); + boolean fromNodeCheck = requirementCapabilityRelDef.getFromNode().equals(fromNode); + boolean toNodeCheck = requirementCapabilityRelDef.getToNode().equals(toNode); + + return fromNodeCheck && toNodeCheck; + } + + private List getComponentInstancesRelations(String resourceUniqueId) + throws ClientProtocolException, IOException { + Resource resource = getVfAsResourceObject(resourceUniqueId); + List componenRelationInstances = resource.getComponentInstancesRelations(); + + return componenRelationInstances; + } + + private Resource getVfAsResourceObject(String resourceUniqueId) throws ClientProtocolException, IOException { + RestResponse getResource = ResourceRestUtils.getResource(resourceUniqueId); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + return resource; + } + + private List getComponentInstancesList(String resourceUniqueId) throws Exception { + Resource resource = getVfAsResourceObject(resourceUniqueId); + List componentInstances = resource.getComponentInstances(); + return componentInstances; + } + + @Test + public void associateCpToCpTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + CapReqDef capReqDef = getResourceReqCap(); + + requirementsBeforeAssociate.remove("tosca.capabilities.Container"); + assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate)); + + List list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container"); + for (CapabilityDefinition cap : list) { + cap.setMinOccurrences("0"); + } + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + } + + private CapReqDef getResourceReqCap(ResourceReqDetails res) throws IOException { + RestResponse getResourceBeforeAssociate = ComponentRestUtils.getComponentRequirmentsCapabilities(designerUser, + resourceDetailsVF); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceBeforeAssociate.getResponse(), CapReqDef.class); + return capReqDef; + } + + private CapReqDef getResourceReqCap() throws IOException { + return getResourceReqCap(resourceDetailsVF); + } + + @Test + public void associateCpToVLTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + CapReqDef capReqDef = getResourceReqCap(); + + requirementsBeforeAssociate.remove("tosca.capabilities.Container"); + assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate)); + + List list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container"); + for (CapabilityDefinition cap : list) { + cap.setMinOccurrences("0"); + } + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + + } + + // Error handling + // ELLA - more informative error + @Test + public void associateCpToVlInVFCTest() throws Exception { + ResourceReqDetails vfcDetails = ElementFactory.getDefaultResourceByType("VFC100", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, designerUser.getUserId(), ResourceTypeEnum.VFC.toString()); + RestResponse createVfcResponse = ResourceRestUtils.createResource(vfcDetails, designerUser); + ResourceRestUtils.checkCreateResponse(createVfcResponse); + + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + vfcDetails.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue()); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "SoftCompRouter 1", + // "MyCompute 2", + // "host" + // ] + } + + // Error handling + @Test + public void associateCpToVfTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riCapInVfInstance = createComponentInstance(resourceDetailsCap, designerUser, + resourceDetailsVF); + ComponentInstance riReqInVfInstance = createComponentInstance(resourceDetailsReq, designerUser, + resourceDetailsVF); + + ResourceReqDetails vfHigh = new ResourceReqDetails(resourceDetailsVF, "0.1"); + vfHigh.setName("vfHigh"); + vfHigh.setTags(new ArrayList(Arrays.asList(vfHigh.getName()))); + vfHigh.setResourceType(ResourceTypeEnum.VF.toString()); + createResource(vfHigh, designerUser); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq, designerUser, vfHigh); + LifecycleRestUtils.changeResourceState(resourceDetailsVF, designerUser, "0.1", LifeCycleStatesEnum.CHECKIN); + ComponentInstance riCap = createComponentInstance(resourceDetailsVF, designerUser, vfHigh); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + associateInstances.getResponse()); + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "SoftCompRouter 1", + // "VF100 2", + // "host" + // ] + } + + // Error handling + @Test + public void associateVfcToVfcNotFoundTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.VFC.toString(), ResourceTypeEnum.VFC.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + riCap.setUniqueId("123"); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST.name(), + new ArrayList(), associateInstances.getResponse()); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "SoftCompRouter 1", + // "012f6dcd-bcdf-4d9b-87be-ff1442b95831.5d265453-0b6a-4453-8f3d-57a253b88432.softcomprouter1", + // "host" + } + + @Test + public void associateCpToDeletedVfcTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VFC.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(), + designerUser.getUserId()); + ResourceRestUtils.checkDeleteResponse(deleteResourceResponse); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + } + + @Test + public void associateCpToDeletedVlTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(), + designerUser.getUserId()); + ResourceRestUtils.checkDeleteResponse(deleteResourceResponse); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + } + + @Test + public void associateCpToDeletedCpTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(), + designerUser.getUserId()); + ResourceRestUtils.checkDeleteResponse(deleteResourceResponse); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + } + + // Error handling + @Test + public void associateCpToDeletedCpInstanceTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse deleteComponentInstance = ComponentInstanceRestUtils.deleteComponentInstance(designerUser, + resourceDetailsVF.getUniqueId(), riReq.getUniqueId(), ComponentTypeEnum.RESOURCE); + ComponentInstanceRestUtils.checkDeleteResponse(deleteComponentInstance); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue()); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "7d6aca08-9321-4ea1-a781-c52c8214a30e.c0e63466-5283-44d8-adff-365c0885a6ba.softcomprouter1", + // "MyCompute 2", + // "host" + // ] + } + + // Error handling + @Test + public void associateVfcToDeletedVFCInstanceTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.VFC.toString(), ResourceTypeEnum.VFC.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse deleteComponentInstance = ComponentInstanceRestUtils.deleteComponentInstance(designerUser, + resourceDetailsVF.getUniqueId(), riReq.getUniqueId(), ComponentTypeEnum.RESOURCE); + ComponentInstanceRestUtils.checkDeleteResponse(deleteComponentInstance); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue()); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "7d6aca08-9321-4ea1-a781-c52c8214a30e.c0e63466-5283-44d8-adff-365c0885a6ba.softcomprouter1", + // "MyCompute 2", + // "host" + // ] + } + + @Test + public void associateWithDifferentOwnerOfVf() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), resourceDetailsVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + associateInstances.getResponse()); + + CapReqDef capReqDef = getResourceReqCap(); + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + Map> requirementsAfterAssociate = capReqDef.getRequirements(); + + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + assertTrue(requirementsAfterAssociate.equals(requirementsBeforeAssociate)); + } + + @Test + public void associateWithTester() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), resourceDetailsVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + associateInstances.getResponse()); + + CapReqDef capReqDef = getResourceReqCap(); + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + Map> requirementsAfterAssociate = capReqDef.getRequirements(); + + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + assertTrue(requirementsAfterAssociate.equals(requirementsBeforeAssociate)); + } + + // Error handling + @Test + public void associateCpToVLIntoVFNotFound() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + String uidNotFound = "123"; + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + uidNotFound, ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 404, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), + new ArrayList(Arrays.asList("")), associateInstances.getResponse()); + + // {"serviceException":{"messageId":"SVC4063","text":"Error: Requested + // '%1' resource was not found.","variables":[""]}}} + } + + // Error Handling + @Test + public void associateCpToVlWithMissingUid() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + requirementDef.setToNode(""); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue()); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), + // new ArrayList(), associateInstances.getResponse()); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "SoftCompRouter 1", + // "fd3a689b-fa1c-4105-933d-d1310e642f05.95bce626-ce73-413b-8c14-2388d1589d5c.softcomprouter1", + // "host" + // ] + } + + @Test + public void associateInServiceWithUidOfVf() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", 404, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), + new ArrayList(Arrays.asList("")), associateInstances.getResponse()); + } + + @Test + public void associateCpToVl_DifferentOwners() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString(), designerUser, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2)); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + CapReqDef capReqDef = getResourceReqCap(); + + requirementsBeforeAssociate.remove("tosca.capabilities.Container"); + assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate)); + + List list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container"); + for (CapabilityDefinition cap : list) { + cap.setMinOccurrences("0"); + } + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + } + + @Test(enabled = false) + public void associateToNotCheckedoutVf() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse changeResourceStateToCheckin = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckin); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + associateInstances.getResponse()); + + CapReqDef capReqDef = getResourceReqCap(); + assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDef.getCapabilities().equals(capabilitiesBeforeAssociate)); + + String firstUniqueId = resourceDetailsVF.getUniqueId(); + + // checkout + + RestResponse changeResourceStateToCheckout = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout); + String secondUniqueId = resourceDetailsVF.getUniqueId(); + + CapReqDef capReqDefAfterFirstCheckout = getResourceReqCap(); + Map> capabilitiesAfterFirstCheckout = capReqDefAfterFirstCheckout + .getCapabilities(); + Map> requirementsAfterFirstCheckout = capReqDefAfterFirstCheckout + .getRequirements(); + + requirementDef = setUidsOfInstancesAfterLifecycleStateChange(riReq, riCap, capReqDefBeforeAssociate); + + RestResponse firstAssociateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, firstAssociateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + CapReqDef capReqDefAfterFirstAssociate = getResourceReqCap(); + Map> capabilitiesAfterFirstAssociate = capReqDefAfterFirstAssociate + .getCapabilities(); + Map> requirementsAfterFirstAssociate = capReqDefAfterFirstAssociate + .getRequirements(); + + requirementsAfterFirstCheckout.remove("tosca.capabilities.Container"); + assertTrue(requirementsAfterFirstAssociate.equals(requirementsAfterFirstCheckout)); + assertTrue(capabilitiesAfterFirstAssociate.equals(capabilitiesAfterFirstCheckout)); + + resourceDetailsVF.setUniqueId(firstUniqueId); + CapReqDef capReqDefOfFirstVersion = getResourceReqCap(); + Map> capabilitiesOfFirstVersion = capReqDefOfFirstVersion.getCapabilities(); + Map> requirementsOfFirstVersion = capReqDefOfFirstVersion.getRequirements(); + + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + assertTrue(requirementsBeforeAssociate.equals(requirementsOfFirstVersion)); + assertTrue(capabilitiesBeforeAssociate.equals(capabilitiesOfFirstVersion)); + + // checkin-checkout + resourceDetailsVF.setUniqueId(secondUniqueId); + RestResponse changeResourceStateToCheckin2 = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckin2); + RestResponse changeResourceStateToCheckout2 = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout2); + + List componentInstancesRelations = getComponentInstancesRelations( + resourceDetailsVF.getUniqueId()); + assertFalse(componentInstancesRelations.isEmpty()); + assertEquals(1, componentInstancesRelations.size()); + List componentInstancesList = getComponentInstancesList(resourceDetailsVF.getUniqueId()); + for (ComponentInstance comp : componentInstancesList) { + String instanceUid = comp.getUniqueId(); + assertTrue(checkNodesInRelations(instanceUid, componentInstancesRelations.get(0))); + } + assertEquals(2, componentInstancesList.size()); + + } + + private RequirementCapabilityRelDef setUidsOfInstancesAfterLifecycleStateChange(ComponentInstance riReq, + ComponentInstance riCap, CapReqDef capReqDefBeforeAssociate) + throws ClientProtocolException, IOException, Exception { + RequirementCapabilityRelDef requirementDef; + // RestResponse getResourceResponse = + // ResourceRestUtils.getResource(resourceDetailsVF.getUniqueId()); + // Resource resource_0_2 = + // ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), + // Resource.class); + // List componentInstances = + // resource_0_2.getComponentInstances(); + List componentInstances = getComponentInstancesList(resourceDetailsVF.getUniqueId()); + + for (ComponentInstance comp : componentInstances) { + if (comp.getName().equals(riReq.getName())) { + riReq.setUniqueId(comp.getUniqueId()); + } else if (comp.getName().equals(riCap.getName())) { + riCap.setUniqueId(comp.getUniqueId()); + } + } + requirementDef = setRelationshipBetweenInstances(riReq, riCap, capReqDefBeforeAssociate); + return requirementDef; + } + + private boolean checkNodesInRelations(String instanceUid, RequirementCapabilityRelDef relation) { + if (relation.getToNode().equals(instanceUid)) { + return true; + } else if (relation.getFromNode().equals(instanceUid)) { + return true; + } else { + return false; + } + } + + @Test + public void associateOneOfTwoCPsToVl_ThenDiscocciate() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + ResourceReqDetails secondResourceDetailsReq = new ResourceReqDetails(resourceDetailsReq, "0.1"); + secondResourceDetailsReq.setName("secondCP"); + secondResourceDetailsReq.setTags(Arrays.asList(secondResourceDetailsReq.getName())); + createAtomicResource(secondResourceDetailsReq, designerUser); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riReq2 = createComponentInstance(secondResourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + CapReqDef capReqDef = getResourceReqCap(); + + List expectedList = requirementsBeforeAssociate.get("tosca.capabilities.Container"); + for (RequirementDefinition req : expectedList) { + if (req.getOwnerName().equals(riReq2.getName())) { + expectedList = new ArrayList(Arrays.asList(req)); + break; + } + } + requirementsBeforeAssociate.put("tosca.capabilities.Container", expectedList); + assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate)); + + List list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container"); + for (CapabilityDefinition cap : list) { + cap.setMinOccurrences("0"); + } + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + + // second relationship + + RequirementCapabilityRelDef secondRequirementDef = setRelationshipBetweenInstances(riReq2, riCap, + capReqDefBeforeAssociate); + RestResponse secondAssociateInstances = ComponentInstanceRestUtils.associateInstances(secondRequirementDef, + designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, secondAssociateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(secondRequirementDef.getFromNode(), secondRequirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + CapReqDef capReqDefAfterSecondAssociation = getResourceReqCap(); + + requirementsBeforeAssociate.remove("tosca.capabilities.Container"); + assertTrue(capReqDefAfterSecondAssociation.getRequirements().equals(requirementsBeforeAssociate)); + + Map> capabilitiesAfterSecondAssociate = capReqDefAfterSecondAssociation + .getCapabilities(); + assertTrue(capabilitiesAfterSecondAssociate.equals(capabilitiesBeforeAssociate)); + + // dissociate + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(secondRequirementDef, + designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + CapReqDef capReqDefAfterDissociation = getResourceReqCap(); + Map> capabilitiesAfterDissociate = capReqDefAfterDissociation + .getCapabilities(); + Map> requirementsAfterDissociate = capReqDefAfterDissociation + .getRequirements(); + + assertTrue(capabilitiesAfterDissociate.equals(capReqDef.getCapabilities())); + requirementsBeforeAssociate.put("tosca.capabilities.Container", expectedList); + assertTrue(requirementsAfterDissociate.equals(requirementsBeforeAssociate)); + } + + @Test + public void associateNotCompitableCapAndReq() throws Exception { + resourceDetailsReq = ElementFactory.getDefaultResourceByType("Database", NormativeTypesEnum.DATABASE, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType + // = + // VFC + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + assertTrue(requirementDef.getRelationships().size() == 1); + String requirement = requirementDef.getRelationships().get(0).getRequirement(); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 404, associateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND.name(), + new ArrayList(Arrays.asList(riReq.getName(), riCap.getName(), requirement)), + associateInstances.getResponse()); + + CapReqDef capReqDef = getResourceReqCap(); + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + Map> requirementsAfterAssociate = capReqDef.getRequirements(); + + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + assertTrue(requirementsAfterAssociate.equals(requirementsBeforeAssociate)); + + } + + @Test + public void disassociateCpAndCpTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + } + + @Test + public void disassociateCpAndVfcTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VFC.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + } + + @Test + public void disassociateCpAndVLTest() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + } + + // Error handliing + // in the error should we get the unique id of instances instead of names + @Test + public void disassociateNotFoundAssociation() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + String requirementName = requirementDef.getRelationships().get(0).getRequirement(); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(), + new ArrayList(Arrays.asList(riReq.getName(), riCap.getName(), requirementName)), + dissociateInstances.getResponse()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + } + + // Error handliing + @Test + public void disassociateRelationInVfNotFound() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + String uidNotFound = "123"; + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + uidNotFound, ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), + new ArrayList(Arrays.asList(uidNotFound)), dissociateInstances.getResponse()); + + // "serviceException": { + // "messageId": "SVC4063", + // "text": "Error: Requested \u0027%1\u0027 resource was not found.", + // "variables": [ + // "" + // ] + } + + @Test + public void disassociateWithDifferentDesigner() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), resourceDetailsVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, dissociateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + dissociateInstances.getResponse()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + + } + + @Test + public void disassociateWithTester() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), resourceDetailsVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, dissociateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + dissociateInstances.getResponse()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertNotNull("Requierment is null after disassociate with tester", listOfRequierments); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + } + + @Test + public void disassociateServiceWithUidOfVF() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VFC.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), + new ArrayList(Arrays.asList("")), dissociateInstances.getResponse()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertTrue(listOfRequierments == null); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).size() != 0); + } + + @Test + public void disassociateWithEmptyVfUid() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + "", ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue()); + + CapReqDef capReqDef = getResourceReqCap(); + + requirementsBeforeAssociate.remove("tosca.capabilities.Container"); + assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate)); + + List list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container"); + for (CapabilityDefinition cap : list) { + cap.setMinOccurrences("0"); + } + + Map> capabilitiesAfterAssociate = capReqDef.getCapabilities(); + assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate)); + } + + @Test + public void disassociateOneComponentDeleted() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + + RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(), + designerUser.getUserId()); + ResourceRestUtils.checkDeleteResponse(deleteResourceResponse); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + + List listOfRequierments = capReqDefAfterDissociate.getRequirements() + .get("tosca.capabilities.Container"); + assertEquals("Check requirement", 1, listOfRequierments.size()); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + } + + @Test + public void disassociateNotCheckedoutVf() throws Exception { + createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString()); + + ComponentInstance riReq = createComponentInstance(resourceDetailsReq); + ComponentInstance riCap = createComponentInstance(resourceDetailsCap); + + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(); + Map> capabilitiesBeforeAssociate = capReqDefBeforeAssociate + .getCapabilities(); + Map> requirementsBeforeAssociate = capReqDefBeforeAssociate + .getRequirements(); + + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap, + capReqDefBeforeAssociate); + + RestResponse changeResourceStateToCheckin = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckin); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", 409, dissociateInstances.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + dissociateInstances.getResponse()); + + CapReqDef capReqDefAfterDissociate = getResourceReqCap(); + assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate)); + assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate)); + + RestResponse changeResourceStateToCheckout = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout); + + requirementDef = setUidsOfInstancesAfterLifecycleStateChange(riReq, riCap, capReqDefBeforeAssociate); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser, + resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF.getUniqueId())); + + RestResponse secondDisociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, secondDisociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + RestResponse changeResourceStateToCheckout2 = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout2); + RestResponse changeResourceStateToCheckout3 = LifecycleRestUtils.changeResourceState(resourceDetailsVF, + designerUser, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout3); + + assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java new file mode 100644 index 0000000000..50d1056d76 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java @@ -0,0 +1,2222 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.validation.constraints.AssertTrue; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.Rule; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.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.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedResourceAuditJavaObject; +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; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +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.ComponentInstanceRestUtils; +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.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +/** + * @author yshlosberg + * + */ +public class CreateResourceApiTest extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(CreateResourceApiTest.class.getName()); + + String contentTypeHeaderData = "application/json"; + String acceptHeaderDate = "application/json"; + String resourceVersion = "0.1"; + + @Rule + public static TestName name = new TestName(); + + public CreateResourceApiTest() { + super(name, CreateResourceApiTest.class.getName()); + } + + @Test + public void createResourceTest() throws Exception { + + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // ResourceReqDetails resourceDetails = new + // ResourceReqDetails(resourceName, description, resourceTags, category, + // derivedFrom, vendorName, vendorRelease, contactId, icon); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + String resourceName = resourceDetails.getName(); + resourceDetails.setTags(Arrays.asList(resourceName, resourceName, resourceName, resourceName, "tag2", "tag2")); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @Test + public void createResourceNonDefaultResourceTypeTest() throws Exception { + + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + String resourceType = ResourceTypeEnum.CP.toString(); + resourceDetails.setResourceType(resourceType); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + resourceRespJavaObject.setResourceType(resourceType); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @Test + public void createResourceTest_costAndLicenseType() throws Exception { + + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + String resourceVersion = "0.1"; + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + + } + + // ////Benny + @Test + public void createResourceTest_CostIsMissing() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + // resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + String resourceVersion = "0.1"; + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + } + + @Test + public void createResourceTest_LicenseTypeMissing() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + // resourceDetails.setLicenseType("User"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + String resourceVersion = "0.1"; + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + } + + @Test + public void createResourceTest_LicenseType_Installation() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("99999.999"); + resourceDetails.setLicenseType("Installation"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + String resourceVersion = "0.1"; + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + } + + @Test + public void createResourceTest_LicenseType_CPU() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("0.0"); + resourceDetails.setLicenseType("CPU"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + // validate response + String resourceVersion = "0.1"; + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + } + + @Test + public void createResourceTest_LicenseType_Uppercase() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("0.0"); + resourceDetails.setLicenseType("INSTALLATION"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage()); + } + + @Test + public void createResourceTest_LicenseType_Invalid() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("0.0"); + resourceDetails.setLicenseType("CPUUU"); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage()); + } + + @Test + public void createResourceTest_CostValidation_noNumeric() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + resourceDetails.setCost("12355.34b"); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + } + + @Test + public void createResourceTest_CostValidation_valueLength() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + + // Adding invalid cost + resourceDetails.setCost("12355.3434"); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + } + + @Test + public void createResourceTest_CostValidation_PriceLimitations() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + + // Adding invalid cost + RestResponse createResponse; + // create resource + + resourceDetails.setCost("000000.000"); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + /* + * resourceDetails.setCost("0550.457"); createResponse = + * resourceUtils.createResource(resourceDetails, sdncModifierDetails); + * assertNotNull("check response object is not null after create resource" + * , createResponse); + * assertNotNull("check error code exists in response after create resource" + * , createResponse.getErrorCode()); + * assertEquals("Check response code after create resource", 400, + * createResponse.getErrorCode().intValue()); + * assertEquals("Check response code after create resource", + * "Bad Request", createResponse.getResponseMessage().toString()); + */ + + resourceDetails.setCost("1"); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + resourceDetails.setCost("123555.340"); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + resourceDetails.setCost("123.4570"); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + resourceDetails.setCost("123555.30"); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + resourceDetails.setCost("123.5550"); + createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", + createResponse.getResponseMessage().toString()); + + } + + @Test + public void createResourceTest_CostIsNull() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + resourceDetails.setCost(""); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage()); + + } + + @Test + public void createResourceTest_LicenseIsNull() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // set resource details + String resourceName = "CISCO4572"; + String description = "description"; + // Duplicate tags are allowed and should be de-duplicated by the server + // side + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add(resourceName); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + // Adding cost and licenseType + resourceDetails.setCost("12355.345"); + resourceDetails.setLicenseType("User"); + resourceDetails.setLicenseType(""); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue()); + assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage()); + + } + + @Test + public void createResourceTest_uri_methods() throws Exception { + + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + ResourceReqDetails resourceDetails = createRandomResource(); + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + log.debug(userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + + RestResponse createResourceResponse2 = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap); + + // validate response + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_ALLOWED.name()); + + assertNotNull("check response object is not null after create resource", createResourceResponse2); + assertNotNull("check error code exists in response after create resource", + createResourceResponse2.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), + createResourceResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + createResourceResponse2.getResponse()); + + } + + private ResourceReqDetails createRandomResource() { + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + return resourceDetails; + } + + @Test + public void createResource_role_tester() throws Exception { + + // init TESTER user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + + ResourceReqDetails resourceDetails2 = createRandomResource(); + + // create resource + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + restResponse2.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.TESTER.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.TESTER.getUserName()); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + // TODO DE171450(to check) + @Test + public void createResource_role_DESIGNER() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceDetails = createRandomResource(); + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + // validate response + assertNotNull("check response object is not null after create resource", restResponse); + assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode()); + assertEquals( + "Check response code after create resource, response message is: " + restResponse.getResponseMessage(), + 201, restResponse.getErrorCode().intValue()); + + } + + @Test + public void createResource_missing_header() throws Exception { + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + ResourceReqDetails resourceDetails = createRandomResource(); + + // set null in userId header + sdncModifierDetails.setUserId(null); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), variables, + restResponse2.getResponse()); + + // //validate audit + // + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // resourceUtils.constructFieldsForAuditValidation(resourceDetails,resourceVersion); + // + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setModifierUid("null null"); + // expectedResourceAuditJavaObject.setModifierName("null null"); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setCurrState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrVersion(""); + // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + // + // String auditDesc = + // AuditValidationUtils.buildAuditDescription(errorInfo, variables); + // expectedResourceAuditJavaObject.setDesc(auditDesc); + // + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction); + // TODO: yshlosberg enable back + + } + + @Test + public void createResource_existing_resource() throws Exception { + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // ResourceReqDetails resourceDetails = createRandomResource(); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + + // create resource + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + assertNotNull("check response object is not null after create resource", restResponse); + assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + + // set resource details + ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource(); + resourceDetails2.setName(resourceDetails.getName()); + + // clean ES DB + DbUtils.cleanAllAudits(); + + // create resource + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource", resourceDetails2.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_category() throws Exception { + + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + ; + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + category = null; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_empty_category() throws Exception { + + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + category = ""; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_tags() throws Exception { + + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + ; + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_TAGS.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_TAGS.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + // TODO DE171450(to check) + @Test + public void createResourceTest_with_multiple_tags() throws Exception { + + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // // set resource details + // String resourceName = "CISCO4"; + // String description = "description"; + // ArrayList resourceTags = new ArrayList(); + // resourceTags.add(resourceName); + // resourceTags.add("tag2"); + // String category = ResourceServiceCategoriesEnum.VOIP.getValue(); + // ArrayList derivedFrom = new ArrayList(); + // derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + // String vendorName = "Oracle"; + // String vendorRelease = "1.5"; + // String icon = "myICON"; + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setTags(Arrays.asList(resourceDetails.getName(), "tag2")); + + // create resource + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + assertNotNull("check response object is not null after create resource", restResponse); + assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + + } + + @Test + public void createResourceTest_empty_tag() throws Exception { + + // init ADMIN user + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(""); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name()); + + assertNotNull("check response object is not null after create resouce", restResponse); + assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), restResponse.getErrorCode()); + + List variables = Arrays.asList("Resource", "tag"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, + restResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_with_empty_vendorName() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + vendorName = ""; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_NAME.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), variables, + restResponse2.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_vendorName() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + vendorName = null; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + assertNotNull("check response object is not null after create resource", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create resource", 400, restResponse2.getErrorCode().intValue()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), variables, + restResponse2.getResponse()); + + } + + @Test + public void createResourceTest_with_empty_vendorRelease() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("root"); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + vendorRelease = ""; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_RELEASE.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_RELEASE.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_vendorRelease() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + vendorRelease = null; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_RELEASE.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_RELEASE.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_with_empty_contactId() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + contactId = ""; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CONTACT.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_contactId() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + contactId = null; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CONTACT.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_with_empty_icon() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + icon = ""; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_ICON.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_icon() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + icon = null; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_ICON.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_with_empty_description() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + description = ""; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createResourceTest_without_description() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // set resource details + String resourceName = "CISCO4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + // set resource details + description = null; + + ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + // create resource + + RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails); + + // validate response + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name()); + + assertNotNull("check response object is not null after create resouce", restResponse2); + assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode()); + + List variables = Arrays.asList("Resource"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), variables, + restResponse2.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails2, resourceVersion); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createAndGetResourceByNameAndVersion() throws Exception { + + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + ResourceReqDetails resourceDetailsComp = ElementFactory.getDefaultResource("testresourceComp", + NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, sdncModifierDetails.getUserId()); + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetailsComp, sdncModifierDetails); + // validate response + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + String resourceVersion = "0.1"; + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetailsComp, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResourceByNameAndVersion( + sdncModifierDetails.getUserId(), resourceDetailsComp.getName(), resourceDetailsComp.getVersion()); + assertEquals("Check response code after delete resource", 200, resourceGetResponse.getErrorCode().intValue()); + // Resource resource = + // ResourceRestUtils.parseResourceFromListResp(resourceGetResponse); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + // resourceDetailsComp.setUniqueId(resource.getUniqueId()); + + } + + @Test + public void createResourceResourceTypeNotExistsTest() throws Exception { + + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + String resourceType = "NOT EXISTS"; + resourceDetails.setResourceType(resourceType); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name()); + + assertNotNull("check response object is not null after create resouce", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), createResponse.getErrorCode()); + + List variables = new ArrayList<>(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, + createResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resourceDetails, resourceVersion); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @Test + public void createResourceResourceTypeEmptyTest() throws Exception { + + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + // String resourceType = ""; + // resourceDetails.setResourceType(resourceType); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // ErrorInfo errorInfo = + // ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name()); + // + // assertNotNull("check response object is not null after create + // resouce", createResponse); + // assertNotNull("check error code exists in response after create + // resource", createResponse.getErrorCode()); + // assertEquals("Check response code after create service", + // errorInfo.getCode(), createResponse.getErrorCode()); + // + // List variables = new ArrayList<>(); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), + // variables, createResponse.getResponse()); + // + // // validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // Convertor.constructFieldsForAuditValidation(resourceDetails, + // resourceVersion); + // String auditAction = "Create"; + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState(""); + // expectedResourceAuditJavaObject.setCurrVersion(""); + // expectedResourceAuditJavaObject.setResourceName(""); + // expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId()); + // expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getFullName()); + // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + // + // String auditDesc = + // AuditValidationUtils.buildAuditDescription(errorInfo, variables); + // expectedResourceAuditJavaObject.setDesc(auditDesc); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + } + + @Test + public void checkInvariantUuidIsImmutable() throws Exception { + // choose the user to create resource + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!"; + resourceDetails.setInvariantUUID(invariantUuidDefinedByUser); + String resourceName = resourceDetails.getName(); + resourceDetails.setTags(Arrays.asList(resourceName, resourceName, resourceName, resourceName, "tag2", "tag2")); + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails); + BaseRestUtils.checkStatusCode(createResponse, "create request failed", false, 201); + // validate response + assertNotNull("check response object is not null after create resource", createResponse); + assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode()); + assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue()); + + Resource resourceCreation = ResponseParser.convertResourceResponseToJavaObject(createResponse.getResponse()); + String invariantUUIDcreation = resourceCreation.getInvariantUUID(); + // validate response + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncUserDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(resourceGetResponse); + Resource resourceGetting = ResponseParser + .convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + String invariantUUIDgetting = resourceGetting.getInvariantUUID(); + assertEquals(invariantUUIDcreation, invariantUUIDgetting); + + // Update resource with new invariant UUID + RestResponse restResponseUpdate = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncUserDetails, + resourceDetails.getUniqueId()); + BaseRestUtils.checkSuccess(restResponseUpdate); + Resource updatedResource = ResponseParser.convertResourceResponseToJavaObject(restResponseUpdate.getResponse()); + String invariantUUIDupdating = updatedResource.getInvariantUUID(); + assertEquals(invariantUUIDcreation, invariantUUIDupdating); + + // Do checkin + RestResponse restResponseCheckin = LifecycleRestUtils.changeResourceState(resourceDetails, sdncUserDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + BaseRestUtils.checkSuccess(restResponseCheckin); + Resource checkinResource = ResponseParser + .convertResourceResponseToJavaObject(restResponseCheckin.getResponse()); + String invariantUUIDcheckin = checkinResource.getInvariantUUID(); + String version = checkinResource.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcheckin); + assertEquals(version, "0.1"); + + // Do checkout + RestResponse restResponseCheckout = LifecycleRestUtils.changeResourceState(resourceDetails, sdncUserDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + BaseRestUtils.checkSuccess(restResponseCheckout); + Resource ResourceResource = ResponseParser + .convertResourceResponseToJavaObject(restResponseCheckout.getResponse()); + String invariantUUIDcheckout = ResourceResource.getInvariantUUID(); + version = ResourceResource.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcheckout); + assertEquals(version, "0.2"); + + // do certification request + RestResponse restResponseCertificationRequest = LifecycleRestUtils.changeResourceState(resourceDetails, + sdncUserDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + BaseRestUtils.checkSuccess(restResponseCertificationRequest); + Resource certificationRequestResource = ResponseParser + .convertResourceResponseToJavaObject(restResponseCertificationRequest.getResponse()); + String invariantUUIDcertificationRequest = certificationRequestResource.getInvariantUUID(); + version = certificationRequestResource.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcertificationRequest); + assertEquals(version, "0.2"); + + // start certification + RestResponse restResponseStartCertification = LifecycleRestUtils.changeResourceState(resourceDetails, + sdncUserDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + BaseRestUtils.checkSuccess(restResponseStartCertification); + Resource startCertificationRequestResource = ResponseParser + .convertResourceResponseToJavaObject(restResponseStartCertification.getResponse()); + String invariantUUIDStartCertification = startCertificationRequestResource.getInvariantUUID(); + version = startCertificationRequestResource.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDStartCertification); + assertEquals(version, "0.2"); + + // certify + RestResponse restResponseCertify = LifecycleRestUtils.changeResourceState(resourceDetails, sdncUserDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + BaseRestUtils.checkSuccess(restResponseCertify); + Resource certifyResource = ResponseParser + .convertResourceResponseToJavaObject(restResponseCertify.getResponse()); + String invariantUUIDcertify = certifyResource.getInvariantUUID(); + version = certifyResource.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcertify); + assertEquals(version, "1.0"); + + } + + // US672129 BENNY + + private void getResourceValidateInvariantUuid(String resourceUniqueId, String invariantUUIDcreation) + throws Exception { + RestResponse getResource = ResourceRestUtils.getResource(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + resourceUniqueId); + BaseRestUtils.checkSuccess(getResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + assertEquals(invariantUUIDcreation, resource.getInvariantUUID()); + } + + @Test + public void resourceInvariantUuid() throws Exception { + + User designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + User testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResourceByType("VF200", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, designerUser.getUserId(), ResourceTypeEnum.VF.toString()); + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("newtestservice1", + ServiceCategoriesEnum.MOBILITY, designerUser.getUserId()); + + // ResourceReqDetails resourceDetails = + // ElementFactory.getDefaultResource(); + resourceDetails.setInvariantUUID("kokomoko"); + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, designerUser); + assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED, + createResponse.getErrorCode().intValue()); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResponse.getResponse(), Resource.class); + String invariantUUIDcreation = resource.getInvariantUUID(); // generated + // when the + // component + // is + // created + // and never + // changed + // get resource and verify InvariantUuid is not changed + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + + // Update resource with new invariant UUID + resourceDetails.setInvariantUUID("1234567890"); + RestResponse updateResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, designerUser, + resourceDetails.getUniqueId()); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, + updateResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + + // checkIn resource + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + + // checkIn resource + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + // certification request + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + // start certification + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + // certify + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation); + // update resource + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + resourceDetails.setDescription("updatedDescription"); + resourceDetails.setVendorRelease("1.2.3.4"); + updateResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, designerUser, + resourceDetails.getUniqueId()); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, updateResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // certification request + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // checkout resource + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // certification request + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + // start certification + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // cancel certification + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, + LifeCycleStatesEnum.CANCELCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // start certification + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // failure + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, + LifeCycleStatesEnum.FAILCERTIFICATION); + assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // upload artifact + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact(); + ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, designerUser, + resourceDetails.getUniqueId()); + assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + // checkIn resource + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + // create instance + RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, designerUser); + ResourceRestUtils.checkCreateResponse(createServiceResponse); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, designerUser, serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED, + createResourceInstanceResponse.getErrorCode().intValue()); + getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java new file mode 100644 index 0000000000..25c3242d2c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java @@ -0,0 +1,582 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.Resource; +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.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class GetAllResourceVersions extends ComponentBaseTest { + + private static Logger logger = LoggerFactory.getLogger(GetAllResourceVersions.class.getName()); + protected User designerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + protected User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + protected ResourceReqDetails resourceDetails; + + public static TestName name = new TestName(); + + public GetAllResourceVersions() { + super(name, GetAllResourceVersions.class.getName()); + + } + + //// NEW + + protected void deleteAllVersionOfResource() throws Exception { + RestResponse response = null; + + String[] versions = { "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0", + "2.1", "2.2", "2.3", "2.4", "2.5", "3.0", "4.0", "4.1" }; + + for (String version : versions) { + + response = ResourceRestUtils.deleteResourceByNameAndVersion(designerDetails, + resourceDetails.getName().toUpperCase(), version); + AssertJUnit.assertTrue("delete request returned status:" + response.getErrorCode(), + response.getErrorCode() == 204 || response.getErrorCode() == 404); + + response = ResourceRestUtils.deleteResourceByNameAndVersion(designerDetails, resourceDetails.getName(), + version); + AssertJUnit.assertTrue("delete request returned status:" + response.getErrorCode(), + response.getErrorCode() == 204 || response.getErrorCode() == 404); + + } + } + + @BeforeMethod + public void init() throws Exception { + resourceDetails = defineResourse(); + deleteAllVersionOfResource(); + + } + + @AfterMethod + public void endOfTests() throws Exception { + deleteAllVersionOfResource(); + } + + protected ResourceReqDetails defineResourse() { + String resourceName = "cisco4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + // String category = ServiceCategoriesEnum.MOBILITY.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, + derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(), + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory()); + + return resourceDetails; + } + + @Test + public void getResourceAllVersions_version15() throws Exception { + // create resource + Map origVersionsMap = new HashMap(); + RestResponse restResponse = createResource(designerDetails, resourceDetails); + AssertJUnit.assertTrue("create request returned status:" + restResponse.getErrorCode(), + restResponse.getErrorCode() == 201); + String resourceName = resourceDetails.getName(); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // change resource version to 0.5 + RestResponse checkoutResource; + for (int x = 0; x < 4; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + // change resource version to 1.5 + for (int x = 0; x < 5; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + AssertJUnit.assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + protected RestResponse createResource(User sdncModifierDetails, ResourceReqDetails resourceDetails) + throws Exception { + // clean ES DB + DbUtils.cleanAllAudits(); + + // create resource + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + AssertJUnit.assertNotNull("check response object is not null after create resource", restResponse); + AssertJUnit.assertNotNull("check error code exists in response after create resource", + restResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create resource", 201, + restResponse.getErrorCode().intValue()); + + return restResponse; + } + + @Test + public void getResourceAllVersions_version05() throws Exception { + + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + Map origVersionsMap = new HashMap(); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + // change resource version to 0.5 + RestResponse checkoutResource; + + logger.debug("Changing resource life cycle "); + for (int x = 0; x < 4; x++) { + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + } + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_version01() throws Exception { + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + Map origVersionsMap = new HashMap(); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_version25() throws Exception { + + Map origVersionsMap = new HashMap(); + + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201); + String resourceName = resourceDetails.getName(); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // change resource version to 0.5 + RestResponse checkoutResource; + for (int x = 0; x < 4; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + // resource version 1.0 + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + // change resource version to 1.5 + for (int x = 0; x < 5; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + // resource version 2.0 + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + // change resource version to 2.5 + for (int x = 0; x < 5; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_ReadyForCertification_version05() throws Exception { + Map origVersionsMap = new HashMap(); + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + String resourceName = resourceDetails.getName(); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // change resource version to 0.5 + RestResponse checkoutResource; + for (int x = 0; x < 4; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + } + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_CertifactionInProgress_version05() throws Exception { + Map origVersionsMap = new HashMap(); + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + String resourceName = resourceDetails.getName(); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // change resource version to 0.5 + RestResponse checkoutResource; + for (int x = 0; x < 4; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + } + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_Certified_version10() throws Exception { + + Map origVersionsMap = new HashMap(); + + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201); + String resourceName = resourceDetails.getName(); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // change resource version to 0.5 + RestResponse checkoutResource; + for (int x = 0; x < 4; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + + } + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_Certified_version20() throws Exception { + + Map origVersionsMap = new HashMap(); + + // create resource + RestResponse restResponse = createResource(designerDetails, resourceDetails); + assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201); + String resourceName = resourceDetails.getName(); + // resourceUtils.addResourceMandatoryArtifacts(designerDetails, + // restResponse); + + // change resource version to 0.5 + RestResponse checkoutResource; + for (int x = 0; x < 4; x++) { + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + // get to version 1.0 + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + // change resource version to 1.5 + for (int x = 0; x < 4; x++) { + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, + checkoutResource.getErrorCode().intValue()); + } + + // get to version 1.0 + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId()); + + // validate get response + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, + resourceDetails.getUniqueId()); + Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void getResourceAllVersions_ResourceNotFound() throws Exception { + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, "123456789"); + assertEquals("Check response code after checkout resource", 404, resourceGetResponse.getErrorCode().intValue()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java new file mode 100644 index 0000000000..562150e5e2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java @@ -0,0 +1,328 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +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 org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.Rule; +import org.junit.rules.TestName; +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.enums.NormativeTypesEnum; +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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.imports.ImportGenericResourceCITest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class GetResourceNotAbstractApiTest extends ComponentBaseTest { + + private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName()); + protected static final int STATUS_CODE_GET_SUCCESS = 200; + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + @Rule + public static TestName name = new TestName(); + + public GetResourceNotAbstractApiTest() { + super(name, GetResourceNotAbstractApiTest.class.getName()); + } + + @Test + public void getNotAbstractResourceList() throws Exception { + + // remove all the not abstract resources + // Map originalState = + // ImportResourceCITest.removeAllNormativeTypeResources(); + + // import all the default not abstract resources + // ImportGenericResourceCITest.importAllNormativeTypesResources(UserRoleEnum.ADMIN); + + // Get not abstract resources + RestResponse getResourceNotAbstarctResponse = getNotAbstractResources(); + // Check that received 200. + assertEquals("Check response code after get abstract resources", STATUS_CODE_GET_SUCCESS, + getResourceNotAbstarctResponse.getErrorCode().intValue()); + // Verify that all the resources not abstract + assertTrue("One or more resources are abstract", isAllResourcesNotAbstract(getResourceNotAbstarctResponse)); + // Verify that all the resources are certified + assertTrue("Not all the resources are certified", isAllResourcesCertified(getResourceNotAbstarctResponse)); + + String objectStorageUid = "ObjectStorage"; + String computeUid = "Compute"; + String blockStorageUid = "BlockStorage"; + String loadBalancerUid = "LoadBalancer"; + // String portUid = "tosca.nodes.Network.Port"; + String portUid = "Port"; + String networkUid = "Network"; + String databaseUid = "Database"; + + // Compare expected list of abstract resources to actual list of + // abstract resources. + List expectedNotAbstractResourcesUniqueIdArray = new ArrayList(Arrays.asList(computeUid, + databaseUid, objectStorageUid, blockStorageUid, loadBalancerUid, portUid, networkUid)); + + List actualNotAbstarctResourcesUniqueIdArray = restResponseToListByHeader( + getResourceNotAbstarctResponse, "name"); + + // Collections.sort(actualNotAbstarctResourcesUniqueIdArray); + // Collections.sort(expectedNotAbstractResourcesUniqueIdArray); + + List toFind = new ArrayList<>(); + toFind.add(objectStorageUid); + toFind.add(computeUid); + toFind.add(blockStorageUid); + toFind.add(loadBalancerUid); + toFind.add(portUid); + + boolean removeAll = toFind.removeAll(actualNotAbstarctResourcesUniqueIdArray); + logger.debug("Cannot find resources {}", toFind.toString()); + + for (String expectedResource : expectedNotAbstractResourcesUniqueIdArray) { + if (false == actualNotAbstarctResourcesUniqueIdArray.contains(expectedResource)) { + // System.out.println("Not found abstract resource " + + // expectedResource); + } + } + + assertTrue( + "Expected abstract resources list: " + expectedNotAbstractResourcesUniqueIdArray.toString() + + " Actual: " + actualNotAbstarctResourcesUniqueIdArray.toString(), + actualNotAbstarctResourcesUniqueIdArray.containsAll(expectedNotAbstractResourcesUniqueIdArray)); + + /* + * java.lang.AssertionError: Expected abstract resources list: + * [tosca.nodes.Compute, tosca.nodes.ObjectStorage, + * tosca.nodes.BlockStorage, tosca.nodes.LoadBalancer, + * tosca.nodes.Network.Port] Actual: [resourceforproperty216, + * tosca.nodes.Compute, tosca.nodes.Database, resourceforproperty217, + * resourceforproperty217, tosca.nodes.ObjectStorage, + * tosca.nodes.BlockStorage, tosca.nodes.LoadBalancer, + * tosca.nodes.network.Port, tosca.nodes.network.Network, + * resourceforproperty217, resourceforproperty217, + * resourceforproperty217, resourceforproperty217, + * resourceforproperty217, resourceforproperty217, + * resourceforproperty217, resourceforproperty217, + * resourceforproperty217, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317, + * resourceforproperty317, resourceforproperty317] + */ + + // Create resource (not certified) + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + String resourceName = "TestResource"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String category = ServiceCategoriesEnum.MOBILITY.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.root"); + String vendorName = "Oracle"; + String vendorRelease = "1.0"; + String contactId = "Peter"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + // assertEquals("Check response code after create user", 201, + // restResponse.getErrorCode().intValue()); + + // Get not abstract resources + getResourceNotAbstarctResponse = getNotAbstractResources(); + // Check that received 200. + assertEquals("Check response code after get abstract resources", STATUS_CODE_GET_SUCCESS, + getResourceNotAbstarctResponse.getErrorCode().intValue()); + // Verify that all the resources not abstract + assertTrue("One or more resources are abstract", isAllResourcesNotAbstract(getResourceNotAbstarctResponse)); + // Verify that all the resources are certified + assertTrue("Not all the resources are certified", isAllResourcesCertified(getResourceNotAbstarctResponse)); + + // Compare expected list of abstract resources to actual list of + // abstract resources. + // expectedNotAbstractResourcesUniqueIdArray = new + // ArrayList(Arrays.asList("tosca.nodes.compute.1.0", + // "tosca.nodes.objectstorage.1.0", "tosca.nodes.blockstorage.1.0", + // "tosca.nodes.loadbalancer.1.0", "tosca.nodes.network.port.1.0")); + + // actualNotAbstarctResourcesUniqueIdArray = + // restResponseToListByHeader(getResourceNotAbstarctResponse, + // "uniqueId"); + + actualNotAbstarctResourcesUniqueIdArray = restResponseToListByHeader(getResourceNotAbstarctResponse, "name"); + + Collections.sort(actualNotAbstarctResourcesUniqueIdArray); + Collections.sort(expectedNotAbstractResourcesUniqueIdArray); + + for (String expectedResource : expectedNotAbstractResourcesUniqueIdArray) { + if (false == actualNotAbstarctResourcesUniqueIdArray.contains(expectedResource)) { + // System.out.println("Not found abstract resource " + + // expectedResource); + } + } + assertTrue( + "Expected abstract resources list: " + expectedNotAbstractResourcesUniqueIdArray.toString() + + " Actual: " + actualNotAbstarctResourcesUniqueIdArray.toString(), + actualNotAbstarctResourcesUniqueIdArray.containsAll(expectedNotAbstractResourcesUniqueIdArray)); + // assertTrue("Expected abstract resources list: "+ + // expectedNotAbstractResourcesUniqueIdArray.toString()+ " Actual: + // "+actualNotAbstarctResourcesUniqueIdArray.toString(),expectedNotAbstractResourcesUniqueIdArray.equals(actualNotAbstarctResourcesUniqueIdArray)); + + // restore the resources + // ImportResourceCITest.restoreToOriginalState(originalState); + + } + + protected RestResponse getNotAbstractResources() throws Exception { + HttpRequest httpRequest = new HttpRequest(); + + String url = String.format(Urls.GET_ALL_NOT_ABSTRACT_RESOURCES, config.getCatalogBeHost(), + config.getCatalogBePort()); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap); + + return getResourceNotAbstarctResponse; + } + + protected List restResponseToListByHeader(RestResponse restResponse, String restResponseHeader) { + JsonElement jelement = new JsonParser().parse(restResponse.getResponse()); + JsonArray jsonArray = jelement.getAsJsonArray(); + + List restResponseArray = new ArrayList<>(); + + for (int i = 0; i < jsonArray.size(); i++) { + JsonObject jobject = (JsonObject) jsonArray.get(i); + String header = jobject.get(restResponseHeader).toString(); + header = header.replace("\"", ""); + restResponseArray.add(header); + } + + return restResponseArray; + + } + + protected boolean isAllResourcesNotAbstract(RestResponse restResponse) { + JsonElement jelement = new JsonParser().parse(restResponse.getResponse()); + JsonArray jsonArray = jelement.getAsJsonArray(); + + for (int i = 0; i < jsonArray.size(); i++) { + JsonObject jobject = (JsonObject) jsonArray.get(i); + + if (jobject.get("abstract").getAsBoolean()) { + return false; + } + + } + return true; + + } + + protected boolean isEmptyList(RestResponse restResponse) { + JsonElement jelement = new JsonParser().parse(restResponse.getResponse()); + JsonArray jsonArray = jelement.getAsJsonArray(); + + if (jsonArray.size() == 0) { + return true; + } + return false; + } + + protected boolean isAllResourcesCertified(RestResponse restResponse) { + JsonElement jelement = new JsonParser().parse(restResponse.getResponse()); + JsonArray jsonArray = jelement.getAsJsonArray(); + + String certified = "CERTIFIED"; + String lifecycleState; + + for (int i = 0; i < jsonArray.size(); i++) { + JsonObject jobject = (JsonObject) jsonArray.get(i); + lifecycleState = jobject.get("lifecycleState").getAsString(); + if (!lifecycleState.equals(certified)) { + return false; + } + + } + return true; + } + + @Test(enabled = false) + public void getEmptyNonAbstractResourcesList() throws Exception { + // remove all the not abstract resources + Map originalState = ImportGenericResourceCITest.removeAllNormativeTypeResources(); + + // Get not abstract resources + RestResponse getResourceNotAbstarctResponse = getNotAbstractResources(); + // Check that received 200. + assertEquals("Check response code after get abstract resources", STATUS_CODE_GET_SUCCESS, + getResourceNotAbstarctResponse.getErrorCode().intValue()); + // Verify empty list + assertTrue("Received list is not empty", isEmptyList(getResourceNotAbstarctResponse)); + + // restore the resources + // ImportResourceCITest.restoreToOriginalState(originalState); + // import the resources + ImportGenericResourceCITest.importAllNormativeTypesResources(UserRoleEnum.ADMIN); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java new file mode 100644 index 0000000000..feb7b6f42e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java @@ -0,0 +1,372 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +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.HttpClients; +import org.apache.http.util.EntityUtils; +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.model.Resource; +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.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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +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.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +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.validation.ResourceValidationUtils; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class ResourceApiTest extends ComponentBaseTest { + + protected final String contentTypeHeaderData = "application/json"; + protected final String acceptHeaderDate = "application/json"; + + @Rule + public static TestName name = new TestName(); + + public ResourceApiTest() { + super(name, ResourceApiTest.class.getName()); + } + + // Keep + @Test + public void updateResourceMetadataSuccess() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncModifierDetails.setUserId("jh0003"); + RestResponse restResponse = createResourceForUpdate(sdncModifierDetails); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + // set resource details + ResourceReqDetails resourceDetails = new ResourceReqDetails(); + resourceDetails.setDescription("updatedDescription"); + ArrayList resourceTags = new ArrayList(); + // Duplicate tags are allowed and should be de-duplicated by the server + // side + resourceTags.add(resourceRespJavaObject.getName()); + resourceTags.add("tag1"); + resourceTags.add("tag1"); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + resourceDetails.setTags(resourceTags); + resourceDetails.addCategoryChain(ResourceCategoryEnum.NETWORK_L2_3_ROUTERS.getCategory(), + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS.getSubCategory()); + resourceDetails.setVendorName("OracleUp"); + resourceDetails.setVendorRelease("1.5Up"); + resourceDetails.setContactId("pe1116"); + + resourceDetails.setIcon(resourceRespJavaObject.getIcon()); + resourceDetails.setName(resourceRespJavaObject.getName()); + resourceDetails.setDerivedFrom(resourceRespJavaObject.getDerivedFrom()); + + // ResourceReqDetails resourceDetails = new + // ResourceReqDetails(resourceName, description, resourceTags, category, + // derivedFrom, vendorName, vendorRelease, contactId, null); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceRespJavaObject.getUniqueId()); + RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap); + + // resourceDetails.setResourceName(resourceRespJavaObject.getResourceName()); + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, + ResponseParser.convertResourceResponseToJavaObject(updateResourceResponse.getResponse())); + + // Delete resource + deleteResource(resourceRespJavaObject.getUniqueId(), sdncModifierDetails.getUserId()); + + } + + protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception { + RestResponse res = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId); + + // System.out.println("Delete resource was finished with response: " + + // res.getErrorCode()); + } + + protected RestResponse createResourceForUpdate(User sdncModifierDetails) throws Exception { + + ResourceReqDetails resourceDetails = getResourceObj(); + + // create resource + return ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + } + + public ResourceReqDetails getResourceObj() { + // set resource details + String resourceName = "ResourceForUpdate" + (int) (Math.random() * 100); + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + // String category = ResourceCategoriesEnum.MOBILITY.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "pe1116"; + String icon = "myICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, + derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(), + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory()); + return resourceDetails; + } + + // ------------------------------------------------------------------- + + protected ResourceReqDetails defineResourse_Benny(int n) { + String resourceName = "cisco" + String.valueOf(n); + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add("tag1"); + String category = ServiceCategoriesEnum.MOBILITY.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "borderElement"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + return resourceDetails; + } + + @Test + public void getAllAbstractResources() throws Exception { + RestResponse abstractResources = CatalogRestUtils.getAbstractResources(); + + int status = abstractResources.getErrorCode(); + assertTrue(status == 200); + String json = abstractResources.getResponse(); + JSONArray array = (JSONArray) JSONValue.parse(json); + for (Object o : array) { + JSONObject value = (JSONObject) o; + Boolean element = (Boolean) value.get("abstract"); + assertTrue(element); + } + + } + + @Test + public void getAllNotAbstractResources() throws Exception { + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + String url = String.format(Urls.GET_ALL_NOT_ABSTRACT_RESOURCES, config.getCatalogBeHost(), + config.getCatalogBePort()); + HttpGet httpget = new HttpGet(url); + + httpget.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + + httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + + httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + + // System.out.println("Executing request " + + // httpget.getRequestLine()); + CloseableHttpResponse response = httpclient.execute(httpget); + int status = response.getStatusLine().getStatusCode(); + assertTrue(status == 200); + try { + String json = EntityUtils.toString(response.getEntity()); + JSONArray array = (JSONArray) JSONValue.parse(json); + for (Object o : array) { + JSONObject value = (JSONObject) o; + Boolean element = (Boolean) value.get("abstract"); + assertTrue(!element); + } + + } finally { + response.close(); + } + } finally { + httpclient.close(); + } + } + + @Test + public void updateResourceMetadata_methodNotAllowed() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + // set resource details + String resourceName = "ResForUpdate"; + String description = "updatedDescription"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add("tag1"); + resourceTags.add("tag2"); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.root"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + String vendorName = "OracleUp"; + String vendorRelease = "1.5Up"; + String contactId = "pe1117"; + String icon = "myICON.jpgUp"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + "NotExistsId"); + + RestResponse updateResourceResponse = http.httpSendByMethod(url, "POST", userBodyJson, headersMap); + + assertNotNull("Check error code exists in response after wrong update resource", + updateResourceResponse.getErrorCode()); + assertEquals("Check error code after update resource", 405, updateResourceResponse.getErrorCode().intValue()); + } + + @Test + public void validateResourceNameTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncModifierDetails.setUserId("jh0003"); + + ResourceReqDetails resourceDetails = getResourceObj(); + + // create resource + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + Resource resourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + CloseableHttpClient httpclient = HttpClients.createDefault(); + try { + + // check invalid + String url = String.format(Urls.VALIDATE_RESOURCE_NAME, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetails.getName()); + + HttpGet httpget = new HttpGet(url); + + httpget.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + + httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + + httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + // System.out.println("Executing request " + + // httpget.getRequestLine()); + CloseableHttpResponse response = httpclient.execute(httpget); + int status = response.getStatusLine().getStatusCode(); + assertTrue(status == 200); + try { + String json = EntityUtils.toString(response.getEntity()); + JSONObject object = (JSONObject) JSONValue.parse(json); + Boolean element = (Boolean) object.get("isValid"); + assertTrue(!element); + + } finally { + response.close(); + } + // check valid + url = String.format(Urls.VALIDATE_RESOURCE_NAME, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceDetails.getName() + "temp"); + + httpget = new HttpGet(url); + + httpget.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + + httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + + httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + // System.out.println("Executing request " + + // httpget.getRequestLine()); + response = httpclient.execute(httpget); + status = response.getStatusLine().getStatusCode(); + assertTrue(status == 200); + try { + String json = EntityUtils.toString(response.getEntity()); + JSONObject object = (JSONObject) JSONValue.parse(json); + Boolean element = (Boolean) object.get("isValid"); + assertTrue(element); + + } finally { + response.close(); + } + } finally { + httpclient.close(); + } + + // Delete resource + ResourceRestUtils.deleteResource(resourceDetails, sdncModifierDetails, "0.1"); + + } + + // ------------------------------------------------------------------- + // //Benny Tal + // @Test + // public void createResource_Benny() throws Exception { + // for (int i = 0; i < 100; i++) { + // ResourceReqDetails resourceDetails = defineResourse_Benny(i); + // + // ResourceRestUtils.createResource(resourceDetails, + // UserUtils.getDesignerDetails()); + // // resourceUtils.deleteResource(resourceDetails, + // UserUtils.getDesignerDetails(), "0.1"); + // } + // } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java new file mode 100644 index 0000000000..f4a4fa108a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java @@ -0,0 +1,41 @@ +/*- + * ============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.ci.tests.execute.resource; + +import java.io.IOException; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.testng.ITestContext; +import org.testng.annotations.DataProvider; + +public class SampleDataProvider { + + @DataProvider + public static Object[][] getResourceByType(ITestContext context) throws IOException, Exception { + return new Object[][] { + { AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true) }, + { AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true) }, + { AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true) } }; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java new file mode 100644 index 0000000000..3002523ccb --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java @@ -0,0 +1,124 @@ +/*- + * ============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.ci.tests.execute.resource; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.annotations.Test; + +public class SimultaneousApiTest extends ComponentBaseTest { + + protected static ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + + @Rule + public static TestName name = new TestName(); + + static String httpCspUserId = "km2000"; + static String userFirstName = "Kot"; + static String userLastName = "Matroskin"; + static String email = "km2000@intl.sdc.com"; + static String role = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getRole(); + + public SimultaneousApiTest() { + super(name, SimultaneousApiTest.class.getName()); + + } + + public static class WorkerThread implements Runnable { + CountDownLatch countDownLatch; + int threadIndex; + + public WorkerThread(int threadIndex, CountDownLatch countDownLatch) { + this.threadIndex = threadIndex; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + System.out.println("**** Thread started " + threadIndex); + try { + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + String id = ResponseParser.getUniqueIdFromResponse(createResource); + // System.out.println("**** Thread " + threadIndex + " create + // resource status " + createResource.getErrorCode() + " id = " + // + id + " error " + createResource.getResponse()); + // assertEquals("**** create resource: " + + // createResource.getErrorCode() + " thread " + threadIndex, + // 201, status); + } catch (Exception e) { + // System.out.println("**** Thread " + threadIndex + " exception + // " + e); + } + countDownLatch.countDown(); + // System.out.println("**** Thread finished " + threadIndex); + + } + + // public void run_() { + // System.out.println("**** Thread started " + threadIndex); + // try { + // UserUtils userUtils = new UserUtils(); + // User userDetails = new User(userFirstName, userLastName, + // httpCspUserId, email, role , 0L); + // RestResponse response = + // userUtils.createUserTowardsCatalogBe(userDetails, + // userUtils.getUserDetailesAdmin()); + // System.out.println("**** Thread " + threadIndex + " create resource + // status " + response.getErrorCode() + " response " + + // response.getResponse()); + //// assertEquals("**** create resource: " + + // createResource.getErrorCode() + " thread " + threadIndex, 201, + // status); + // } catch (Exception e) { + // System.out.println("**** Thread " + threadIndex + " exception " + e); + // } + // countDownLatch.countDown(); + // System.out.println("**** Thread finished " + threadIndex); + // + // } + } + + @Test + public void create2Resources() throws InterruptedException { + int threadCount = 5; + CountDownLatch countDownLatch = new CountDownLatch(threadCount); + ExecutorService executor = Executors.newFixedThreadPool(threadCount); + for (int i = 0; i < threadCount; i++) { + Runnable worker = new WorkerThread(i + 1, countDownLatch); + executor.execute(worker); + } + countDownLatch.await(); + // System.out.println(" finished "); + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java new file mode 100644 index 0000000000..9d519c8b33 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java @@ -0,0 +1,2650 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.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.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedResourceAuditJavaObject; +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; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.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.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +public class UpdateResourceMetadataTest extends ComponentBaseTest { + private static Logger logger = LoggerFactory.getLogger(UpdateResourceMetadataTest.class.getName()); + protected List Empty_List = new ArrayList(); + protected String extendedChars; + + protected final String contentTypeHeaderData = "application/json"; + protected final String acceptHeaderDate = "application/json"; + protected final String CHARSET_ISO_8859 = "charset=ISO-8859-1"; + + public static TestName name = new TestName(); + protected User sdncModifierDetails; + protected ResourceReqDetails resourceDetails; + + public UpdateResourceMetadataTest() { + super(name, UpdateResourceMetadataTest.class.getName()); + + } + + public String extendedCharsStringBuilder() throws Exception { + char[] extendedCharsArray = new char[128]; + char ch = 128; + for (int i = 0; i < extendedCharsArray.length - 1; i++) { + extendedCharsArray[i] = ch; + ch++; + } + extendedChars = new String(extendedCharsArray); + return extendedChars; + + } + + @BeforeMethod + public void setup() throws Exception { + sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + resourceDetails = defineResourse(); + + } + + // Keep + @Test + public void UpdateDerivedFromSuccess() throws Exception { + + String oldDerivedFromName = NormativeTypesEnum.ROOT.getNormativeName(); + String newDerivedFromName = NormativeTypesEnum.SOFTWARE_COMPONENT.getNormativeName(); + + // Getting both derived from resources for validation + /* + * RestResponse resourceByNameAndVersion = + * resourceUtils.getResourceByNameAndVersion(sdncModifierDetails, + * oldDerivedFromName, "1.0"); + * assertEquals("Check response code after get database normative", 200, + * resourceByNameAndVersion.getErrorCode().intValue()); Resource + * databaseNormative = + * resourceUtils.parseResourceResp(resourceByNameAndVersion); + * + * resourceByNameAndVersion = + * resourceUtils.getResourceByNameAndVersion(sdncModifierDetails, + * newDerivedFromName, "1.0"); + * assertEquals("Check response code after get database normative", 200, + * resourceByNameAndVersion.getErrorCode().intValue()); Resource + * lbNormative = + * resourceUtils.parseResourceResp(resourceByNameAndVersion); + */ + + // Derived from set to Database + List derivedFrom = new ArrayList<>(); + derivedFrom.add(oldDerivedFromName); + resourceDetails.setDerivedFrom(derivedFrom); + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + AssertJUnit.assertEquals("Check response code after create resource", 201, + restResponse.getErrorCode().intValue()); + Resource currentResource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + + derivedFrom.clear(); + derivedFrom.add(newDerivedFromName); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResource.getUniqueId(), ""); + AssertJUnit.assertEquals("Check response code after create resource", 200, + updatedRestResponse.getErrorCode().intValue()); + + } + + protected ResourceReqDetails defineUpdateResourceWithNonUpdatableFields(Resource resourceBeforeUpdate) { + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceBeforeUpdate.getName()); + + updatedResourceDetails.setVersion("mumu"); + updatedResourceDetails.setIsAbstract(true); + updatedResourceDetails.setIsHighestVersion(true); + updatedResourceDetails.setCreatorUserId("df4444"); + updatedResourceDetails.setCreatorFullName("John Doe"); + updatedResourceDetails.setLastUpdaterUserId("gf5646"); + updatedResourceDetails.setLastUpdaterFullName("Viktor Tzoy"); + updatedResourceDetails.setCreationDate(new Long(4444)); + updatedResourceDetails.setLastUpdateDate(new Long("534535")); + updatedResourceDetails.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + updatedResourceDetails.setCost("6.1"); + updatedResourceDetails.setLicenseType("Installation"); + updatedResourceDetails.setUUID("dfsfsdf"); + return updatedResourceDetails; + } + + public void UpdateResourceNotFoundTest() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + String resourceName = "cisco4"; + // update resource + String description = "updatedDescription"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.MOBILITY.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "newOracle"; + String vendorRelease = "2.5"; + String contactId = "jh0003"; + String icon = "myICON"; + + ResourceReqDetails updatedResourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, + category, derivedFrom, vendorName, vendorRelease, contactId, icon); + updatedResourceDetails.setUniqueId("dummyId"); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, "0.1"); + + // validate response + AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse); + AssertJUnit.assertNotNull("check error code exists in response after update resource", + updatedRestResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after update resource", 404, + updatedRestResponse.getErrorCode().intValue()); + // String resourceId = + // UniqueIdBuilder.buildResourceUniqueId(resourceName, "0.1"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), Arrays.asList("dummyId"), + updatedRestResponse.getResponse()); + + resourceName = ""; + // resourceId = UniqueIdBuilder.buildResourceUniqueId(resourceName, + // "0.1"); + updatedResourceDetails = defineUpdatedResourse(resourceName); + updatedResourceDetails.setUniqueId("dummyId"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + "0.1"); + AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse); + AssertJUnit.assertNotNull("check error code exists in response after update resource", + updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), Arrays.asList("dummyId"), + updatedRestResponse.getResponse()); + + } + + public char[] getInValidChars() throws Exception { + + char[] extendedCharsArray = new char[59]; + char ch = 1; + for (int i = 0; i < 44; i++) { + extendedCharsArray[i] = ch; + ch++; + } + ch = 58; + for (int i = 44; i < 51; i++) { + extendedCharsArray[i] = ch; + ch++; + } + ch = 91; + for (int i = 51; i < 55; i++) { + extendedCharsArray[i] = ch; + ch++; + } + ch = 123; + for (int i = 55; i < 59; i++) { + extendedCharsArray[i] = ch; + ch++; + } + return extendedCharsArray; + } + + public char[] getTagInValidFormatChars() throws Exception { + // Tag format is the same as defined for "Resource Name" : + // Allowed characters: Alphanumeric (a-zA-Z0-9), space (' '), underscore + // ('_'), dash ('-'), dot ('.') + char[] notValidCharsArray = new char[30]; + char ch = 33; + for (int i = 0; i < 12; i++) { + notValidCharsArray[i] = ch; + ch++; + } + notValidCharsArray[13] = 47; + ch = 58; + for (int i = 14; i < 21; i++) { + notValidCharsArray[i] = ch; + ch++; + } + ch = 91; + for (int i = 21; i < 24; i++) { + notValidCharsArray[i] = ch; + ch++; + } + notValidCharsArray[24] = 96; + ch = 123; + for (int i = 25; i < 30; i++) { + notValidCharsArray[i] = ch; + ch++; + } + return notValidCharsArray; + } + + public void Validation_UpdateWithIncompleteJsonBodyTest() throws Exception { + // init ADMIN user + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // define and create resource + ResourceReqDetails resourceDetails = defineResourse(); + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "0.1"); + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.0"); + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.1"); + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceId = resourceDetails.getUniqueId(); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + + // build Json Object + JSONObject jsonObject = JsonObjectBuilder(resourceDetails); + + List resource = new ArrayList<>(); + resource.add("Resource"); + + // remove Description + UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "description", + ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), resource); + // remove Tags + UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "tags", + ActionStatus.COMPONENT_MISSING_TAGS.name(), Empty_List); + // remove Category + UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "category", + ActionStatus.COMPONENT_MISSING_CATEGORY.name(), resource); + // remove VendorName + UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "vendorName", + ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List); + // remove VendorRelease + UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "vendorRelease", + ActionStatus.MISSING_VENDOR_RELEASE.name(), Empty_List); + // remove AT&T Contact + UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "contactId", + ActionStatus.COMPONENT_MISSING_CONTACT.name(), resource); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, "0.1"); + // validate response + AssertJUnit.assertNotNull("check response object is not null after get resource", getRestResponse); + AssertJUnit.assertNotNull("check error code exists in response after get resource", + getRestResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after update resource", 200, + getRestResponse.getErrorCode().intValue()); + + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "0.1"); + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.0"); + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.1"); + } + + // End of validation tests + // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + protected ResourceReqDetails defineUpdatedResourse(String resourceName) { + String description = "updatedDescription"; + ArrayList resourceTags = new ArrayList(); + // Duplicate tags are allowed and should be de-duplicated by server side + resourceTags.add(resourceName); + resourceTags.add("tag1"); + resourceTags.add("tag1"); + resourceTags.add("tag2"); + resourceTags.add("tag2"); + String category = ServiceCategoriesEnum.VOIP.getValue(); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName()); + String vendorName = "updatedOracle"; + String vendorRelease = "3.5"; + String contactId = "jh0001"; + String icon = "myUpdatedICON"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, + derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(), + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory()); + + return resourceDetails; + } + + protected ResourceReqDetails defineResourse() { + String resourceName = "cisco4"; + String description = "description"; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());// "tosca.nodes.Root"); + String vendorName = "Oracle"; + String vendorRelease = "1.5"; + String contactId = "jh0003"; + String icon = "objectStorage"; + + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, + derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(), + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory()); + + return resourceDetails; + } + + protected RestResponse createResource(User sdncModifierDetails, ResourceReqDetails resourceDetails) + throws Exception { + // clean ES DB + DbUtils.cleanAllAudits(); + + // create resource + RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + + // validate response + AssertJUnit.assertNotNull("check response object is not null after create resource", restResponse); + AssertJUnit.assertNotNull("check error code exists in response after create resource", + restResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create resource", 201, + restResponse.getErrorCode().intValue()); + + return restResponse; + } + + protected RestResponse TryUpdateByAnotherVerb(ResourceReqDetails updatedResourceDetails, User sdncModifierDetails, + String uri) throws Exception { + // delete resource + Config config; + RestResponse ResourceResponse; + try { + config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), + config.getCatalogBePort(), updatedResourceDetails.getName() + ".0.1"); + + if (uri == "GET") { + ResourceResponse = http.httpSendGet(url, headersMap); + } else if (uri == "POST") { + Gson gson = new Gson(); + String userBodyJson = gson.toJson(updatedResourceDetails); + ResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + } else if (uri == "DELETE") { + ResourceResponse = http.httpSendDelete(url, headersMap); + } else + return null; + + return ResourceResponse; + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + + } + + protected JSONObject JsonObjectBuilder(ResourceReqDetails resourceDetails) throws JSONException { + // json object: resourceName and icon are must + JSONObject jObject = new JSONObject(); + + List tagsList = Arrays.asList(resourceDetails.getName()); + List derivedFromList = Arrays.asList("[tosca.nodes.Root]"); + + jObject.put("name", resourceDetails.getName()); + jObject.put("description", "updatedDescription"); + jObject.put("tags", tagsList); + jObject.put("category", ServiceCategoriesEnum.VOIP.getValue()); + jObject.put("derivedFrom", derivedFromList); + jObject.put("vendorName", "newOracle"); + jObject.put("vendorRelease", "1.5"); + jObject.put("contactId", "jh0003"); + jObject.put("icon", resourceDetails.getIcon()); + + return jObject; + } + + protected JSONObject RemoveFromJsonObject(JSONObject jObject, String removedPropery) { + jObject.remove(removedPropery); + + return jObject; + } + + // purpose: function for controlling json body fields and validating + // response + protected void UpdateAndValidateWithIncompletedJsonBody(User sdncModifierDetails, JSONObject jsonObject, + String resourceId, String removedField, String errorMessage, List variables) throws Exception { + + JSONObject jObject = new JSONObject(jsonObject, JSONObject.getNames(jsonObject)); + // remove description from jsonObject + jObject = RemoveFromJsonObject(jObject, removedField); + // update with incomplete body. + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(jObject.toString(), + sdncModifierDetails, resourceId); + // validate response + AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse); + AssertJUnit.assertNotNull("check error code exists in response after update resource", + updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(errorMessage, variables, updatedRestResponse.getResponse()); + + } + + // purpose: function for validating error response + protected void UpdateAndValidate(User sdncModifierDetails, ResourceReqDetails resourceDetails, + String recievedMessage, List variables) throws Exception { + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, "0.1"); + // validate response + AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse); + AssertJUnit.assertNotNull("check error code exists in response after update resource", + updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(recievedMessage, variables, updatedRestResponse.getResponse()); + + } + + protected void parseResponseAndValidateNonUpdatable(ResourceReqDetails resourceDetails, RestResponse restResponse) + throws Exception { + // parse response to javaObject + Resource updatedResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + AssertJUnit.assertTrue( + !resourceDetails.getIsHighestVersion().equals(updatedResourceRespJavaObject.isHighestVersion())); + AssertJUnit.assertTrue(!resourceDetails.getVersion().equals(updatedResourceRespJavaObject.getName())); + AssertJUnit.assertTrue(!resourceDetails.getIsAbstract().equals(updatedResourceRespJavaObject.isAbstract())); + AssertJUnit.assertTrue( + !resourceDetails.getCreatorUserId().equals(updatedResourceRespJavaObject.getCreatorUserId())); + AssertJUnit.assertTrue( + !resourceDetails.getCreatorFullName().equals(updatedResourceRespJavaObject.getCreatorFullName())); + AssertJUnit.assertTrue( + !resourceDetails.getLastUpdateDate().equals(updatedResourceRespJavaObject.getLastUpdateDate())); + AssertJUnit + .assertTrue(!resourceDetails.getCreationDate().equals(updatedResourceRespJavaObject.getCreationDate())); + AssertJUnit.assertTrue( + !resourceDetails.getLastUpdaterUserId().equals(updatedResourceRespJavaObject.getLastUpdaterUserId())); + AssertJUnit.assertTrue(!resourceDetails.getLastUpdaterFullName() + .equals(updatedResourceRespJavaObject.getLastUpdaterFullName())); + AssertJUnit.assertTrue( + !resourceDetails.getLifecycleState().equals(updatedResourceRespJavaObject.getLifecycleState())); + AssertJUnit.assertTrue(!resourceDetails.getCost().equals(updatedResourceRespJavaObject.getCost())); + AssertJUnit + .assertTrue(!resourceDetails.getLicenseType().equals(updatedResourceRespJavaObject.getLicenseType())); + AssertJUnit.assertTrue(!resourceDetails.getUUID().equals(updatedResourceRespJavaObject.getUUID())); + + } + + protected void parseResponseAndValidate(ResourceReqDetails ResourceDetails, RestResponse restResponse) + throws Exception { + // parse response to javaObject + Resource updatedResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + // validate request vs response + ResourceValidationUtils.validateResourceReqVsResp(ResourceDetails, updatedResourceRespJavaObject); + } + + public ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails, + String resourceVersion) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + + expectedResourceAuditJavaObject.setAction("Checkout"); + expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId()); + expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName()); + expectedResourceAuditJavaObject.setStatus("200.0"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName().toLowerCase()); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(resourceVersion) - 0.1f)); + expectedResourceAuditJavaObject.setCurrVersion(resourceVersion); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + + return expectedResourceAuditJavaObject; + + } + + public enum FieldToValidate { + contactId, Tags, VendorName, VendorRelease, Description + } + + @Test + public void UpdateBy_postTest() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // update resource - without changing resourceName + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + + RestResponse updatedRestResponse = TryUpdateByAnotherVerb(updatedResourceDetails, sdncModifierDetails, "POST"); + + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), Empty_List, + updatedRestResponse.getResponse()); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(resourceDetails, getRestResponse); + + } + + @Test + public void UpdateBy_getTest() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // update resource - without changing resourceName + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + RestResponse updatedRestResponse = TryUpdateByAnotherVerb(updatedResourceDetails, sdncModifierDetails, "GET"); + + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), Empty_List, + updatedRestResponse.getResponse()); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(resourceDetails, getRestResponse); + + } + + @Test + public void UpdateBy_deleteTest() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // update resource - without changing resourceName + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + RestResponse updatedRestResponse = TryUpdateByAnotherVerb(updatedResourceDetails, sdncModifierDetails, + "DELETE"); + + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), Empty_List, + updatedRestResponse.getResponse()); + + RestResponse getRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(resourceDetails, getRestResponse); + + } + + // TODO DE + // @Ignore("") + @Test + public void UpdateWithInvaldJsonBodyTest() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + String resourceId = resourceDetails.getUniqueId(); + + // update Descirption value + String description = "updatedDescription"; + + // send update with incompleted json, only description string + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(description, sdncModifierDetails, + resourceId); + + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("check error code after update resource", 400, updatedRestResponse.getErrorCode().intValue()); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(resourceDetails, getRestResponse); + + } + + // @Test + // public void UpdateResourceModifierNotOwnerStateTest() throws Exception { + // + // + // RestResponse restResponse = createResource(sdncModifierDetails, + // resourceDetails); + // String resourceName = resourceDetails.getName(); + // + // // new user parameters + // String userFirstName = "Kot"; + // String userLastName = "Matroskin"; + // String role = "ADMIN"; + // User sdncUserDetails = new User(userFirstName, userLastName, + // httpCspUserId, email, role,null); + // RestResponse deleteUserResponse = userUtils.deleteUser(sdncUserDetails, + // ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)); + // + // RestResponse createUserResponse = UserUtils.createUser(sdncUserDetails, + // ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)); + // + // User updatedSdncModifierDetails = new User(userFirstName, userLastName, + // httpCspUserId, email,role,null); + // ResourceReqDetails updatedResourceDetails = + // defineUpdatedResourse(resourceName); + // RestResponse updatedRestResponse = + // ResourceRestUtils.updateResource(updatedResourceDetails, + // updatedSdncModifierDetails, resourceDetails.getUniqueId(), ""); + // + // // validate response + // assertNotNull("check response object is not null after update resource", + // updatedRestResponse); + // assertNotNull("check error code exists in response after update + // resource", updatedRestResponse.getErrorCode()); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), + // Empty_List, updatedRestResponse.getResponse()); + // + // RestResponse getRestResponse = + // ResourceRestUtils.getResource(sdncModifierDetails, + // resourceDetails.getUniqueId()); + // assertNotNull("check response object is not null after update resource", + // getRestResponse); + // parseResponseAndValidate(resourceDetails, getRestResponse); + // + // + // } + + @Test + public void UpdateResourceNameSensitiveTest() throws Exception { + User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + String resourceName = "Ab"; + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + // Delete resources + RestResponse response = null; + response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, + updatedResourceDetails.getName(), "0.1"); + BaseRestUtils.checkDeleteResponse(response); + response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, + updatedResourceDetails.getName(), "0.2"); + BaseRestUtils.checkDeleteResponse(response); + + RestResponse restResponse = createResource(sdncModifierDetails, updatedResourceDetails); + assertEquals("create resource failed", 201, restResponse.getErrorCode().intValue()); + + // check-in Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(updatedResourceDetails, + sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // String resourceCertifyVersion = "0.1"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(updatedResourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + updatedResourceDetails.setName("ABC_-bt.aT"); + ArrayList resourceTag = new ArrayList(); + resourceTag.add(0, "ABC_-bt.aT"); + updatedResourceDetails.setTags(resourceTag); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, updatedResourceDetails.getUniqueId(), ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(updatedResourceDetails, updatedRestResponse); + + // Delete resources + response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, + updatedResourceDetails.getName(), "0.1"); + BaseRestUtils.checkDeleteResponse(response); + response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, + updatedResourceDetails.getName(), "0.2"); + BaseRestUtils.checkDeleteResponse(response); + + } + + @Test + public void UpdateIcon_InegativeFlow() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + List resourceList = new ArrayList(); + resourceList.add(0, "Resource"); + // check InValid Characters + char[] notValidCharsArray = new char[59]; + notValidCharsArray = getInValidChars(); + // update metadata details + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + RestResponse updatedRestResponse; + + for (int i = 0; i < notValidCharsArray.length; i++) { + // change icon of metadata + updatedResourceDetails.setIcon("MyIcon" + notValidCharsArray[i]); + // PUT request + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", + updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), resourceList, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource icon", 400, + updatedRestResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating resource icon", "Bad Request", + updatedRestResponse.getResponseMessage().toString()); + + } + + // empty icon + String updateIcon = ""; + updatedResourceDetails.setIcon(updateIcon); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), resourceList, + updatedRestResponse.getResponse()); + + // Icon length more then 25 characters + resourceList.add(1, "25"); + updatedResourceDetails.setIcon("1234567890_-qwertyuiopASDNNN"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT.name(), resourceList, + updatedRestResponse.getResponse()); + assertEquals("Check response code after create resource", 400, updatedRestResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating resource icon", "Bad Request", + updatedRestResponse.getResponseMessage().toString()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResource_NoTagsEqualToResourceName() throws Exception { + + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + ResourceReqDetails updatedResourceDetails = defineResourse(); + updatedResourceDetails.setName("updatedResourceName"); + List tags = updatedResourceDetails.getTags(); + + for (Iterator iter = tags.listIterator(); iter.hasNext();) { + String a = iter.next(); + if (a.equals("updatedResourceName")) { + iter.remove(); + } + } + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + List resourceList = new ArrayList(); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME.name(), + resourceList, updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource icon", 400, + updatedRestResponse.getErrorCode().intValue()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResourceName_negativeFlow() throws Exception { + // The validation are done in Tag's validation + User sdncAdminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + RestResponse updatedRestResponse; + RestResponse restResponse = createResource(sdncAdminModifierDetails, resourceDetails); + assertEquals("create resource failed", 201, restResponse.getErrorCode().intValue()); + String uniqueId = resourceDetails.getUniqueId(); + String resourceName = resourceDetails.getName(); + // check InValid Characters + char[] notValidCharsArray = new char[59]; + notValidCharsArray = getInValidChars(); + ArrayList resource_Name = new ArrayList(); + List resourceList = new ArrayList(); + + ArrayList resourceTags = new ArrayList(); + resourceList.add(0, "Resource"); + + // update metadata details + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + for (int i = 0; i < notValidCharsArray.length; i++, resource_Name.clear()) { + if (i != 1 && i != 46 + && /* + * i != 8 && i != 9 && i != 10 && i != 11 && i != 12 && + */ i != 31) // space ("") and dot(.) + { + // change resourceName parameter + updatedResourceDetails.setName("UpdatedResourceName" + notValidCharsArray[i]); + resource_Name.add("UpdatedResourceName" + notValidCharsArray[i]); + updatedResourceDetails.setTags(resource_Name); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncAdminModifierDetails, uniqueId, ""); + // validate response + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAG.name(), + // Empty_List, updatedRestResponse.getResponse()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), resourceList, + updatedRestResponse.getResponse()); + + } + } + + // resourceName length more then 50 characters + // Duplicate tags are allowed and should be de-duplicated by server side + resource_Name.add(resourceName); + resource_Name.add("tag1"); + resource_Name.add("tag1"); + resource_Name.add("tag2"); + resource_Name.add("tag2"); + + resourceList.add(1, "1024"); + // updatedResourceDetails.setName("123456789012345678901234567890123456789012345678901"); + updatedResourceDetails.setName(new String(new char[1025]).replace("\0", "a")); + // resource_Name.add("123456789012345678901234567890123456789012345678901"); + updatedResourceDetails.setTags(resource_Name); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncAdminModifierDetails, + uniqueId, ""); + // validate response + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), resourceList, + updatedRestResponse.getResponse()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncAdminModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + // delete resource + RestResponse response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncAdminModifierDetails, + updatedResourceDetails.getName(), "0.1"); + BaseRestUtils.checkDeleteResponse(response); + } + + @Test + public void UpdateResourceInformation_NotCheckedOut() throws Exception { + + String resourceBaseVersion = "0.1"; + List resourceList = new ArrayList(); + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // CheckIn Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); // NOT_CERTIFIED_CHECKIN + assertNotNull("check response object is not null after checkout resource", checkoutResource); + assertNotNull("check error code exists in response after checkIn resource", checkoutResource.getErrorCode()); + assertEquals("Check response code after checkin resource", 200, checkoutResource.getErrorCode().intValue()); + + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), resourceList, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource icon", 409, + updatedRestResponse.getErrorCode().intValue()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResourceInformation_resourceVersion_11() throws Exception { + + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + List resourceList = new ArrayList(); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), resourceList, + updatedRestResponse.getResponse()); + // assertEquals("Check response code after updating resource icon", 409, + // updatedRestResponse.getErrorCode().intValue()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResourceInformation_resourceVersion_02() throws Exception { + + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // String resourceCertifyVersion = "0.1"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after updating resource icon", 200, + updatedRestResponse.getErrorCode().intValue()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(updatedResourceDetails, getResourceRespJavaObject); + + // delete resource + RestResponse response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, + updatedResourceDetails.getName(), "0.1"); + BaseRestUtils.checkDeleteResponse(response); + response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, + updatedResourceDetails.getName(), "0.2"); + BaseRestUtils.checkDeleteResponse(response); + + } + + @Test + public void UpdateResourceIcon_resourceVersion_11() throws Exception { + // Can be changed only if major version is "0". + + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // ResourceReqDetails updatedResourceDetails = + // defineUpdatedResourse(resourceName); + ResourceReqDetails updatedResourceDetails = defineResourse(); + // updatedResourceDetails.setVendorName("updatedVandorName"); + updatedResourceDetails.setIcon("updatedIcon"); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + List resourceList = new ArrayList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED.name(), resourceList, + updatedRestResponse.getResponse()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResourceVandorName_resourceVersion_11() throws Exception { + // Can be changed only if the major resource version is "0". + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // ResourceReqDetails updatedResourceDetails = + // defineUpdatedResourse(resourceName); + ResourceReqDetails updatedResourceDetails = defineResourse(); + + updatedResourceDetails.setVendorName("updatedVandorName"); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + List resourceList = new ArrayList(); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED.name(), + resourceList, updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource icon", 400, + updatedRestResponse.getErrorCode().intValue()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResourceName_resourceVersion_11() throws Exception { + // Can be changed only if the major resource version is "0". + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("create resource failed", 201, restResponse.getErrorCode().intValue()); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + /* + * //ResourceReqDetails updatedResourceDetails = + * defineUpdatedResourse(resourceName); ResourceReqDetails + * updatedResourceDetails = defineResourse(); + * + * updatedResourceDetails.setResourceName("updatedResourceName"); + * updatedResourceDetails.setIcon("updatedResourceName"); + */ + resourceDetails.setName("updatedResourceName"); + List tagList = new ArrayList(); + tagList.add(0, "updatedResourceName"); + resourceDetails.setTags(tagList); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + List resourceList = new ArrayList(); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED.name(), resourceList, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResourceTag_resourceVersion_11() throws Exception { + // Tag Can be updated when major version is "0". + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // ResourceReqDetails updatedResourceDetails = + // defineUpdatedResourse(resourceName); + ResourceReqDetails updatedResourceDetails = defineResourse(); + // updatedResourceDetails.setVendorName("updatedVandorName"); + + ArrayList resourceTags = new ArrayList(); + resourceTags.add("NewTag"); + resourceTags.add(resourceDetails.getName()); + + updatedResourceDetails.setTags(resourceTags); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(updatedResourceDetails, getRestResponse); + + } + + @Test + public void UpdateAllowedParames_resourceVersion_11() throws Exception { + + // Tag, contactId, vendorRelease,tags And description - Can be also + // updated when major version is NOT "0". + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // ResourceReqDetails updatedResourceDetails = + // defineUpdatedResourse(resourceName); + ResourceReqDetails updatedResourceDetails = defineResourse(); + // updatedResourceDetails.setVendorName("updatedVandorName"); + + // updated allowed parameters when major resource version is NOT "0" + ArrayList resourceTags = new ArrayList(); + resourceTags.add("NewTag"); + resourceTags.add(resourceDetails.getName()); + updatedResourceDetails.setTags(resourceTags); + updatedResourceDetails.setDescription("UpdatedDescription"); + updatedResourceDetails.setVendorRelease("5.1"); + updatedResourceDetails.setContactId("bt750h"); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(updatedResourceDetails, getRestResponse); + + } + + @Test + public void UpdateResourceDerivedFrom_resourceVersion_11() throws Exception { + // DerivedFrom parameter - Can be updated when major version is "0". + User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + String resourceBaseVersion = "0.1"; + + // create resource + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String resourceName = resourceDetails.getName(); + + // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails, + // restResponse); + + // Certify Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, + resourceBaseVersion, LifeCycleStatesEnum.CERTIFY); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + String resourceCertifyVersion = "1.0"; + logger.debug("Changing resource life cycle "); + checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue()); + + // ResourceReqDetails updatedResourceDetails = + // defineUpdatedResourse(resourceName); + ResourceReqDetails updatedResourceDetails = defineResourse(); + ArrayList drivenFrom = new ArrayList(); + drivenFrom.add(0, "tosca.nodes.Container.Application"); + updatedResourceDetails.setDerivedFrom(drivenFrom); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + // validate response + List resourceList = new ArrayList(); + ResourceRestUtils.checkSuccess(updatedRestResponse); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + } + + @Test + public void UpdateResource_vendorNameValidation() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + String updatedVendorName = ""; + String uniqueId = resourceDetails.getUniqueId(); + resourceDetails.setVendorName(updatedVendorName); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, uniqueId, ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + // update resource vendorName metadata: 1 characters + updatedVendorName = " "; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + // update resource vendorName metadata: 25 characters + updatedVendorName = "Verification and validati"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // update resource vendorName metadata: 26 characters + updatedVendorName = "Verification and validatii"; + // set vendorName + List myList = new ArrayList(); + myList.add(0, "25"); + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT.name(), myList, + updatedRestResponse.getResponse()); + + // update resource VendorRelease metadata: forbidden characters + updatedVendorName = "A1<"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1>"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1:"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1\""; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1/"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1\\"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1|"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1?"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorName = "A1*"; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + // update resource vendorName metadata: null + updatedVendorName = null; + // set vendorName + resourceDetails.setVendorName(updatedVendorName); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResource_vendorReleaseValidation() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + RestResponse updatedRestResponse; + String uniqueId = resourceDetails.getUniqueId(); + String updatedVendorRelease; + // set VendorRelease + + // update resource VendorRelease metadata: 1 characters + updatedVendorRelease = "1"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // update resource VendorRelease metadata: 25 characters + updatedVendorRelease = "(!#1.00000000000000000000"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // update resource VendorRelease metadata: 26 characters + updatedVendorRelease = "(!#1.000000000000000000005";// set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT.name(), + Arrays.asList("" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH), updatedRestResponse.getResponse()); + + // UpdateAndValidate(sdncModifierDetails, resourceDetails, + // ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT.name(), + // Arrays.asList(""+ValidationUtils.VENDOR_RELEASE_MAX_LENGTH)); + + // update resource VendorRelease metadata: forbidden characters + updatedVendorRelease = "A1<"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1>"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1:"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1\""; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1/"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1\\"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1|"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1?"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + updatedVendorRelease = "A1*"; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + // update resource VendorRelease metadata: null + updatedVendorRelease = null; + // set VendorRelease + resourceDetails.setVendorRelease(updatedVendorRelease); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_RELEASE.name(), Empty_List, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResource_contactIdValidation() throws Exception { // [a-zA-Z]{2}[0-9]{3}[a-zA-Z0-9]{1} + // (6 + // characters + // now, + // may + // be + // expanded + // up + // to + // 8 + // characters + // in + // the + // future). + // Convert + // Upper + // case + // character + // to + // lower + // case + RestResponse updatedRestResponse; + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + String uniqueId = resourceDetails.getUniqueId(); + + List myList = new ArrayList(); + myList.add(0, "Resource"); + String updatedcontactId = ""; + resourceDetails.setContactId(updatedcontactId); + + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "ab12345"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = " "; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "ab 50h"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "ab123c"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + updatedcontactId = "cd789E"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + + resourceDetails.setContactId(updatedcontactId.toLowerCase()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + updatedcontactId = "ef4567"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + updatedcontactId = "AA012A"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + + resourceDetails.setContactId(updatedcontactId.toLowerCase()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + updatedcontactId = "CD012c"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + + resourceDetails.setContactId(updatedcontactId.toLowerCase()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + updatedcontactId = "EF0123"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + + resourceDetails.setContactId(updatedcontactId.toLowerCase()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + ////////////////////////////// **************////////////////////////////// + List resource = Arrays.asList("Resource"); + updatedcontactId = "01345a"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "0y000B"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "Y1000b"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "abxyzC"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "cdXYZc"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "efXY1D"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "EFabcD"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "EFABCD"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "EFABC1"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "efui1D"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "efui1!"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "ef555!"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = ",f555"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + updatedcontactId = "EF55.5"; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + // update resource contactId metadata: extended character set (128–255) + resourceDetails.setContactId(extendedCharsStringBuilder()); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + // update resource contactId metadata: null + updatedcontactId = null; + resourceDetails.setContactId(updatedcontactId); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), myList, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResource_TagsFieldValidation() throws Exception { + RestResponse updatedRestResponse; + // define and create resource + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + String uniqueId = resourceDetails.getUniqueId(); + + String updatedTagField = ""; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(updatedTagField); + // set description + resourceDetails.setTags(resourceTags); + List variables = Arrays.asList("Resource", "tag"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, + updatedRestResponse.getResponse()); + + // update resource tags metadata: empty + resourceTags = new ArrayList(); + // set Tags + resourceDetails.setTags(resourceTags); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_TAGS.name(), Empty_List, + updatedRestResponse.getResponse()); + + // update resource description metadata: 1 characters + updatedTagField = "A"; + resourceTags = new ArrayList(); + resourceTags.add(updatedTagField); + resourceTags.add(resourceDetails.getName()); + // set description + resourceDetails.setTags(resourceTags); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // OK - tag up to 50 chars + updatedTagField = "The Indian-crested.porcupine_The Indian cresteddds"; + resourceTags.add(updatedTagField); + resourceDetails.setTags(resourceTags); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // OK - sum is 1024, 50x20+48+20(commas)+6(cisco4 - resource name) + String updatedTagField1 = "The Indian-crested.porcupine_The Indian crestedd01"; + String updatedTagField2 = "The Indian-crested.porcupine_The Indian crestedd02"; + String updatedTagField3 = "The Indian-crested.porcupine_The Indian crestedd03"; + String updatedTagField4 = "The Indian-crested.porcupine_The Indian crestedd04"; + String updatedTagField5 = "The Indian-crested.porcupine_The Indian crestedd05"; + String updatedTagField6 = "The Indian-crested.porcupine_The Indian crestedd06"; + String updatedTagField7 = "The Indian-crested.porcupine_The Indian crestedd07"; + String updatedTagField8 = "The Indian-crested.porcupine_The Indian crestedd08"; + String updatedTagField9 = "The Indian-crested.porcupine_The Indian crestedd09"; + String updatedTagField10 = "The Indian-crested.porcupine_The Indian crestedd10"; + String updatedTagField11 = "The Indian-crested.porcupine_The Indian crestedd11"; + String updatedTagField12 = "The Indian-crested.porcupine_The Indian crestedd12"; + String updatedTagField13 = "The Indian-crested.porcupine_The Indian crestedd13"; + String updatedTagField14 = "The Indian-crested.porcupine_The Indian crestedd14"; + String updatedTagField15 = "The Indian-crested.porcupine_The Indian crestedd15"; + String updatedTagField16 = "The Indian-crested.porcupine_The Indian crestedd16"; + String updatedTagField17 = "The Indian-crested.porcupine_The Indian crestedd17"; + String updatedTagField18 = "The Indian-crested.porcupine_The Indian crestedd18"; + String updatedTagField19 = "The Indian-crested.porcupine_The Indian crestaa"; + + resourceTags = new ArrayList(); + resourceTags.add(updatedTagField); + resourceTags.add(updatedTagField1); + resourceTags.add(updatedTagField2); + resourceTags.add(updatedTagField3); + resourceTags.add(updatedTagField4); + resourceTags.add(updatedTagField5); + resourceTags.add(updatedTagField6); + resourceTags.add(updatedTagField7); + resourceTags.add(updatedTagField8); + resourceTags.add(updatedTagField9); + resourceTags.add(updatedTagField10); + resourceTags.add(updatedTagField11); + resourceTags.add(updatedTagField12); + resourceTags.add(updatedTagField13); + resourceTags.add(updatedTagField14); + resourceTags.add(updatedTagField15); + resourceTags.add(updatedTagField16); + resourceTags.add(updatedTagField17); + resourceTags.add(updatedTagField18); + resourceTags.add(updatedTagField19); + resourceTags.add(resourceDetails.getName()); + // set description + resourceDetails.setTags(resourceTags); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // Add another tag-exceeds limit + resourceTags.add("d"); + resourceDetails.setTags(resourceTags); + ArrayList myArray = new ArrayList(); + myArray.add(0, "1024"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT.name(), myArray, + updatedRestResponse.getResponse()); + + // Tag exceeds limit - 51 + resourceTags = new ArrayList(); + updatedTagField = "The Indian-crested.porcupine_The Indian crestedddsw"; + resourceTags.add(updatedTagField); + resourceTags.add(resourceDetails.getName()); + // set description + resourceDetails.setTags(resourceTags); + myArray.remove(0); + myArray.add(0, "50"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), myArray, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResource_DesriptionFieldValidation() throws Exception { + // define and create resource + RestResponse updatedRestResponse; + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + String uniqueId = resourceDetails.getUniqueId(); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + List resource = new ArrayList<>(); + resource.add("Resource"); + // update resource description metadata: 0 characters + String updatedDescription = ""; + // set description + resourceDetails.setDescription(updatedDescription); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), resource, + updatedRestResponse.getResponse()); + + // update resource description metadata: null + updatedDescription = null; + // set description + resourceDetails.setDescription(updatedDescription); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), resource, + updatedRestResponse.getResponse()); + + // update resource description metadata: 1 characters + updatedDescription = "A"; + // set description + resourceDetails.setDescription(updatedDescription); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // update resource description metadata: 1024 characters + updatedDescription = "The Indian crested porcupine *{Hystrix indica}*, or Indian porcupine is a member of the Old World porcupines." + + "It is quite an adaptable rodent, found throughout southern Asia and the Middle East." + + "It is tolerant of several different habitats: mountains, tropical and subtropical grasslands, scrublands, and forests." + + "It is a large rodent, growing more than 0.9 m = (3 ft) long and weighing 14.5 kg = (32 lb)! [citation needed] It is covered in multiple layers of quills." + + "The longest quills grow from its shoulders to about a third of the animal's length." + + "Its tail is covered in short, hollow quills that can rattle when threatened." + + "It has broad feet and long claws for digging. When attacked, the Indian crested porcupine raises its quills and rattles the hollow quills on its tail." + + "If the predator persists past these threats, the porcupine launches a backwards assault, hoping to stab its attacker with its quills." + + "It does this so effectively that most brushes between predators and the Indian porcupine end in death or severe injury"; + // set description + resourceDetails.setDescription(updatedDescription); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + parseResponseAndValidate(resourceDetails, updatedRestResponse); + + // update resource description metadata: 1025 characters + updatedDescription = "The Indian crested porcupine *{Hystrix indica}*, or Indian porcupine is a member of the Old World porcupines." + + "It is quite an adaptable rodent, found throughout southern Asia and the Middle East." + + "It is tolerant of several different habitats: mountains, tropical and subtropical grasslands, scrublands, and forests." + + "It is a large rodent, growing more than 0.9 m = (3 ft) long and weighing 14.5 kg = (32 lb)! [citation needed] It is covered in multiple layers of quills." + + "The longest quills grow from its shoulders to about a third of the animal's length." + + "Its tail is covered in short, hollow quills that can rattle when threatened." + + "It has broad feet and long claws for digging. When attacked, the Indian crested porcupine raises its quills and rattles the hollow quills on its tail." + + "If the predator persists past these threats, the porcupine launches a backwards assault, hoping to stab its attacker with its quills." + + "It does this so effectively that most brushes between predators and the Indian porcupine end in death or severe injury."; + // set description + resourceDetails.setDescription(updatedDescription); + resource.add(1, "1024"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, + ""); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT.name(), resource, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResource_TagsFormatValidation() throws Exception { + char[] notValidCharsArray = getTagInValidFormatChars(); + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check recourse created ", 201, restResponse.getErrorCode().intValue()); + String resourceName = resourceDetails.getName(); + + // update tag details + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + ArrayList resourceTags = new ArrayList(); + + String updatedTagField; + RestResponse updatedRestResponse; + List variables = Arrays.asList("Resource", "tag"); + + for (int i = 0; i < notValidCharsArray.length; i++) { + updatedTagField = "UpdatedTag" + notValidCharsArray[i]; + resourceTags = new ArrayList(); + resourceTags.add(updatedTagField); + resourceTags.add(resourceDetails.getName()); + // set description + updatedResourceDetails.setTags(resourceTags); + + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", + updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource icon", 400, + updatedRestResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating resource icon", "Bad Request", + updatedRestResponse.getResponseMessage().toString()); + + } + + } + + @Test + public void UpdateResourceCategory_negativeFlow() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after update resource", 201, restResponse.getErrorCode().intValue()); + Resource resourceBeforeUpdate = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + String uniqueID = resourceDetails.getUniqueId(); + + // Update resource Category Successfully + ResourceReqDetails updatedResourceDetails = resourceDetails; + + updatedResourceDetails.removeAllCategories(); + updatedResourceDetails.addCategoryChain(ServiceCategoriesEnum.MOBILITY.getValue(), + ResourceCategoryEnum.APPLICATION_L4_DATABASE.getSubCategory()); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + + // validate response + List resourceList = new ArrayList(); + resourceList.add(0, "Resource"); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CATEGORY.name(), resourceList, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource", 400, updatedRestResponse.getErrorCode().intValue()); + + // Updating resource category + updatedResourceDetails = defineUpdateResourceWithNonUpdatableFields(resourceBeforeUpdate); + updatedResourceDetails.addCategory(""); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + // validate response + resourceList = new ArrayList(); + resourceList.add(0, "Resource"); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), resourceList, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource", 400, updatedRestResponse.getErrorCode().intValue()); + + // Updating resource category + updatedResourceDetails = defineUpdateResourceWithNonUpdatableFields(resourceBeforeUpdate); + updatedResourceDetails.addCategory("XXXXXX"); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + // validate response + resourceList = new ArrayList(); + resourceList.add(0, "Resource"); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CATEGORY.name(), resourceList, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource", 400, updatedRestResponse.getErrorCode().intValue()); + + // CheckIn Resource + logger.debug("Changing resource life cycle "); + RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); // NOT_CERTIFIED_CHECKIN + assertEquals("Check response code after checkin resource", 200, checkoutResource.getErrorCode().intValue()); + + // Update resource Category + updatedResourceDetails = defineUpdateResourceWithNonUpdatableFields(resourceBeforeUpdate); + updatedResourceDetails.addCategory(ServiceCategoriesEnum.VOIP.getValue()); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, + resourceDetails.getUniqueId(), ""); + // verify response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), Empty_List, + updatedRestResponse.getResponse()); + assertEquals("Check response code after updating resource", 409, updatedRestResponse.getErrorCode().intValue()); + + // CheckIn Resource + logger.debug("Changing resource life cycle "); + RestResponse checkinResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); // NOT_CERTIFIED_CHECKIN + assertNotNull("check response object is not null after checkout resource", checkoutResource); + assertNotNull("check error code exists in response after checkIn resource", checkoutResource.getErrorCode()); + assertEquals("Check response code after checkin resource", 200, checkoutResource.getErrorCode().intValue()); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, uniqueID); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(resourceDetails, getRestResponse); + + } + + @Test + public void UpdateResourceCategorySuccessfully() throws Exception { + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after update resource", 201, restResponse.getErrorCode().intValue()); + Resource resourceBeforeUpdate = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + + // Update resource Category Successfully + ResourceReqDetails updatedResourceDetails = resourceDetails; + + updatedResourceDetails.removeAllCategories(); + updatedResourceDetails.addCategoryChain(ResourceCategoryEnum.APPLICATION_L4_DATABASE.getCategory(), + ResourceCategoryEnum.APPLICATION_L4_DATABASE.getSubCategory()); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncModifierDetails, resourceDetails.getUniqueId(), ""); + + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue()); + // parseResponseAndValidateNonUpdatable(updatedResourceDetails, + // updatedRestResponse); + parseResponseAndValidate(updatedResourceDetails, updatedRestResponse); + + // validate category updated + assertTrue(updatedResourceDetails.getCategories().get(0).getName() + .equals(ResourceCategoryEnum.APPLICATION_L4_DATABASE.getCategory())); + + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, + resourceDetails.getUniqueId()); + assertNotNull("check response object is not null after update resource", getRestResponse); + parseResponseAndValidate(updatedResourceDetails, getRestResponse); + + ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.1"); + } + + // Benny + + @Test + public void Validation_UpdateIcon() throws Exception { + // Fields to update (Forbidden) + String _updatedIcon = "mySecondIcon.Jpg"; + + // administrator permissions + User sdncAdminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // define and create resource + ResourceRestUtils.deleteResourceByNameAndVersion(sdncAdminModifierDetails, resourceDetails.getName(), "0.1"); + + RestResponse restResponse = createResource(sdncAdminModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + String resourceName = resourceDetails.getName(); + + // update metadata details + ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); + // change icon of metadata + updatedResourceDetails.setIcon(_updatedIcon); + // PUT request + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, + sdncAdminModifierDetails, resourceDetails.getUniqueId(), ""); + + // validate response + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), + Arrays.asList("Resource"), updatedRestResponse.getResponse()); + + // empty icon + _updatedIcon = ""; + updatedResourceDetails.setIcon(_updatedIcon); + updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncAdminModifierDetails, + resourceDetails.getUniqueId(), ""); + assertNotNull("check response object is not null after update resource", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), + Arrays.asList("Resource"), updatedRestResponse.getResponse()); + + // get resource with original name. original metadata should be returned + RestResponse getRestResponse = ResourceRestUtils.getResource(sdncAdminModifierDetails, + resourceDetails.getUniqueId()); + // validate response + assertNotNull("check response object is not null after get resource", getRestResponse); + assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue()); + + // parse updated response to javaObject + Resource getResourceRespJavaObject = ResponseParser + .convertResourceResponseToJavaObject(getRestResponse.getResponse()); + // validate that metadata was not changed + ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject); + + ResourceRestUtils.deleteResourceByNameAndVersion(sdncAdminModifierDetails, updatedResourceDetails.getName(), + "0.1"); + + } + + @Test + public void UpdateResourceTypeSuccess() throws Exception { + // LCS is CheckOut + String newResourceType = ResourceTypeEnum.VL.toString(); + String currentResourceType = resourceDetails.getResourceType(); + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + Resource currentResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + resourceDetails.setResourceType(newResourceType); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResourceJavaObject.getUniqueId(), ""); + assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue()); + Resource updatedResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(updatedRestResponse.getResponse()); + // assertTrue("Check resource type after update resource", + // updatedResourceJavaObject.getResourceType().toString().equals(resourceType)); + assertTrue("Check resource type after update resource", + updatedResourceJavaObject.getResourceType().toString().equals(currentResourceType)); + + } + + @Test + public void UpdateResourceTypeAndNameSuccess() throws Exception { + // LCS is CheckOut + String newResourceType = ResourceTypeEnum.VL.toString(); + String currentResourceType = resourceDetails.getResourceType(); + String newResourceName = "new Name"; + + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + Resource currentResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + resourceDetails.setResourceType(newResourceType); + resourceDetails.setName(newResourceName); + List tags = resourceDetails.getTags(); + tags.add(newResourceName); + resourceDetails.setTags(tags); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResourceJavaObject.getUniqueId(), ""); + assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue()); + Resource updatedResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(updatedRestResponse.getResponse()); + assertTrue("Check resource type after update resource", + updatedResourceJavaObject.getResourceType().toString().equals(currentResourceType)); + assertTrue("Check resource name after update resource", + updatedResourceJavaObject.getName().equals(newResourceName)); + + } + + @Test + public void UpdateResourceTypeAfterResourceCertification() throws Exception { + + String newResourceType = ResourceTypeEnum.VF.toString(); + String currentResourceType = resourceDetails.getResourceType(); + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + Resource currentResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + resourceDetails.setResourceType(newResourceType); + restResponse = LifecycleRestUtils.certifyResource(resourceDetails); + assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue()); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue()); + currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResourceJavaObject.getUniqueId(), ""); + assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue()); + Resource updatedResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(updatedRestResponse.getResponse()); + // assertTrue("Check resource type after update resource", + // updatedResourceJavaObject.getResourceType().toString().equals(newResourceType)); + assertTrue("Check resource type after update resource", + updatedResourceJavaObject.getResourceType().toString().equals(currentResourceType)); + + } + + @Test + public void UpdateResourceTypeCheckInLCS() throws Exception { + + String resourceType = ResourceTypeEnum.VL.toString(); + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + Resource currentResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + resourceDetails.setResourceType(resourceType); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, + LifeCycleStatesEnum.CHECKIN); + assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue()); + + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResourceJavaObject.getUniqueId(), ""); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + + assertNotNull("check response object is not null after create resouce", updatedRestResponse); + assertNotNull("check error code exists in response after create resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), + updatedRestResponse.getErrorCode()); + + List variables = new ArrayList<>(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResourceTypeCertifiedLCS() throws Exception { + + String resourceType = ResourceTypeEnum.VL.toString(); + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + Resource currentResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + restResponse = LifecycleRestUtils.certifyResource(resourceDetails); + assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue()); + + resourceDetails.setResourceType(resourceType); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResourceJavaObject.getUniqueId(), ""); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + + assertNotNull("check response object is not null after create resouce", updatedRestResponse); + assertNotNull("check error code exists in response after create resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), + updatedRestResponse.getErrorCode()); + + List variables = new ArrayList<>(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + updatedRestResponse.getResponse()); + + } + + @Test + public void UpdateResourceTypeInvalidType() throws Exception { + + String resourceType = "INVALID TYPE"; + RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails); + assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue()); + Resource currentResourceJavaObject = ResponseParser + .convertResourceResponseToJavaObject(restResponse.getResponse()); + + resourceDetails.setResourceType(resourceType); + RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, + sdncModifierDetails, currentResourceJavaObject.getUniqueId(), ""); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name()); + + assertNotNull("check response object is not null after update resouce", updatedRestResponse); + assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode()); + assertEquals("Check response code after update resource", errorInfo.getCode(), + updatedRestResponse.getErrorCode()); + + List variables = new ArrayList<>(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, + updatedRestResponse.getResponse()); + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java new file mode 100644 index 0000000000..59050103ca --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java @@ -0,0 +1,481 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.ErrorInfo; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.ComponentInstanceRestUtils; +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.validation.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import com.google.gson.Gson; + +import fj.data.Either; + +public class VFResourceInstanceNameCRUD extends ComponentBaseTest { + + protected static ServiceReqDetails serviceDetails; + protected static ResourceReqDetails resourceDetailsVFC; + protected static ResourceReqDetails resourceDetailsVL; + protected static ResourceReqDetails resourceDetailsVF; + protected static ResourceReqDetails resourceDetailsCP; + protected static ComponentInstanceReqDetails resourceInstanceReqDetailsVF; + protected static ComponentInstanceReqDetails resourceInstanceReqDetailsVFC; + protected static ComponentInstanceReqDetails resourceInstanceReqDetailsVL; + protected static ComponentInstanceReqDetails resourceInstanceReqDetailsCP; + protected static User sdncDesignerDetails1; + protected static User sdncTesterDeatails1; + protected static User sdncAdminDetails1; + protected static ArtifactReqDetails heatArtifactDetails; + protected static ArtifactReqDetails defaultArtifactDetails; + protected static int maxLength = 50; + protected static Resource resourceVF = null; + + @Rule + public static TestName name = new TestName(); + + public VFResourceInstanceNameCRUD() { + super(name, VFResourceInstanceNameCRUD.class.getName()); + } + + @BeforeMethod + + public void init() throws Exception { + + // serviceDetails = ElementFactory.getDefaultService(); + // resourceDetailsVFC = + // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC.toString(), + // "resourceVFC"); + // resourceDetailsVF = + // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF.toString(), + // "resourceVF3"); + // resourceDetailsVL = + // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VL.toString(), + // "resourceVL"); + // resourceDetailsCP = + // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.CP.toString(), + // "resourceCP"); + sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // heatArtifactDetails = + // ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + + Either resourceDetailsCP_01e = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(resourceDetailsCP_01e.left().value(), UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CHECKIN, true); + resourceDetailsCP = new ResourceReqDetails(resourceDetailsCP_01e.left().value()); + Either resourceDetailsVL_01e = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(resourceDetailsVL_01e.left().value(), UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CHECKIN, true); + resourceDetailsVL = new ResourceReqDetails(resourceDetailsVL_01e.left().value()); + Either resourceDetailsVF_01e = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true); + resourceDetailsVF = new ResourceReqDetails(resourceDetailsVF_01e.left().value()); + Either resourceDetailsVFC_01e = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.changeComponentState(resourceDetailsVFC_01e.left().value(), UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CHECKIN, true); + resourceDetailsVFC = new ResourceReqDetails(resourceDetailsVFC_01e.left().value()); + + resourceInstanceReqDetailsVFC = ElementFactory.getDefaultComponentInstance("VFC", resourceDetailsVFC); + resourceInstanceReqDetailsVF = ElementFactory.getDefaultComponentInstance("VF", resourceDetailsVF); + resourceInstanceReqDetailsVL = ElementFactory.getDefaultComponentInstance("VL", resourceDetailsVL); + resourceInstanceReqDetailsCP = ElementFactory.getDefaultComponentInstance("CP", resourceDetailsCP); + sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + } + + @Test + public void addResourceInstanceToVF() throws Exception { + + createVFWithCertifiedResourceInstance(resourceDetailsCP, resourceInstanceReqDetailsCP); + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 1"); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + @Test + public void updateResourceInstanceName() throws Exception { + + // update resource instance name + String resourceInstanceUpdatedName = "resource New 2"; + + ResourceReqDetails updatedResourceDetailsVLC = changeResouceName(resourceDetailsVFC, + resourceInstanceUpdatedName); + createVFWithCertifiedResourceInstance(updatedResourceDetailsVLC, resourceInstanceReqDetailsVFC); + + resourceInstanceReqDetailsVFC.setName(resourceInstanceUpdatedName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetailsVFC, sdncDesignerDetails1, resourceVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + assertTrue(updateResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceUpdatedName); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + @Test + public void updateResourceInstanceNameToNextGeneratedName() throws Exception { + + // update resource instance name + String resourceInstanceUpdatedName = resourceInstanceReqDetailsCP.getName() + " 2"; + + ResourceReqDetails updatedResourceDetailsVL = changeResouceName(resourceDetailsVL, resourceInstanceUpdatedName); + createVFWithCertifiedResourceInstance(updatedResourceDetailsVL, resourceInstanceReqDetailsVL); + resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName); + + // add second resource instance + RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP, + sdncDesignerDetails1, resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1"); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2"); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + @Test + public void normolizeUpdatedResourceInstanceName() throws Exception { + + String resourceInstanceUpdatedName = "resource new - .2"; + String normalizedName = "resourcenew2"; + + ResourceReqDetails updatedResourceDetailsVL = changeResouceName(resourceDetailsVL, resourceInstanceUpdatedName); + + createVFWithCertifiedResourceInstance(updatedResourceDetailsVL, resourceInstanceReqDetailsVL); + // update resource instance name + resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName); + + // add second resource instance + RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP, + sdncDesignerDetails1, resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1"); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2"); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + @Test + public void updatedResourceInstanceNameToEmpty() throws Exception { + + createVFWithCertifiedResourceInstance(resourceDetailsVL, resourceInstanceReqDetailsVL); + String resourceInstanceUpdatedName = ""; + String resourceInstancePreviousName = resourceDetailsCP.getName(); + + // add second resource instance + RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP, + sdncDesignerDetails1, resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails1, resourceVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + assertEquals("Check response code after RI update request", 200, + updateResourceInstanceResponse.getErrorCode().intValue()); + // change request + // ErrorInfo errorInfo = + // Utils.parseYaml(ActionStatus.MISSING_COMPONENT_NAME.name()); + // utils.validateResponseCode(updateResourceInstanceResponse, + // errorInfo.getCode(), "update resource instance"); + // + // List variables = Arrays.asList("Resource Instance"); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_COMPONENT_NAME.name(), + // variables, updateResourceInstanceResponse.getResponse()); + + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1"); + resourceInstanceExpectedListName.add(resourceInstancePreviousName + " 3"); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + @Test + public void updatedResourceNameLengthExceedMaximumCharacters() throws Exception { + + String resourceInstancePreviousName = resourceDetailsCP.getName(); + // update resource instance name + String resourceInstanceUpdatedName = "a"; + for (int i = 0; i < maxLength; i++) { + resourceInstanceUpdatedName += "b"; + } + // ResourceReqDetails updatedResourceDetailsVL = + // changeResouceName(resourceDetailsVL, resourceInstanceUpdatedName); + + createVFWithCertifiedResourceInstance(resourceDetailsVL, resourceInstanceReqDetailsVL); + // add second resource instance + RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP, + sdncDesignerDetails1, resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + String prevName = resourceInstanceReqDetailsCP.getName(); + resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails1, resourceVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name()); + // utils.validateResponseCode(updateResourceInstanceResponse, + // errorInfo.getCode(), "update resource instance"); + + List variables = Arrays.asList("Resource Instance", "50"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), variables, + updateResourceInstanceResponse.getResponse()); + + resourceInstanceReqDetailsCP.setName(prevName); + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1"); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2"); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + @Test + public void updatedResourceNameWithUnSupportedCharacters() throws Exception { + + createVFWithCertifiedResourceInstance(resourceDetailsVL, resourceInstanceReqDetailsVL); + String resourceInstancePreviousName = resourceDetailsCP.getName(); + // update resource instance name + String resourceInstanceUpdatedName = "a???<>"; + + // add second resource instance + RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP, + sdncDesignerDetails1, resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + String prevValue = resourceInstanceReqDetailsCP.getName(); + resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails1, resourceVF.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_COMPONENT_NAME.name()); + // ResourceRestUtils.validateResponseCode(updateResourceInstanceResponse, + // errorInfo.getCode(), "update resource instance"); + + List variables = Arrays.asList("Resource Instance"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), variables, + updateResourceInstanceResponse.getResponse()); + + resourceInstanceReqDetailsCP.setName(prevValue); + + // validate RI name + List resourceInstances = resourceVF.getComponentInstances(); + List resourceInstanceListName = new ArrayList(); + for (int i = 0; i < resourceInstances.size(); i++) { + resourceInstanceListName.add(resourceInstances.get(i).getName()); + } + List resourceInstanceExpectedListName = new ArrayList(); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1"); + resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2"); + String message = "resource instance name"; + Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message); + + } + + private static ResourceReqDetails changeResouceName(ResourceReqDetails resourceDet, + String resourceInstanceUpdatedName) throws Exception { + + ResourceReqDetails updatedResourceDetails = new ResourceReqDetails(); + updatedResourceDetails = resourceDet; + updatedResourceDetails.setName(resourceInstanceUpdatedName); + List tags = new ArrayList(); + tags.add(resourceInstanceUpdatedName); + updatedResourceDetails.setTags(tags); + Gson gson = new Gson(); + String updatedResourceBodyJson = gson.toJson(updatedResourceDetails); + RestResponse response = LifecycleRestUtils.changeResourceState(resourceDet, sdncDesignerDetails1, + resourceDet.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertTrue("change LS state to CHECKOUT, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + response = ResourceRestUtils.updateResourceMetadata(updatedResourceBodyJson, sdncDesignerDetails1, + updatedResourceDetails.getUniqueId()); + assertEquals("Check response code after updateresource name", 200, response.getErrorCode().intValue()); + response = LifecycleRestUtils.changeResourceState(updatedResourceDetails, sdncDesignerDetails1, + resourceDet.getVersion(), LifeCycleStatesEnum.CHECKIN); + + return updatedResourceDetails; + + } + + // private Component changeResouceName(Resource resourceDet, String + // resourceInstanceUpdatedName) throws Exception{ + // + // User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // Resource updatedResourceDetails = resourceDet; + // RestResponse response = + // LifecycleRestUtils.changeComponentState(updatedResourceDetails, + // defaultUser, LifeCycleStatesEnum.CHECKOUT, "state changed"); + // assertTrue("change LS state to CHECKOUT, returned status:" + + // response.getErrorCode(),response.getErrorCode() == 200); + // updatedResourceDetails.setName(resourceInstanceUpdatedName); + // List tags = new ArrayList(); + // tags.add(resourceInstanceUpdatedName); + // updatedResourceDetails.setTags(tags); + // Gson gson = new Gson(); + // ResourceReqDetails resourceReqDetails = new + // ResourceReqDetails(updatedResourceDetails); + // String updatedResourceBodyJson = gson.toJson(resourceReqDetails); + // response = ResourceRestUtils.updateResource(updatedResourceBodyJson, + // defaultUser, updatedResourceDetails.getUniqueId()); + // assertEquals("Check response code after updateresource name", 200, + // response.getErrorCode().intValue()); + // response = + // LifecycleRestUtils.changeComponentState(updatedResourceDetails, + // defaultUser, LifeCycleStatesEnum.CHECKIN, "state changed"); + // assertEquals("Check response code after updateresource name", 200, + // response.getErrorCode().intValue()); + // + // return updatedResourceDetails; + // + // } + + private void createVFWithCertifiedResourceInstance(ResourceReqDetails resourceDetails, + ComponentInstanceReqDetails resourceInstanceReqDetails) throws Exception { + + RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails1, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after CHECKOUT", 200, response.getErrorCode().intValue()); + + // add heat artifact to resource and certify + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, + resourceDetails.getUniqueId()); + assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + response = LifecycleRestUtils.certifyResource(resourceDetails); + assertEquals("Check response code after CERTIFY request", 200, response.getErrorCode().intValue()); + + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + resourceInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerDetails1, + resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + } + + protected Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException { + RestResponse response = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails1); + assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue()); + return ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java new file mode 100644 index 0000000000..8a17c3c115 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java @@ -0,0 +1,319 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.List; + +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.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.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.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.AssocType; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.execute.lifecycle.LCSbaseTest; +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.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import fj.data.Either; + +public class ValidateExtendedVfData extends ComponentBaseTest { + + protected Resource resourceDetailsVF; + protected Resource resourceDetailsCP_01; + protected Resource resourceDetailsVL_01; + protected Resource resourceDetailsVFCcomp; + + protected User sdncUserDetails; + + @Rule + public static TestName name = new TestName(); + + public ValidateExtendedVfData() { + super(name, ValidateExtendedVfData.class.getName()); + } + + @BeforeMethod + public void create() throws Exception { + + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Either resourceDetailsVFe = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true); + resourceDetailsVF = resourceDetailsVFe.left().value(); + Either resourceDetailsCP_01e = AtomicOperationUtils + .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.PORT, + ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true); + resourceDetailsCP_01 = resourceDetailsCP_01e.left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsCP_01, UserRoleEnum.DESIGNER, + true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsCP_01, + UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsCP_01, + UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_NET, resourceDetailsCP_01, + UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsCP_01, UserRoleEnum.DESIGNER, + true, true); + AtomicOperationUtils.changeComponentState(resourceDetailsCP_01, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + Either resourceDetailsVL_01e = AtomicOperationUtils + .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VL, NormativeTypesEnum.NETWORK, + ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true); + resourceDetailsVL_01 = resourceDetailsVL_01e.left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVL_01, UserRoleEnum.DESIGNER, + true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsVL_01, + UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsVL_01, + UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_NET, resourceDetailsVL_01, + UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVL_01, UserRoleEnum.DESIGNER, + true, true); + AtomicOperationUtils.changeComponentState(resourceDetailsVL_01, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + + Either resourceDetailsVFCcompE = AtomicOperationUtils + .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetailsVFCcomp = resourceDetailsVFCcompE.left().value(); + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + + ComponentInstance resourceDetailsCP_01ins = AtomicOperationUtils + .addComponentInstanceToComponentContainer(resourceDetailsCP_01, resourceDetailsVF, + UserRoleEnum.DESIGNER, true) + .left().value(); + ComponentInstance resourceDetailsVL_01ins = AtomicOperationUtils + .addComponentInstanceToComponentContainer(resourceDetailsVL_01, resourceDetailsVF, + UserRoleEnum.DESIGNER, true) + .left().value(); + ComponentInstance resourceDetailsVFCcomp_ins = AtomicOperationUtils + .addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, resourceDetailsVF, + UserRoleEnum.DESIGNER, true) + .left().value(); + + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF, resourceDetailsCP_01ins, + resourceDetailsVL_01ins, AssocType.LINKABLE.getAssocType(), UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF, resourceDetailsCP_01ins, + resourceDetailsVFCcomp_ins, AssocType.BINDABLE.getAssocType(), UserRoleEnum.DESIGNER, true); + + } + + @Test + public void getResourceLatestVersion() throws Exception { + + RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + // resourceDetailsVF = + // AtomicOperationUtils.getResourceObject(resourceDetailsVF, + // UserRoleEnum.DESIGNER); + RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionList(sdncUserDetails); + assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(), + getResourceLatestVersionResponse.getErrorCode() == 200); + + List resourceList = ResourceRestUtils + .restResponseToResourceObjectList(getResourceLatestVersionResponse.getResponse()); + Resource resource = ResourceRestUtils.getResourceObjectFromResourceListByUid(resourceList, + resourceDetailsVF.getUniqueId()); + + callAllCheckMethods(resource); + } + + @Test + public void getFollowedResources() throws Exception { + + RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + // resourceDetailsVF = + // AtomicOperationUtils.getResourceObject(resourceDetailsVF, + // UserRoleEnum.DESIGNER); + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + + RestResponse getFollowedResourcesResponse = ResourceRestUtils.getFollowedList(sdncUserDetails); + String json = getFollowedResourcesResponse.getResponse(); + JSONObject jsonResp = (JSONObject) JSONValue.parse(json); + JSONArray resources = (JSONArray) jsonResp.get("resources"); + + List resourceList = ResourceRestUtils.restResponseToResourceObjectList(resources.toString()); + Resource resource = ResourceRestUtils.getResourceObjectFromResourceListByUid(resourceList, + resourceDetailsVF.getUniqueId()); + // TODO if get followed list Api should return full object data? + // callAllCheckMethods(resource); + } + + @Test + public void lifeCycleChekInRequest() throws Exception { + + RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + // resourceDetailsVF = + // AtomicOperationUtils.getResourceObject(resourceDetailsVF, + // UserRoleEnum.DESIGNER); + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + callAllCheckMethods(resource); + } + + @Test + public void lifeCycleChekOutRequest() throws Exception { + + RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CHECKOUT); + assertTrue("change LC state to CHECKOUT, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + callAllCheckMethods(resource); + } + + @Test + public void lifeCycleRequestForCertification() throws Exception { + + RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CHECKIN); + assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertTrue("change LC state to CERTIFICATIONREQUEST, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + callAllCheckMethods(resource); + } + + @Test + public void lifeCycleCertificationRequest() throws Exception { + + RestResponse response = AtomicOperationUtils + .changeComponentState(resourceDetailsVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, false) + .getRight(); + assertTrue("change LC state to CERTIFY, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + callAllCheckMethods(resource); + } + + @Test + public void checkGetResourceAfterCertificationRequest() throws Exception { + + RestResponse response = AtomicOperationUtils + .changeComponentState(resourceDetailsVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, false) + .getRight(); + assertTrue("change LC state to CERTIFY, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER); + + callAllCheckMethods(resourceDetailsVF); + } + + @Test + public void updateResourceMetadata() throws Exception { + + resourceDetailsVF.setDescription("stamStam"); + ResourceReqDetails resourceDetailsVFreqD = new ResourceReqDetails(resourceDetailsVF); + RestResponse updateResourceResponse = ResourceRestUtils.updateResourceMetadata(resourceDetailsVFreqD, + sdncUserDetails, resourceDetailsVF.getUniqueId()); + assertTrue("response code is not 200, returned :" + updateResourceResponse.getErrorCode(), + updateResourceResponse.getErrorCode() == 200); + + Resource resource = ResponseParser.convertResourceResponseToJavaObject(updateResourceResponse.getResponse()); + + callAllCheckMethods(resource); + } + + private void checkResourceInstances(Resource resource) { + assertNotNull("resource component Instances list is null ", resource.getComponentInstances()); + assertTrue("resource component Instances list is empty ", !resource.getComponentInstances().equals("")); + } + + private void checkResourceInstancesProperties(Resource resource) { + assertNotNull("component Instances properies list is null ", resource.getComponentInstancesProperties()); + assertTrue("component Instances properies list is empty ", + !resource.getComponentInstancesProperties().equals("")); + } + + private void checkResourceInstancesRelations(Resource resource) { + assertNotNull("component Instances Relations list is null ", resource.getComponentInstancesRelations()); + assertTrue("component Instances Relations list is empty ", + !resource.getComponentInstancesRelations().equals("")); + } + + private void checkResourceCapabilities(Resource resource) { + assertNotNull("component Instances Capabilities list is null ", resource.getCapabilities()); + assertTrue("component Instances Capabilities list is empty ", !resource.getCapabilities().equals("")); + } + + private void checkResourceRequirements(Resource resource) { + assertNotNull("component Instances Requirements list is null ", resource.getRequirements()); + assertTrue("component Instances Requirements list is empty ", !resource.getRequirements().equals("")); + } + + private void callAllCheckMethods(Resource resource) { + + checkResourceInstances(resource); + checkResourceInstancesProperties(resource); + checkResourceInstancesRelations(resource); + checkResourceCapabilities(resource); + checkResourceRequirements(resource); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java new file mode 100644 index 0000000000..ea8b89200e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java @@ -0,0 +1,1792 @@ +/*- + * ============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.ci.tests.execute.resource; + +import static org.junit.Assert.assertTrue; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_DELETE; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapReqDef; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +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.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils; +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.validation.BaseValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class VfComponentInstanceCRUDTest extends ComponentInstanceBaseTest { + + @Rule + public static TestName name = new TestName(); + + public VfComponentInstanceCRUDTest() { + super(name, VfComponentInstanceCRUDTest.class.getName()); + } + + @BeforeMethod + public void before() throws Exception { + init(); + createComponents(); + } + + // CREATE Resource + private void createComponents() throws Exception { + createAtomicResource(resourceDetailsVFC_01); + LifecycleRestUtils.changeResourceState(resourceDetailsVFC_01, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createAtomicResource(resourceDetailsVFC_02); + LifecycleRestUtils.changeResourceState(resourceDetailsVFC_02, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createAtomicResource(resourceDetailsCP_01); + LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createAtomicResource(resourceDetailsCP_02); + LifecycleRestUtils.changeResourceState(resourceDetailsCP_02, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createAtomicResource(resourceDetailsVL_01); + LifecycleRestUtils.changeResourceState(resourceDetailsVL_01, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createAtomicResource(resourceDetailsVL_02); + LifecycleRestUtils.changeResourceState(resourceDetailsVL_02, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createVF(resourceDetailsVF_02); + } + + @Test + public void createVfcInstanceByDesigner() throws Exception { + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVFC_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test(enabled = false) // DE189419 + public void createInstanceOfVfToItself() throws Exception { + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVF_02); + createAtomicResourceInstance = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertTrue(createAtomicResourceInstance.getErrorCode() == STATUS_CODE_NOT_FOUND); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void createVfcInstanceByAdmin() throws Exception { + User user = sdncAdminDetails; + createVF(resourceDetailsVF_01, user); + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_01, + resourceDetailsVFC_01, user); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_01, 1, 0); + } + + @Test + public void createCpInstance() throws Exception { + // Create CP instance + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void createVlInstance() throws Exception { + // Create VL instance + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void updateResourceInstanceNameLessMaxLegth() throws Exception { + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("xxxxXthisXstringxisx49XcharcatersXlengthXxxxxxxxx"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + + } + + @Test + public void updateInstanceNameExceedMaxLegth() throws Exception { + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("xxxxXthisXstringxisx51XcharcatersXlengthXxxxxxxxxxx"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT, + updateResourceInstanceResponse.getErrorCode().intValue()); + } + + @Test + public void updateResourceInstanceNameHasMaxLegth() throws Exception { + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("xxxxXthisXstringxisx50XcharcatersXlengthXxxxxxxxxx"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + } + + @Test + public void resourceInstanceNameIsEmpty() throws Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + resourceInstanceReqDetails.setName(""); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + String instanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "name"); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"), + instanceName); + } + + @Test + public void resourceInstanceNameIsNull() throws Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + resourceInstanceReqDetails.setName(null); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + String instanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "name"); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"), + instanceName); + } + + @Test + public void resourceInstanceNameValidation01() throws Exception { + // 2 Instances + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String instanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "name"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"), + instanceName); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "normalizedName"); + instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name"); + componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), + ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"), + instanceName); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void resourceInstanceNameValidation02() throws Exception { + + // 2 Instances + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String instanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "name"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"), + instanceName); + resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(resourceDetailsCP_01); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "normalizedName"); + instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name"); + componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), + ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsCP_01.getName() + "2").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsCP_01.getName() + " 2"), + instanceName); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createVfcInstanceByTester() throws Exception { // Response 409 + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncTesterDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void createVfcInstance_UserIdIsEmpty() throws Exception { + + User sdncUserDetails = new User(); + sdncUserDetails.setUserId(""); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncUserDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void createVfcInstance_UserIdIsNonAsdcUser() throws Exception { + + User sdncUserDetails = new User(); + sdncUserDetails.setUserId("bt4567"); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncUserDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void createAllAtomicInstances() throws Exception { + + // Add to VF resource VFC, CP and VL instances + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 3, 0); + } + + @Test + public void createDefferentVfcInstances() throws Exception { + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVFC_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createDefferentCpInstances() throws Exception { + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createDefferentVLInstances() throws Exception { + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVL_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createSeveralInstanceOfSameVFC() throws Exception { + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVFC_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createSeveralInstanceOfSameVL() throws Exception { + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVL_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createSeveralInstanceOfSameCP() throws Exception { + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void createInstanceOfCpToVfc() throws Exception { // Add to CP to VFC + // (not allowed) + + ComponentInstanceReqDetails resourceInstanceReqDetailsCP = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + ComponentInstanceReqDetails resourceInstanceReqDetailsVFC = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceInstanceReqDetailsVFC.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void createInstanceVfcToCp() throws Exception { // (not allowed) + + ComponentInstanceReqDetails resourceInstanceReqDetailsCP = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + ComponentInstanceReqDetails resourceInstanceReqDetailsVFC = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsVFC, sdncDesignerDetails, resourceInstanceReqDetailsCP.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void createInstanceVlToVfc() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetailsVL = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + ComponentInstanceReqDetails resourceInstanceReqDetailsVFC = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsVFC, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsVL, sdncDesignerDetails, resourceInstanceReqDetailsVFC.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void createInstanceToNonSupportedComponentType() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetailsCP = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE_INSTANCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + // ("Create instance without position is allowed") + @Test + public void createInstanceOfVlWithoutPosXAndPosY() throws Exception { // instance + // does + // not + // have + // position + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + resourceInstanceReqDetails.setPosX(""); + resourceInstanceReqDetails.setPosY(""); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + // Create instance without position is allowed") + @Test + public void createInstanceOfVlWithPositionNull() throws Exception { // instance + // does + // not + // have + // position + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + resourceInstanceReqDetails.setPosX(null); + resourceInstanceReqDetails.setPosY(null); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void createResourceInstanceForNonCheckedOutVF() throws Exception { + + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncAdminDetails, + "0.1", LifeCycleStatesEnum.CHECKIN); + resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + AssertJUnit.assertEquals("Check response code after create user", STATUS_CODE_SUCCESS, + checkInResponse.getErrorCode().intValue()); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + createResourceInstanceResponse.getErrorCode().intValue()); + } + + @Test + public void createResourceInstanceVfCheckedOutByOtherUser() throws Exception { + + // Admin try to add RI to VF which is checked-Out By Designer + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void createResourceInstanceForNonExistingVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, "blablabla", ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + createResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + // Delete + @Test + public void deleteVfcInstanceByDesigner() throws Exception { + + // Create RI + RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVFC_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void deleteVfcInstanceByAdmin() throws Exception { + createVF(resourceDetailsVF_01, sdncAdminDetails); + RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_01, + resourceDetailsVL_01, sdncAdminDetails); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_01, 1, 0); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_01, + sdncAdminDetails); + ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_01, 0, 0); + } + + @Test + public void deleteCpInstance() throws Exception { + + RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void deleteVlInstance() throws Exception { + + RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + } + + @Test + public void deleteOneVlInstance() throws Exception { + + // RI-1 + RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + // RI-2 + createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVL_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + // Delete Resource instance RI-1 + RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteVfcInstanceCheckedByOtherUser() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncTesterDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteInstanceNonSupportedComponentType() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE_INSTANCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteInstanceFromNonVF() throws Exception { + // RI-1 + + ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance1 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE); + // RI-2 + ComponentInstanceReqDetails resourceInstanceCplReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceCplReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance2 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance2, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + // Delete VL instance from CP instance + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceInstanceCplReqDetails.getUniqueId(), + resourceInstanceVlReqDetails.getUniqueId(), ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + } + + @Test + public void deleteNonExistingInstanceFromVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance1 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + resourceInstanceVlReqDetails.setUniqueId("1234567890"); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceVlReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteCpInstanceFromNonCheckOutVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceCpReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceCpReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance1 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, + "0.1", LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS, + checkInResponse.getErrorCode().intValue()); + resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceCpReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteVlInstanceFromNonCheckOutVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance1 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, + "0.1", LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS, + checkInResponse.getErrorCode().intValue()); + resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceVlReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteVfcInstanceFromNonCheckOutVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceVfcReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceVfcReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance1 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, + "0.1", LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS, + checkInResponse.getErrorCode().intValue()); + resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + // Delete Resource instance + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceVfcReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteVlInstance_UserIdIsNonAsdcUser() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + // Delete Resource instance by non-ASDC User + User sdncUserDetails = new User(); + sdncUserDetails.setUserId("bt4567"); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncUserDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + deleteResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void deleteAlreadyDeletedInstance() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_DELETE, + deleteResourceInstanceResponse.getErrorCode().intValue()); + deleteCompInstReqCapFromExpected(componentInstance.getUniqueId()); + getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0); + deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncDesignerDetails, + resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + deleteResourceInstanceResponse.getErrorCode().intValue()); + } + + @Test + public void reCreateDeletedInstance() throws Exception { + + // 2 Instances + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String instanceNormalizedName = ResponseParser + .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "name"); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"), + instanceName); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "normalizedName"); + instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name"); + componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), + ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"), + instanceName); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + // Delete one instance + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance( + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_DELETE, + deleteResourceInstanceResponse.getErrorCode().intValue()); + deleteCompInstReqCapFromExpected(componentInstance.getUniqueId()); + // Create same instance again + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), + "normalizedName"); + instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name"); + componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), + ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "3").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 3"), + instanceName); + + } + + // Update + @Test + public void updateVfcInstanceNameByDesigner() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("abcd"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcd"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "abcd"); + } + + @Test + public void updateVfcInstanceNameByAdmin() throws Exception { + User user = sdncAdminDetails; + createVF(resourceDetailsVF_01, user); + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_01.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_01, 1, 0); + vfcResourceInstanceReqDetails.setName("ABCD E"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_01.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcde"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "ABCD E"); + } + + @Test + public void updateInstanceNameAllowedCharacters() throws Exception { + // Allowed characters: Alphanumeric (a-zA-Z0-9), space (' '), underscore + // ('_'), dash ('-'), dot ('.')) + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("Abcd_1234567890-qwert-yuiop.zxcvb"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + // assertEquals("Check if RI normalizedName is correct ", + // riNormalizedName, "abcd_1234567890-qwert-yuiop.zxcv" ); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "Abcd_1234567890-qwert-yuiop.zxcvb"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, + "abcd1234567890qwertyuiopzxcvb"); + + } + + @Test + public void updateVfcInstanceNameEmpty() throws Exception { + // see US534663 In case a designer removes the current resource instance + // name then BE has to generate again the "default" resource instance + // name + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = ""; + vfcResourceInstanceReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String instanceNormalizedName = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "name"); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"), + instanceName); + } + + @Test + public void updateVfcInstanceNameNull() throws Exception { + // see US534663 In case a designer removes the current resource instance + // name then BE has to generate again the "default" resource instance + // name + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = null; + vfcResourceInstanceReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + final String updateResponse = updateResourceInstanceResponse.getResponse(); + String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateResponse, "normalizedName"); + String instanceName = ResponseParser.getValueFromJsonResponse(updateResponse, "name"); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", + (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName); + AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"), + instanceName); + } + + @Test + public void updateCpInstanceName() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("AbcD"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcd"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "AbcD"); + } + + @Test + public void updateVlInstanceName() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName("ABCD"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcd"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "ABCD"); + } + + @Test + public void updateInstanceNameToArleadyExistInstanceName02() throws Exception { + + // Create VFC instance + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance vfcComponentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(vfcComponentInstance, ComponentTypeEnum.RESOURCE); + // Create CP instance + ComponentInstanceReqDetails cpResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance cpComponentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(cpComponentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0); + cpResourceInstanceReqDetails.setName(vfcComponentInstance.getName()); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS, + updateResourceInstanceResponse.getErrorCode().intValue()); + } + + @Test + public void updateInstanceNameMaxLength() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl12345"; + vfcResourceInstanceReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, newName.toLowerCase()); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, newName); + } + + @Test + public void updateInstanceNameExceedMaxLength() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456"; + vfcResourceInstanceReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT, + updateResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void updateCpInstanceCheckedByOtherUser() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = "Qwertyuiop1234567890"; + resourceInstanceReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + updateResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void UpdateVfcInstance_UserIdIsNonAsdcUser() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = "Qwertyuiop1234567890"; + resourceInstanceReqDetails.setName(newName); + User nonSdncUserDetails = new User(); + nonSdncUserDetails.setUserId("bt4567"); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetails, nonSdncUserDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION, + updateResourceInstanceResponse.getErrorCode().intValue()); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + } + + @Test + public void UpdateResourceInstanceFormNonExistingVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + // LifecycleRestUtils.changeResourceState(resourceDetailsVL_01, + // sdncAdminDetails, "0.1", LifeCycleStatesEnum.CHECKIN); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String newName = "Qwertyuiop1234567890"; + resourceInstanceReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, "blablabla", ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + updateResourceInstanceResponse.getErrorCode().intValue()); + } + + @Test + public void updateNonExistingInstanceFromVF() throws Exception { + + ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance1 = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + resourceInstanceVlReqDetails.setUniqueId("1234567890"); + // String newName= "Qwertyuiop1234567890"; + // resourceInstanceVlReqDetails.setName(newName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + updateResourceInstanceResponse.getErrorCode().intValue()); + } + + // Update + @Test + public void updateVfcInstanceNameAsVfName() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + vfcResourceInstanceReqDetails.setName(resourceDetailsVF_02.getName()); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse); + AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName()); + String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "normalizedName"); + String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name"); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, + resourceDetailsVF_02.getName().toLowerCase()); + AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, resourceDetailsVF_02.getName()); + } + + @Test + public void updateInstanceNameInvalidCharacters() throws Exception { + char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', + '|', '\\', ',' }; + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String newName = "Abcd1"; + String updateName; + for (int i = 0; i < invalidChars.length; i++) { + updateName = newName + invalidChars[i]; + vfcResourceInstanceReqDetails.setName(updateName); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT, + updateResourceInstanceResponse.getErrorCode().intValue()); + } + } + + // Update Position + @Test + public void updateVfcInstancePosition() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String updatePosX = "130"; + String updatePosY = "180"; + vfcResourceInstanceReqDetails.setPosX(updatePosX); + vfcResourceInstanceReqDetails.setPosY(updatePosY); + vfcResourceInstanceReqDetails.setName(null); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String posXFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX"); + String posYFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY"); + AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX); + AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY); + } + + @Test + public void updateVlInstancePosition() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVL_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String updatePosX = "130"; + String updatePosY = "180"; + vfcResourceInstanceReqDetails.setPosX(updatePosX); + vfcResourceInstanceReqDetails.setPosY(updatePosY); + vfcResourceInstanceReqDetails.setName(null); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String posXFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX"); + String posYFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY"); + AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX); + AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY); + } + + @Test + public void updateCpInstancePosition() throws Exception { + + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String updatePosX = "130"; + String updatePosY = "180"; + vfcResourceInstanceReqDetails.setPosX(updatePosX); + vfcResourceInstanceReqDetails.setPosY(updatePosY); + vfcResourceInstanceReqDetails.setName(null); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String posXFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX"); + String posYFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY"); + AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX); + AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY); + } + + @Test + public void updateInstancePositionNegativePosition() throws Exception { + + ComponentInstanceReqDetails cpResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE); + getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0); + String updatePosX = "-100"; + String updatePosY = "-100"; + cpResourceInstanceReqDetails.setPosX(updatePosX); + cpResourceInstanceReqDetails.setPosY(updatePosY); + cpResourceInstanceReqDetails.setName(null); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String posXFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX"); + String posYFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY"); + AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX); + AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY); + } + + @Test + public void updateInstancesPositionSameLocationForBothInstances() throws Exception { + + ComponentInstanceReqDetails cpResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsVFC_01); + createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + String updatePosX = "100"; + String updatePosY = "500"; + vfcResourceInstanceReqDetails.setPosX(updatePosX); + vfcResourceInstanceReqDetails.setPosY(updatePosY); + vfcResourceInstanceReqDetails.setName(null); + cpResourceInstanceReqDetails.setPosX(updatePosX); + cpResourceInstanceReqDetails.setPosY(updatePosY); + cpResourceInstanceReqDetails.setName(null); + RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + String posXFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX"); + String posYFromJsonResponse = ResponseParser + .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY"); + AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX); + AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY); + updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance( + cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), + ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(updateResourceInstanceResponse); + posXFromJsonResponse = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "posX"); + posYFromJsonResponse = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), + "posY"); + AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX); + AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY); + } + + @Test + public void createAllAtomicInstancesTestGetReqCapAPI_suc() throws Exception { + + // Add to VF resource VFC, CP and VL instances + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + + getVfResourceReqCapUsingAPI(3, 0, sdncDesignerDetails); + + } + + // END of Update + + @Test + public void createAllAtomicInstancesTestGetReqCapAPIfailed() throws Exception { + + // Add to VF resource VFC, CP and VL instances + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsVL_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + resourceDetailsVF_02.setUniqueId("dummy"); + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncAdminDetails, + resourceDetailsVF_02); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, + getResourceResponse.getErrorCode().intValue()); + + } + + @Test + public void associateInVF() throws Exception { + + ResourceReqDetails resourceDetailsReq = ElementFactory.getDefaultResourceByType("SoftCompRouter", + NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, + sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC); // resourceType + // = VFC + ResourceReqDetails resourceDetailsCap = ElementFactory.getDefaultResourceByType("MyComput", + NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VFC); // resourceType = VFC + createAtomicResource(resourceDetailsReq); + LifecycleRestUtils.changeResourceState(resourceDetailsReq, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createAtomicResource(resourceDetailsCap); + LifecycleRestUtils.changeResourceState(resourceDetailsCap, sdncAdminDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + + RestResponse riReqR = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsReq, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(riReqR); + RestResponse riCapR = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCap, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(riCapR); + + ComponentInstance riReq = ResponseParser.parseToObject(riReqR.getResponse(), ComponentInstance.class); + ComponentInstance riCap = ResponseParser.parseToObject(riCapR.getResponse(), ComponentInstance.class); + + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + resourceDetailsVF_02); + + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + + List capList = capReqDef.getCapabilities().get("tosca.capabilities.Container"); + List reqList = capReqDef.getRequirements().get("tosca.capabilities.Container"); + + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + requirementDef.setFromNode(riReq.getUniqueId()); + requirementDef.setToNode(riCap.getUniqueId()); + + RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(); + pair.setRequirementOwnerId(riReq.getUniqueId()); + pair.setCapabilityOwnerId(riCap.getUniqueId()); + pair.setRequirement("host"); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("tosca.capabilities.Container"); + pair.setRelationships(relationship); + pair.setCapabilityUid(capList.get(0).getUniqueId()); + pair.setRequirementUid(reqList.get(0).getUniqueId()); + List relationships = new ArrayList<>(); + relationships.add(pair); + requirementDef.setRelationships(relationships); + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS, + associateInstances.getErrorCode().intValue()); + + getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + resourceDetailsVF_02); + capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + + List list = capReqDef.getRequirements().get("tosca.capabilities.Container"); + AssertJUnit.assertEquals("Check requirement", null, list); + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS, + dissociateInstances.getErrorCode().intValue()); + + getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + resourceDetailsVF_02); + capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + + list = capReqDef.getRequirements().get("tosca.capabilities.Container"); + AssertJUnit.assertEquals("Check requirement", 1, list.size()); + + } + + @Test + public void testUnsatisfiedCpReqInVF() throws Exception { + + // Certify all the needed atomic resources + RestResponse response = LifecycleRestUtils.certifyResource(resourceDetailsVFC_02); + ResourceRestUtils.checkSuccess(response); + response = LifecycleRestUtils.certifyResource(resourceDetailsCP_01); + ResourceRestUtils.checkSuccess(response); + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails, + resourceDetailsVF_02.getUniqueId()); + ResourceRestUtils.checkSuccess(response); + + RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String compInstName = ResponseParser.getNameFromResponse(createAtomicResourceInstance); + String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + RestResponse submitForTesting = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, + sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + String[] variables = new String[] { resourceDetailsVF_02.getName(), "VF", "CP (Connection Point)", compInstName, + "requirement", "tosca.capabilities.network.Bindable", "fulfilled" }; + BaseValidationUtils.checkErrorResponse(submitForTesting, + ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, variables); + + createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + fulfillCpRequirement(resourceDetailsVF_02, cpCompInstId, computeCompInstId, computeCompInstId, + sdncDesignerDetails, ComponentTypeEnum.RESOURCE); + + submitForTesting = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + BaseValidationUtils.checkSuccess(submitForTesting); + } + + private void getVfResourceReqCapUsingAPI(int numberOfRIs, int numberOfRelations, User user) + throws IOException, Exception { + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncAdminDetails, + resourceDetailsVF_02); + AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS, + getResourceResponse.getErrorCode().intValue()); + // ResourceValidationUtils.validateResp(getResourceResponse, + // resourceRespJavaObject); + // int numberOfActualRIs = resource.getComponentInstances()!=null ? + // resource.getComponentInstances().size() : 0; + // int numberOfActualRelations = + // resource.getComponentInstancesRelations()!=null ? + // resource.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); + + //// get VF actual Capabilities and Requirements and validate according + //// to expected + Resource vfResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), + Resource.class); + verifyReqCap(vfResource); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java new file mode 100644 index 0000000000..3d338534d1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java @@ -0,0 +1,1012 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.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.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +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.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +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.LifecycleRestUtils; +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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import fj.data.Either; + +public class ChangeServiceDistributionStatusApiTest extends ComponentBaseTest { + + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + protected User sdncDesignerDetails; + protected User sdncAdminDetails; + protected User sdncGovernorDeatails; + protected User sdncTesterDetails; + protected User sdncOpsDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails; + protected Component resourceDetailsVFCcomp; + protected Component serviceDetailsCompp; + + private String userRemarks = "commentTest"; + + private List variablesAsList; + + @Rule + public static TestName name = new TestName(); + + public ChangeServiceDistributionStatusApiTest() throws Exception { + super(name, ChangeServiceDistributionStatusApiTest.class.getName()); + + } + + @BeforeMethod + public void init() throws Exception { + + variablesAsList = new ArrayList(); + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + resourceDetailsVFCcomp = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + true, true); + + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + Service serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ, + UserRoleEnum.DESIGNER, true); + + serviceDetails = new ServiceReqDetails(serviceServ); + + } + + // -----------------------------------------------T E S T + // S--------------------------------------------// + + @Test + public void approveNotCertifiedService_checkout() throws Exception { + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + validateAudit("DApprove", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + } + + @Test + public void approveNotCertifiedService_checkedin() throws Exception { + RestResponse checkinResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals(200, checkinResp.getErrorCode().intValue()); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + validateAudit("DApprove", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + } + + @Test + public void approveNotCertifiedService_inProgress() throws Exception { + RestResponse certReqResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(200, certReqResp.getErrorCode().intValue()); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); + // String auditAction="DApprove"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // version, sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setStatus("403"); + // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() + // + ": " + errorInfo.getMessage(), version, + // serviceDetails.getServiceName())); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DApprove", LifecycleStateEnum.READY_FOR_CERTIFICATION, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + + } + + @Test + public void approveNotCertifiedService_readyForCer() throws Exception { + approveNotCertifiedService_inProgress(); + DbUtils.deleteFromEsDbByPattern("_all"); + + RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(200, startCertResp.getErrorCode().intValue()); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); + // String auditAction="DApprove"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // version, sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setDprevStatus(""); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setStatus("403"); + // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() + // + ": " + errorInfo.getMessage(), version, + // serviceDetails.getServiceName())); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + } + + @Test + public void rejectNotCertifiedService_checkeout() throws Exception { + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // version, sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setDprevStatus(""); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setStatus("403"); + // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() + // + ": " + errorInfo.getMessage(), version, + // serviceDetails.getServiceName())); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + } + + @Test + public void rejectNotCertifiedService_checkedin() throws Exception { + RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertEquals(200, startCertResp.getErrorCode().intValue()); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // version, sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name()); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setDprevStatus(""); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setStatus("403"); + // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() + // + ": " + errorInfo.getMessage(), version, + // serviceDetails.getServiceName())); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + } + + @Test + public void rejectNotCertifiedService_inProgress() throws Exception { + RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(200, startCertResp.getErrorCode().intValue()); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // version, sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.name()); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setDprevStatus(""); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setStatus("403"); + // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() + // + ": " + errorInfo.getMessage(), version, + // serviceDetails.getServiceName())); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.READY_FOR_CERTIFICATION, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + } + + @Test + public void rejectNotCertifiedService_readyForCer() throws Exception { + rejectNotCertifiedService_inProgress(); + DbUtils.deleteFromEsDbByPattern("_all"); + + RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(200, startCertResp.getErrorCode().intValue()); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); + + variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), + variablesAsList, changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // version, sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setDprevStatus(""); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setStatus("403"); + // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() + // + ": " + errorInfo.getMessage(), version, + // serviceDetails.getServiceName())); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); + + } + + @Test + public void approveCertifiedService_bysdncGovernorDeatails() throws Exception { + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncGovernorDeatails); + } + + @Test + public void approveCertifiedService_bysdncAdminDetails() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncAdminDetails); + } + + @Test + public void approveCertifiedService_byDesigner() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncDesignerDetails, 409, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); + // String auditAction="DApprove"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncDesignerDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setStatus("409"); + // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": + // " + errorInfo.getMessage()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, + sdncDesignerDetails); + } + + @Test + public void approveCertifiedService_byTester() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncTesterDetails, 409, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); + // String auditAction="DApprove"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncTesterDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setStatus("409"); + // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": + // " + errorInfo.getMessage()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, + sdncTesterDetails); + } + + @Test + public void approveCertifiedService_byOps() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncOpsDetails, 409, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, + sdncOpsDetails); + + } + + @Test + public void rejectCertifiedService_bysdncGovernorDeatails() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncGovernorDeatails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_REJECTED); + + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncGovernorDeatails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_REJECTED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncGovernorDeatails); + + } + + @Test + public void rejectCertifiedService_bysdncAdminDetails() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_REJECTED); + + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncAdminDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_REJECTED.name()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncAdminDetails); + } + + @Test + public void rejectCertifiedService_byDesigner() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncDesignerDetails, 409, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncDesignerDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setStatus("409"); + // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": + // " + errorInfo.getMessage()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, + sdncDesignerDetails); + } + + @Test + public void rejectCertifiedService_byTester() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncTesterDetails, 409, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncTesterDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setStatus("409"); + // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": + // " + errorInfo.getMessage()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, + sdncTesterDetails); + } + + @Test + public void rejectCertifiedService_byOps() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncOpsDetails, 409, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + // ErrorInfo errorInfo = + // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); + // String auditAction="DReject"; + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, + // certifyService.getVersion(), sdncOpsDetails); + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setResourceType("Service"); + // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); + // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + // expectedResourceAuditJavaObject.setStatus("409"); + // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": + // " + errorInfo.getMessage()); + // expectedResourceAuditJavaObject.setComment(userRemarks); + // expectedResourceAuditJavaObject.setPrevVersion("0.1"); + // + // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, + // auditAction); + + validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, + sdncOpsDetails); + } + + @Test + public void approveServiceNotFound() throws Exception { + String previuosId = serviceDetails.getUniqueId(); + serviceDetails.setUniqueId("dummyId"); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 404, serviceDetails.getVersion()); + serviceDetails.setUniqueId(previuosId); + + variablesAsList = Arrays.asList("dummyId"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variablesAsList, + changeDistStatusAndValidate.getResponse()); + + } + + @Test + public void rejectServiceNotFound() throws Exception { + String previuosId = serviceDetails.getUniqueId(); + serviceDetails.setUniqueId("dummyId"); + + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 404, serviceDetails.getVersion()); + serviceDetails.setUniqueId(previuosId); + + variablesAsList = Arrays.asList("dummyId"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variablesAsList, + changeDistStatusAndValidate.getResponse()); + + } + + @Test + public void rejectService_emptyComment() throws Exception { + userRemarks = ""; + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + } + + @Test + public void rejectService_nullComment() throws Exception { + userRemarks = null; + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + } + + @Test + public void rejectService_spaceComment() throws Exception { + userRemarks = " "; + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + } + + @Test + public void approveService_emptyComment() throws Exception { + userRemarks = ""; + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + } + + @Test + public void approveService_nullComment() throws Exception { + userRemarks = null; + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + } + + @Test + public void approveService_spaceComment() throws Exception { + userRemarks = " "; + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), + changeDistStatusAndValidate.getResponse()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + } + + @Test + public void distributionStatusChange_approve_Reject_AprroveBysdncAdminDetails() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + + RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(approveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse rejectDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncGovernorDeatails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(rejectDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED); + + validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_APPROVED, + DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncGovernorDeatails); + + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse secondApproveDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(secondApproveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_REJECTED, + DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncAdminDetails); + + } + + @Test + public void distributeNotCertifiedServiceTest() throws Exception { + RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(DistributionStatusEnum.DISTRIBUTED, + sdncGovernorDeatails, 200, serviceDetails.getVersion()); + + RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTED); + + } + + @Test + public void distributeCertifiedServiceTest() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(DistributionStatusEnum.DISTRIBUTED, + sdncGovernorDeatails, 200, certifyService.getVersion()); + + RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); + getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTED); + + } + + @Test + public void approveCheckedoutCertifiedServiceTest() throws Exception { + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate( + DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion()); + getDistrubtionStatusValue(approveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); + + RestResponse checkoutResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals(200, checkoutResp.getErrorCode().intValue()); + // Utils r = new Utils(); + + String distributionStatus = ResponseParser.getValueFromJsonResponse(checkoutResp.getResponse(), + "distributionStatus"); + // Utils r1 = new Utils(); + String lifecycleState = ResponseParser.getValueFromJsonResponse(checkoutResp.getResponse(), "lifecycleState"); + + assertTrue("NOT_CERTIFIED_CHECKOUT".equals(lifecycleState)); + assertTrue("DISTRIBUTION_NOT_APPROVED".equals(distributionStatus)); + } + + private RestResponse changeDistStatusAndValidate(DistributionStatusEnum distStatus, User user, int errorCode, + String serviceVersion) throws Exception { + RestResponse distributionResponse = LifecycleRestUtils.changeDistributionStatus(serviceDetails, serviceVersion, + user, userRemarks, distStatus); + assertNotNull(distributionResponse); + assertNotNull(distributionResponse.getErrorCode()); + assertEquals(errorCode, distributionResponse.getErrorCode().intValue()); + + if (userRemarks == " " || userRemarks == null) { + userRemarks = ""; + } + + return distributionResponse; + } + + private void getDistrubtionStatusValue(RestResponse response, DistributionStatusEnum expectedDistributionValue) + throws Exception { + String actualDistributionValue = ResponseParser.getValueFromJsonResponse(response.getResponse(), + "distributionStatus"); + assertEquals(expectedDistributionValue.name(), actualDistributionValue); + } + + private void validateAudit(String Action, LifecycleStateEnum currState, DistributionStatusEnum dPrevStatus, + DistributionStatusEnum dCurrStatus, String status, ActionStatus errorInfoFromFile, User user) + throws Exception { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), user); + expectedResourceAuditJavaObject.setAction(Action); + expectedResourceAuditJavaObject.setResourceType("Service"); + expectedResourceAuditJavaObject.setCurrState(currState.name()); + expectedResourceAuditJavaObject.setDprevStatus(dPrevStatus.name()); + expectedResourceAuditJavaObject.setDcurrStatus(dCurrStatus.name()); + expectedResourceAuditJavaObject.setComment(userRemarks); + expectedResourceAuditJavaObject.setDesc("OK"); + + if (errorInfoFromFile != null) { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorInfoFromFile.name()); + expectedResourceAuditJavaObject + .setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variablesAsList)); + } + + if (status != null) + expectedResourceAuditJavaObject.setStatus(status); + + if (currState != LifecycleStateEnum.CERTIFIED) { + expectedResourceAuditJavaObject.setModifierName(""); + } + + AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, Action); + } + + // private ServiceReqDetails certifyService() throws Exception + // { + // ServiceReqDetails certifyService = + // LifecycleRestUtils.certifyService(serviceDetails, + // serviceDetails.getVersion(), sdncAdminDetails); + //// version = certifyService.getVersion(); + // + // return certifyService; + // } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java new file mode 100644 index 0000000000..8e95a6d02c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java @@ -0,0 +1,1304 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.json.JSONObject; +import org.junit.Rule; +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.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.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.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +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.expected.ExpectedResourceAuditJavaObject; +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; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class CreateServiceMetadataApiTest extends ComponentBaseTest { + private static Logger logger = LoggerFactory.getLogger(CreateServiceMetadataApiTest.class.getName()); + + String serviceBaseVersion = "0.1"; + + @Rule + public static TestName name = new TestName(); + + public CreateServiceMetadataApiTest() { + super(name, CreateServiceMetadataApiTest.class.getName()); + } + + @Test + public void createDefaultService() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // String creator = + // ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId(); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", 201, restResponse.getErrorCode().intValue()); + + // validate create service response vs actual + + Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails, + (LifecycleStateEnum) null); + + // validate get service response vs actual + restResponse = ServiceRestUtils.getService(serviceDetails, sdncUserDetails); + service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails, + (LifecycleStateEnum) null); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createDefaultServiceUserDesigner() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", 201, restResponse.getErrorCode().intValue()); + + // validate create service response vs actual + + Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails, + (LifecycleStateEnum) null); + + // validate get service response vs actual + restResponse = ServiceRestUtils.getService(serviceDetails, sdncUserDetails); + service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceUserNotFound() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncUserDetails.setUserId("no1234"); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + restResponse.getResponse()); + + // validate audit + + sdncUserDetails.setFirstName(""); + sdncUserDetails.setLastName(""); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setModifierName(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceUserNotAllowed() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceEmptyName() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + String serviceName = ""; + serviceDetails.setName(serviceName); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_COMPONENT_NAME.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("Service"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_COMPONENT_NAME.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceEmptyCategory() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + String category = ""; + + serviceDetails.setCategories(null); + // serviceDetails.addCategory(category); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("Service"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceEmptyTag() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ArrayList tags = new ArrayList(); + tags.add(""); + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setTags(tags); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("Service", "tag"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceEmptyDescription() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + String description = ""; + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setDescription(description); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("Service"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceEmptyTags() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ArrayList tags = new ArrayList(); + tags.add(""); + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setTags(tags); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("Service", "tag"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceByPutHttpMethod() throws Exception { + + String method = "PUT"; + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + + RestResponse restResponse = ServiceRestUtils.createServiceByHttpMethod(serviceDetails, sdncUserDetails, method, + Urls.CREATE_SERVICE); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_ALLOWED.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + restResponse.getResponse()); + + // //validate audit + // + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // resourceUtils.constructFieldsForAuditValidation(serviceDetails, + // serviceBaseVersion, sdncUserDetails); + // + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + // + // String auditDesc = + // AuditValidationUtils.buildAuditDescription(errorInfo, variables); + // expectedResourceAuditJavaObject.setDesc(auditDesc); + // + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction); + + } + + @Test + public void createServiceByDeleteHttpMethod() throws Exception { + + String method = "DELETE"; + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + + RestResponse restResponse = ServiceRestUtils.createServiceByHttpMethod(serviceDetails, sdncUserDetails, method, + Urls.CREATE_SERVICE); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_ALLOWED.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables, + restResponse.getResponse()); + + // //validate audit + // + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // resourceUtils.constructFieldsForAuditValidation(serviceDetails, + // serviceBaseVersion, sdncUserDetails); + // + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setAction(auditAction); + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + // + // String auditDesc = + // AuditValidationUtils.buildAuditDescription(errorInfo, variables); + // expectedResourceAuditJavaObject.setDesc(auditDesc); + // + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction); + + } + + @Test + public void createServiceTagLengthExceedLimit() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + StringBuffer tagBuffer = new StringBuffer(); + for (int i = 0; i < 1025; i++) { + tagBuffer.append("a"); + } + ArrayList tags = new ArrayList(); + tags.add(tagBuffer.toString()); + serviceDetails.setTags(tags); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("50"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), variables, + restResponse.getResponse()); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("50")); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + /* + * ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + * ServiceValidationUtils.constructFieldsForAuditValidation( + * serviceDetails, serviceBaseVersion, sdncUserDetails); + * + * String auditAction="Create"; + * expectedResourceAuditJavaObject.setAction(auditAction); + * expectedResourceAuditJavaObject.setPrevState(""); + * expectedResourceAuditJavaObject.setPrevVersion(""); + * expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum. + * NOT_CERTIFIED_CHECKOUT).toString()); + * expectedResourceAuditJavaObject.setStatus(errorInfo.getCode(). + * toString()); expectedResourceAuditJavaObject.setDesc(auditDesc); + * + * AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + * auditAction, null); + */ + + } + + @Test + public void createServiceAlreadyExistException() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // create service with the same name + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + + List variables = Arrays.asList("Service", serviceDetails.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), variables, + restResponse.getResponse()); + + // validate audit + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void createServiceWrongContactId() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setContactId("123as"); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_CONTACT.name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + } + + @Test + public void createServiceProjectName() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setProjectCode("12345"); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + Integer expectedCode = 201; + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", expectedCode, restResponse.getErrorCode()); + Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + + assertEquals("12345", service.getProjectCode()); + } + + @Test + public void createAndGetByNameAndVersion() throws Exception { + + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // create + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + assertEquals("Check response code after create service", 201, restResponse.getErrorCode().intValue()); + + // get + restResponse = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, serviceDetails.getName(), + serviceBaseVersion); + assertEquals("Check response code after get service", 200, restResponse.getErrorCode().intValue()); + + Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + String uniqueId = service.getUniqueId(); + serviceDetails.setUniqueId(uniqueId); + ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails, + (LifecycleStateEnum) null); + } + + //// US553874 + + @JsonIgnore + @Test + public void createServiceIsVNF_isFalse() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after updating Interface Artifact", 201, + restResponse.getErrorCode().intValue()); + + // get service and verify that service created with isVNF defined in + // serviceDetails + RestResponse serviceByNameAndVersion = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + serviceDetails.getName(), serviceBaseVersion); + Service serviceObject = ResponseParser + .convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, serviceObject, sdncUserDetails, + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @JsonIgnore + @Test + public void createServiceIsVNF_isTrue() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after updating Interface Artifact", 201, + restResponse.getErrorCode().intValue()); + + // get service and verify that service created with isVNF defined in + // serviceDetails + RestResponse serviceByNameAndVersion = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + serviceDetails.getName(), serviceBaseVersion); + Service serviceObject = ResponseParser + .convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, serviceObject, sdncUserDetails, + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + // validate audit + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @JsonIgnore + @Test(enabled = false) + public void createServiceIsVNF_isNull() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // clean audit DB before service creation + DbUtils.cleanAllAudits(); + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + assertNotNull("check response object is not null after create service", restResponse); + assertEquals("Check response code after updating Interface Artifact", 400, + restResponse.getErrorCode().intValue()); + List variables = Arrays.asList("VNF Service Indicator"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), variables, + restResponse.getResponse()); + + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("VNF Service Indicator")); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + } + + @JsonIgnore + @Test(enabled = false) + public void createServiceEmptyIsVNF() throws Exception { + + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + DbUtils.cleanAllAudits(); + + // send create service toward BE + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", restResponse.getErrorCode(), + restResponse.getErrorCode()); + + // validate create service response vs actual + List variables = Arrays.asList("VNF Service Indicator"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), variables, + restResponse.getResponse()); + + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails); + + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + private RestResponse createServiceWithMissingAttribute(String serviceDetails, User sdncModifierDetails) + throws Exception { + + Config config = Utils.getConfig(); + + Map headersMap = ServiceRestUtils.prepareHeadersMap(sdncModifierDetails, false); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort()); + // TODO: ADD AUTHENTICATION IN REQUEST + logger.debug(url); + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceDetails); + logger.debug("Service headers: {}", headersMap); + RestResponse sendCreateUserRequest = http.httpSendPost(url, serviceDetails, headersMap); + + return sendCreateUserRequest; + + } + + @JsonIgnore + @Test(enabled = false) + public void createServiceVersion_isVNFDoesNotExistInJson() throws Exception { + + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // clean audit DB before updating service + DbUtils.cleanAllAudits(); + + // remove isVNF from json sent to create service + JSONObject jObject = new JSONObject(serviceDetails); + jObject.remove("VNF"); + + // send create service toward BE + RestResponse restResponse = createServiceWithMissingAttribute(jObject.toString(), sdncUserDetails); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after updating Interface Artifact", 400, + restResponse.getErrorCode().intValue()); + List variables = new ArrayList(); + variables.add("VNF Service Indicator"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), variables, + restResponse.getResponse()); + + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils + .constructFieldsForAuditValidation(serviceDetails, "0.1", sdncUserDetails); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("VNF Service Indicator")); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false); + + } + + @Test + public void checkInvariantUuidIsImmutable() throws Exception { + // choose the user to create service + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + Component resourceDetailsVFCcomp = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.ADMIN, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.ADMIN, + true, true); + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.ADMIN, + LifeCycleStatesEnum.CERTIFY, true); + + // fill new service details + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!"; + serviceDetails.setInvariantUUID(invariantUuidDefinedByUser); + + // create service + RestResponse restResponseCreation = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + BaseRestUtils.checkStatusCode(restResponseCreation, "create request failed", false, 201); + Service service = ResponseParser.convertServiceResponseToJavaObject(restResponseCreation.getResponse()); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, service, + UserRoleEnum.ADMIN, true); + + String invariantUUIDcreation = service.getInvariantUUID(); + + // validate get service response vs actual + RestResponse restResponseGetting = ServiceRestUtils.getService(serviceDetails, sdncUserDetails); + BaseRestUtils.checkSuccess(restResponseGetting); + service = ResponseParser.convertServiceResponseToJavaObject(restResponseGetting.getResponse()); + String invariantUUIDgetting = service.getInvariantUUID(); + + assertEquals(invariantUUIDcreation, invariantUUIDgetting); + + // Update service with new invariant UUID + RestResponse restResponseUpdate = ServiceRestUtils.updateService(serviceDetails, sdncUserDetails); + BaseRestUtils.checkSuccess(restResponseUpdate); + Service updatedService = ResponseParser.convertServiceResponseToJavaObject(restResponseUpdate.getResponse()); + String invariantUUIDupdating = updatedService.getInvariantUUID(); + assertEquals(invariantUUIDcreation, invariantUUIDupdating); + + // Do checkin + RestResponse restResponseCheckin = LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); + BaseRestUtils.checkSuccess(restResponseCheckin); + Service checkinService = ResponseParser.convertServiceResponseToJavaObject(restResponseCheckin.getResponse()); + String invariantUUIDcheckin = checkinService.getInvariantUUID(); + String version = checkinService.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcheckin); + assertEquals(version, "0.1"); + + // Do checkout + RestResponse restResponseCheckout = LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + BaseRestUtils.checkSuccess(restResponseCheckout); + Service checkoutService = ResponseParser.convertServiceResponseToJavaObject(restResponseCheckout.getResponse()); + String invariantUUIDcheckout = checkoutService.getInvariantUUID(); + version = checkoutService.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcheckout); + assertEquals(version, "0.2"); + + // do certification request + RestResponse restResponseCertificationRequest = LifecycleRestUtils.changeServiceState(serviceDetails, + sdncUserDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + BaseRestUtils.checkSuccess(restResponseCertificationRequest); + Service certificationRequestService = ResponseParser + .convertServiceResponseToJavaObject(restResponseCertificationRequest.getResponse()); + String invariantUUIDcertificationRequest = certificationRequestService.getInvariantUUID(); + version = certificationRequestService.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcertificationRequest); + assertEquals(version, "0.2"); + + // start certification + RestResponse restResponseStartCertification = LifecycleRestUtils.changeServiceState(serviceDetails, + sdncUserDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); + BaseRestUtils.checkSuccess(restResponseStartCertification); + Service startCertificationRequestService = ResponseParser + .convertServiceResponseToJavaObject(restResponseStartCertification.getResponse()); + String invariantUUIDStartCertification = startCertificationRequestService.getInvariantUUID(); + version = startCertificationRequestService.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDStartCertification); + assertEquals(version, "0.2"); + + // certify + RestResponse restResponseCertify = LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails, + serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY); + BaseRestUtils.checkSuccess(restResponseCertify); + Service certifyService = ResponseParser.convertServiceResponseToJavaObject(restResponseCertify.getResponse()); + String invariantUUIDcertify = certifyService.getInvariantUUID(); + version = certifyService.getVersion(); + assertEquals(invariantUUIDcreation, invariantUUIDcertify); + assertEquals(version, "1.0"); + + } + + // US672129 Benny + private void getServiceValidateInvariantUuid(String serviceUniqueId, String invariantUUIDcreation) + throws Exception { + RestResponse getService = ServiceRestUtils.getService(serviceUniqueId, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getService.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(getService)); + } + + @Test // invariantUUID generated when the component is created and never + // changed + public void serviceInvariantUuid() throws Exception { + User designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + User testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + User pmUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + Component resourceDetailsVFCcomp = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + true, true); + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + // create service + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setInvariantUUID("123456"); + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, designerUser); + assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED, + restResponse.getErrorCode().intValue()); + Service service = ResponseParser.parseToObjectUsingMapper(restResponse.getResponse(), Service.class); + // invariantUUID generated when the component is created and never + // changed + String invariantUUIDcreation = ResponseParser.getInvariantUuid(restResponse); + // Add VF instance to service + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, service, + UserRoleEnum.DESIGNER, true); + // get resource and verify InvariantUuid is not changed + getServiceValidateInvariantUuid(service.getUniqueId(), invariantUUIDcreation); + + // Update service with new invariant UUID + restResponse = ServiceRestUtils.updateService(serviceDetails, designerUser); + assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_SUCCESS, + restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // Checkin + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // Checkout + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // certification request + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // start certification + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // certify + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, LifeCycleStatesEnum.CERTIFY); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // update resource + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + serviceDetails.setDescription("updatedDescription"); + restResponse = ServiceRestUtils.updateService(serviceDetails, designerUser); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // certification request + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // Checkout + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // certification request + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // start certification + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // cancel certification + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, + LifeCycleStatesEnum.CANCELCERTIFICATION); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // start certification + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // failure + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, + LifeCycleStatesEnum.FAILCERTIFICATION); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // Checkout + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, + LifeCycleStatesEnum.CHECKOUT); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // Checkin + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN); + assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue()); + assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse)); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + // create instance + ProductReqDetails productDetails = ElementFactory.getDefaultProduct(); + RestResponse createProductResponse = ProductRestUtils.createProduct(productDetails, pmUser); + assertEquals(BaseRestUtils.STATUS_CODE_CREATED, createProductResponse.getErrorCode().intValue()); + ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(serviceDetails); + RestResponse createServiceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + serviceInstanceReqDetails, pmUser, productDetails.getUniqueId(), ComponentTypeEnum.PRODUCT); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED, + createServiceInstanceResponse.getErrorCode().intValue()); + getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java new file mode 100644 index 0000000000..3460cd6e04 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java @@ -0,0 +1,351 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.cassandra.transport.Event.SchemaChange.Target; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.ErrorInfo; +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; +import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest; +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.LifecycleRestUtils; +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.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class GetAllServiceVersions extends ComponentBaseTest { + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + protected User sdncDesignerDetails; + protected User sdncDesignerDetails2; + protected User sdncAdminDetails; + protected User sdncGovernorDeatails; + protected User sdncTesterDetails; + protected User sdncOpsDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails; + protected Component resourceDetailsVFCcomp; + protected Service serviceServ; + + @Rule + public static TestName name = new TestName(); + + public GetAllServiceVersions() { + super(name, GetAllServiceVersions.class.getName()); + ; + } + + @BeforeMethod + public void setUp() throws Exception { + + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + resourceDetailsVFCcomp = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + true, true); + + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ, + UserRoleEnum.DESIGNER, true); + + serviceDetails = new ServiceReqDetails(serviceServ); + + } + + @Test + public void GetAllServiceVersions_Version05() throws Exception { + + Map origVersionsMap = new HashMap(); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + } + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + + } + + @Test + public void GetAllServiceVersions_Version01() throws Exception { + + Map origVersionsMap = new HashMap(); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_Version15() throws Exception { + // addMandatoryArtifactsToService(); + Map origVersionsMap = new HashMap(); + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + } + + RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + // serviceServ.setUniqueId(serviceDetails.getUniqueId()); + // RestResponse changeServiceState = + // AtomicOperationUtils.changeComponentState(serviceServ, + // UserRoleEnum.ADMIN, LifeCycleStatesEnum.CERTIFY, false).getRight(); + + assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(), + changeServiceState.getErrorCode() == 200); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + for (int x = 0; x < 5; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + } + + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_Version25() throws Exception { + // addMandatoryArtifactsToService(); + Map origVersionsMap = new HashMap(); + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + } + + // getting to version 1.0 + RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(), + changeServiceState.getErrorCode() == 200); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + // getting to version 1.5 + for (int x = 0; x < 5; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + } + + // getting to version 2.0 + changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(), + changeServiceState.getErrorCode() == 200); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + // getting to version 2.5 + for (int x = 0; x < 5; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + } + + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_ReadyForCertification_version05() throws Exception { + // addMandatoryArtifactsToService(); + Map origVersionsMap = new HashMap(); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + } + + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_CertifactionInProgress_version05() throws Exception { + // addMandatoryArtifactsToService(); + Map origVersionsMap = new HashMap(); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + } + + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.STARTCERTIFICATION); + + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_Certified_version10() throws Exception { + // addMandatoryArtifactsToService(); + Map origVersionsMap = new HashMap(); + // get to version 0.5 + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + + } + + // get version 1.0 + RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(), + changeServiceState.getErrorCode() == 200); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_Certified_version20() throws Exception { + // addMandatoryArtifactsToService(); + Map origVersionsMap = new HashMap(); + // get to version 0.5 + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + } + + // get version 1.0 + RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(), + changeServiceState.getErrorCode() == 200); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + // get version 1.5 + for (int x = 0; x < 4; x++) { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + } + + // get version 2.0 + changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(), + changeServiceState.getErrorCode() == 200); + origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId()); + + // validate get response + RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails); + Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse()); + Map getVersionsMap = res.getAllVersions(); + assertTrue(origVersionsMap.equals(getVersionsMap)); + } + + @Test + public void GetAllServiceVersions_ServiceNotFound() throws Exception { + + RestResponse serviceGetResponse = ServiceRestUtils.getService("123456789", sdncAdminDetails); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); + assertEquals("Check response code after get service without cache", errorInfo.getCode(), + serviceGetResponse.getErrorCode()); + + List variables = Arrays.asList("123456789"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, + serviceGetResponse.getResponse()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java new file mode 100644 index 0000000000..5642ce4745 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java @@ -0,0 +1,371 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.http.HttpStatus; +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.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.ComponentInstanceReqDetails; +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; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +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.general.FileUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +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.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import fj.data.Either; + +public class GetComponentAuditApiTest extends ComponentBaseTest { + + public static final String SERVICES_API = "services"; + public static final String RESOURCES_API = "resources"; + + protected User sdncAdminUser; + protected User sdncDesignerUser; + protected User sdncTesterUser; + + @Rule + public static TestName name = new TestName(); + + public GetComponentAuditApiTest() { + super(name, GetComponentAuditApiTest.class.getName()); + } + + // in case tests fail, run this method as test to create mapping in ES + public void updateElasticSearchMapping() throws IOException { + Either fileContentUTF8 = FileUtils + .getFileContentUTF8("src\\test\\resources\\CI\\other\\mapping.json"); + AssertJUnit.assertTrue(fileContentUTF8.isLeft()); + + final String ES_TEMPLATE_URL = "http://%s:%s/_template/audit_template"; + String url = String.format(ES_TEMPLATE_URL, config.getEsHost(), config.getEsPort()); + + RestResponse sendHttpPost = new HttpRequest().sendHttpPost(url, fileContentUTF8.left().value(), null); + AssertJUnit.assertTrue(sendHttpPost.getErrorCode() == HttpStatus.SC_OK); + } + + @BeforeMethod + public void init() { + sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncDesignerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncTesterUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + ; + + } + + @Test + public void testServiceAuditCertifiedVersion() throws Exception { + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + Wrapper versionZeroOneIDWrapper = new Wrapper(), + versionZeroTwoIDWrapper = new Wrapper(); + + createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, true); + // First Certification + + LifecycleRestUtils.certifyService(serviceDetails); + // LCSbaseTest.certifyService(serviceDetails); + AssertJUnit.assertTrue(serviceDetails.getVersion().equals("1.0")); + + // Second Certification + increaseServiceVersion(serviceDetails, "1.1"); + increaseServiceVersion(serviceDetails, "1.2"); + increaseServiceVersion(serviceDetails, "1.3"); + increaseServiceVersion(serviceDetails, "1.4"); + LifecycleRestUtils.certifyService(serviceDetails); + AssertJUnit.assertTrue(serviceDetails.getVersion().equals("2.0")); + String certifiedId = serviceDetails.getUniqueId(); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKOUT); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKIN); + + JsonElement element = getAuditJson(SERVICES_API, certifiedId); + // audits kept: 5*check ins + 4*check outs + 2*artifact payload + // updates(tosca) + certification request + certification start + + // certification success + // + 3 A&AI(ArtifactDelete, ArtifactUpload, ArtifactUpdate) + List actions = new ArrayList<>(); + JsonArray jsonArray = element.getAsJsonArray(); + for( int i =0 ; i < jsonArray.size(); i++){ + actions.add(jsonArray.get(i).getAsJsonObject().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName()).getAsString()); + } + long checkinCount = actions.stream().filter( e -> e.equals(AuditingActionEnum.CHECKIN_RESOURCE.getName())).count(); + assertTrue(checkinCount == 5); + + long checkOutCount = actions.stream().filter( e -> e.equals(AuditingActionEnum.CHECKOUT_RESOURCE.getName())).count(); + assertTrue(checkOutCount == 4); + + long certificationRequestCount = actions.stream().filter( e -> e.equals(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName())).count(); + assertTrue(certificationRequestCount == 1); + + long certificationStartCount = actions.stream().filter( e -> e.equals(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName())).count(); + assertTrue(certificationStartCount == 1); + + long certificationSuccessCount = actions.stream().filter( e -> e.equals(AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE.getName())).count(); + assertTrue(certificationSuccessCount == 1); + + + } + + protected void certifyResource(ResourceReqDetails defaultResource) throws IOException { + RestResponse response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + response = LifecycleRestUtils.changeResourceState(defaultResource, sdncTesterUser, + LifeCycleStatesEnum.STARTCERTIFICATION); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + response = LifecycleRestUtils.changeResourceState(defaultResource, sdncTesterUser, LifeCycleStatesEnum.CERTIFY); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + } + + protected JsonElement getAuditJson(String componentType, String componentId) throws IOException { + Map headers = new HashMap() { + { + put(Constants.USER_ID_HEADER, UserRoleEnum.ADMIN.getUserId()); + } + }; + String url = String.format(Urls.GET_COMPONENT_AUDIT_RECORDS, config.getCatalogBeHost(), + config.getCatalogBePort(), componentType, componentId); + + RestResponse httpSendGet = new HttpRequest().httpSendGet(url, headers); + AssertJUnit.assertTrue(httpSendGet.getErrorCode() == HttpStatus.SC_OK); + JsonElement element = ResponseParser.parseToObject(httpSendGet.getResponse(), JsonElement.class); + AssertJUnit.assertTrue(element.isJsonArray()); + return element; + } + + protected void createBasicServiceForAudit(Wrapper versionZeroOneIDWrapper, + Wrapper versionZeroTwoIDWrapper, ServiceReqDetails serviceDetails, Boolean withResInst) + throws Exception { + + User designerUser = sdncDesignerUser; + + RestResponse response = ServiceRestUtils.createService(serviceDetails, designerUser); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_CREATED); + versionZeroOneIDWrapper.setInnerElement(serviceDetails.getUniqueId()); + + if (withResInst) { + Resource resourceObj = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceObj, UserRoleEnum.DESIGNER, true, + true); + AtomicOperationUtils.changeComponentState(resourceObj, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, + true); + ResourceReqDetails resource = new ResourceReqDetails(resourceObj); + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + resourceInstanceReqDetails.setComponentUid(resource.getUniqueId()); + ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerUser, + serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + + // ServiceUtils.createCertResourceWithDeploymentArt(serviceDetails, + // "myResource"); + } + + response = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + AssertJUnit.assertTrue(serviceDetails.getVersion().equals("0.1")); + + response = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKOUT); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + // ServiceUtils.addServiceDeploymentArtifact(serviceDetails.getUniqueId(), + // designerUser); + versionZeroTwoIDWrapper.setInnerElement(serviceDetails.getUniqueId()); + AssertJUnit.assertTrue(serviceDetails.getVersion().equals("0.2")); + response = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + + increaseServiceVersion(serviceDetails, "0.3"); + + increaseServiceVersion(serviceDetails, "0.4"); + + increaseServiceVersion(serviceDetails, "0.5"); + + } + + protected void increaseServiceVersion(ServiceReqDetails serviceDetails, String excpectedVersion) throws Exception { + RestResponse response = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, + LifeCycleStatesEnum.CHECKOUT); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + AssertJUnit.assertTrue(serviceDetails.getVersion().equals(excpectedVersion)); + response = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + } + + protected void createBasicResourceForAudit(Wrapper versionOnePointTwoIDWrapper, + ResourceReqDetails defaultResource) throws Exception { + + RestResponse response = ResourceRestUtils.createResource(defaultResource, sdncDesignerUser); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_CREATED); + + // ArtifactDefinition artifactDef = new + // ArtifactUtils().constructDefaultArtifactInfo(); + // response = resourceUtils.add_artifact(defaultResource, + // sdncDesignerUser, defaultResource.getVersion(), artifactDef); + // assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerUser, + defaultResource.getUniqueId()); + AssertJUnit.assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, + LifeCycleStatesEnum.CHECKIN); + + increaseResourceVersion(defaultResource, "0.2"); + + increaseResourceVersion(defaultResource, "0.3"); + + increaseResourceVersion(defaultResource, "0.4"); + + increaseResourceVersion(defaultResource, "0.5"); + + certifyResource(defaultResource); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + AssertJUnit.assertTrue(defaultResource.getVersion().equals("1.0")); + + increaseResourceVersion(defaultResource, "1.1"); + + increaseResourceVersion(defaultResource, "1.2"); + versionOnePointTwoIDWrapper.setInnerElement(defaultResource.getUniqueId()); + + increaseResourceVersion(defaultResource, "1.3"); + + increaseResourceVersion(defaultResource, "1.4"); + + } + + protected void increaseResourceVersion(ResourceReqDetails defaultResource, String expectedVersion) + throws IOException { + RestResponse response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, + LifeCycleStatesEnum.CHECKOUT); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + AssertJUnit.assertTrue(defaultResource.getVersion().equals(expectedVersion)); + response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, + LifeCycleStatesEnum.CHECKIN); + AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + } + + @Test + public void testServiceAuditLastUncertifiedVersion() throws Exception { + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + Wrapper versionZeroOneIDWrapper = new Wrapper(), + versionZeroTwoIDWrapper = new Wrapper(); + + createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, false); + + JsonElement element = getAuditJson(SERVICES_API, versionZeroTwoIDWrapper.getInnerElement()); + + assertTrue(element.getAsJsonArray().size() == 3); + + } + + @Test + public void testServiceAuditFirstUncertifiedVersion() throws Exception { + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + Wrapper versionZeroOneIDWrapper = new Wrapper(), + versionZeroTwoIDWrapper = new Wrapper(); + + createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, false); + + JsonElement element = getAuditJson(SERVICES_API, versionZeroOneIDWrapper.getInnerElement()); + + assertTrue(element.getAsJsonArray().size() == 3); + + } + + @Test + public void testResourceAuditUncertifiedVersion() throws Exception { + + ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(); + Wrapper versionOnePointTwoIDWrapper = new Wrapper(); + + createBasicResourceForAudit(versionOnePointTwoIDWrapper, defaultResource); + + JsonElement element = getAuditJson(RESOURCES_API, versionOnePointTwoIDWrapper.getInnerElement()); + + assertTrue(element.getAsJsonArray().size() == 3); + + } + + @Test + public void testResourceAuditCertifiedVersion() throws Exception { + + ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(); + Wrapper versionOnePointTwoIDWrapper = new Wrapper(); + + createBasicResourceForAudit(versionOnePointTwoIDWrapper, defaultResource); + + certifyResource(defaultResource); + assertTrue(defaultResource.getVersion().equals("2.0")); + String certifiedId = defaultResource.getUniqueId(); + + increaseResourceVersion(defaultResource, "2.1"); + + increaseResourceVersion(defaultResource, "2.2"); + + JsonElement element = getAuditJson(RESOURCES_API, certifiedId); + + assertTrue(element.getAsJsonArray().size() == 13); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java new file mode 100644 index 0000000000..55ecf694ee --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java @@ -0,0 +1,685 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION; +import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +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.datatypes.enums.ResourceTypeEnum; +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.ci.tests.api.ComponentInstanceBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +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.NormativeTypesEnum; +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.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.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.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + +public class GetServiceLatestVersionTest extends ComponentInstanceBaseTest { + + protected ArtifactReqDetails heatArtifactDetails; + + @Rule + public static TestName name = new TestName(); + + public GetServiceLatestVersionTest() { + super(name, GetServiceLatestVersionTest.class.getName()); + } + + @BeforeMethod + public void before() throws Exception { + initMembers(); + createAtomicResource(resourceDetailsVFC_01); + changeResourceStateToCertified(resourceDetailsVFC_01); + createAtomicResource(resourceDetailsCP_01); + changeResourceStateToCertified(resourceDetailsCP_01); + createAtomicResource(resourceDetailsVL_01); + changeResourceStateToCertified(resourceDetailsVL_01); + createVF(resourceDetailsVF_01); + certifyVf(resourceDetailsVF_01); + createService(serviceDetails_01); + createService(serviceDetails_02); + createService(serviceDetails_03); + createProduct(productDetails_01); + createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); // create + // certified + // VF + // instance + // in + // service + /* + * RestResponse restResponse = + * LifecycleRestUtils.changeServiceState(serviceDetails_01, + * sdncDesignerDetails, LifeCycleStates.CHECKIN); + * ResourceRestUtils.checkSuccess(restResponse); + */ + } + + public void initMembers() throws Exception { + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + sdncPsDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1); + sdncPmDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1); + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + resourceDetailsVFC_01 = ElementFactory.getDefaultResourceByType("VFC100", NormativeTypesEnum.COMPUTE, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VFC.toString()); // resourceType = VFC + resourceDetailsVF_01 = ElementFactory.getDefaultResourceByType("VF100", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("CP100", NormativeTypesEnum.PORT, + ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.CP.toString()); + resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("VL100", NormativeTypesEnum.NETWORK, + ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VL.toString()); + serviceDetails_01 = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY, + sdncDesignerDetails.getUserId()); + serviceDetails_02 = ElementFactory.getDefaultService("newtestservice2", ServiceCategoriesEnum.MOBILITY, + sdncDesignerDetails.getUserId()); + serviceDetails_03 = ElementFactory.getDefaultService("newtestservice3", ServiceCategoriesEnum.MOBILITY, + sdncDesignerDetails.getUserId()); + productDetails_01 = ElementFactory.getDefaultProduct("product01"); + } + + @Test + public void getServicesLatestVersionServiceInCheckOutState() throws Exception { + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncPsDetails1); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertNull("No Service returned, one service in checkout state 0.1", servcieFromList); + } + + @Test + public void getServicesLatestVersionServiceInCheckInState() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncPsDetails1); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.1")); + } + + @Test + public void getServicesLatestVersionByPm() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncPmDetails1); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.1")); + } + + @Test + public void getServicesLatestVersionByAdmin() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncAdminDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.1")); + } + + @Test + public void getServicesLatestVersionService02CheckOutState() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + String serviceUniqueID = ResponseParser.getUniqueIdFromResponse(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueID); + assertTrue(servcieFromList.getVersion().equals("0.1")); + servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertNull(servcieFromList); + } + + @Test + public void getServicesLatestVersionService02CheckInState() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.2")); + } + + @Test + public void getServicesLatestVersionServiceWaitingForCertification() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.2")); + } + + @Test + public void getServicesLatestVersionServiceCertificationInProgress() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.2")); + } + + @Test + public void getServicesLatestVersionServiceCertificationFail() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.FAILCERTIFICATION); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.2")); + } + + @Test + public void getServicesLatestVersionServiceCertifed() throws Exception { + certifyService(serviceDetails_01); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("1.0")); + } + + @Test + public void getLatestVersionServiceHasSeveralCertifedVersion_01() throws Exception { + RestResponse certifyServiceResponse; + String serviceUniqueIdFromResponse = null; + int numberOfCertifiedService = 3; + for (int i = 0; i < numberOfCertifiedService; i++) { + certifyServiceResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(certifyServiceResponse); + if (i == (numberOfCertifiedService - 1)) { + serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(certifyServiceResponse); + } + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + } + // We have service with following versions : 1.0, 2.0 ,3.0 and + // 3.1(checkedOut) + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueIdFromResponse); + assertTrue(servcieFromList.getVersion().equals("3.0")); + } + + @Test + public void getLatestVersionServiceHasSeveralCertifedVersions02() throws Exception { + RestResponse certifyServiceResponse; + certifyServiceResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(certifyServiceResponse); + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + certifyServiceResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(certifyServiceResponse); + // We have service with following versions : 1.0, 2.0 + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("2.0")); + } + + @Test + public void getLatestVersionServiceCertifedWasCheckedOutAndCheckedin() throws Exception { + RestResponse certifyServiceResponse; + int numberOfCertifiedService = 3; + for (int i = 0; i < numberOfCertifiedService; i++) { + certifyServiceResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(certifyServiceResponse); + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + } + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + // We have service with following versions : 1.0, 2.0 and 2.1(checkedIn) + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("3.1")); + } + + @Test + public void getLatestVersionServiceCheckOutCertifedService() throws Exception { + RestResponse restResponse; + String serviceUniqueIdFromResponse = null; + RestResponse certifyServiceResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(certifyServiceResponse); + for (int i = 0; i < 11; i++) { + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + if (i == (10)) { + serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse); + } + } + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + // We have service with following versions : 1.0 and 1.11(Check-out) + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueIdFromResponse); + assertTrue(servcieFromList.getVersion().equals("1.11")); + } + + @Test + public void getLatestVersionServiceCheckOutCheckInCertifedService() throws Exception { + RestResponse restResponse; + String serviceUniqueIdFromResponse = null; + RestResponse certifyServiceResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(certifyServiceResponse); + for (int i = 0; i < 12; i++) { + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + if (i == (11)) { + serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse); + } + } + // We have service with following versions : 1.0 and 1.11(Check-out) + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueIdFromResponse); + assertTrue(servcieFromList.getVersion().equals("1.12")); + } + + @Test + public void getLatestVersionServiceCertifedCheckedOutAndInWaitingForCertificationState() throws Exception { + certifyService(serviceDetails_01); // 1.0 + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ServiceRestUtils.checkSuccess(restResponse); + // We have service with following versions : 1.0 and 1.1(Waiting For + // Certification) + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("1.1")); + } + + @Test + public void getLatestVersionServiceCertifedCheckedOutAndInCertificationInProgressState() throws Exception { + certifyService(serviceDetails_01); // 1.0 + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + ServiceRestUtils.checkSuccess(restResponse); + // We have service with following versions : 1.0 and 1.1(Certification + // In Progress) + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("1.1")); + } + + // DE190818 + @Test(enabled = false) + public void getLatestVersionByNonAsdcUser() throws Exception { + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + nonAsdcUser.setUserId("gg750g"); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(nonAsdcUser); + assertTrue(getServicesLatestVersion.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + getServicesLatestVersion.getResponse()); + } + + // DE190818 + @Test(enabled = false) + public void getLatestVersionUserIdIsEmpty() throws Exception { + User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + nonAsdcUser.setUserId(""); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(nonAsdcUser); + assertTrue(getServicesLatestVersion.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), + getServicesLatestVersion.getResponse()); + } + + @Test + public void getServicesLatestVersionByTester() throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncTesterDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 1); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.1")); + } + + @Test + public void getLatestVersionSeveralServicesInDifferentVersion() throws Exception { + RestResponse restResponse = certifyService(serviceDetails_01); // 1.0 + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = certifyService(serviceDetails_01); + ServiceRestUtils.checkSuccess(restResponse); + String service1_UniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); // serviceDetails_01 + // version is 2.1 + // (check-out) + + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); // serviceDetails_02 + // version 0.2 + // (Check-in) + + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + String service3_UniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); // serviceDetails_03 + // version 0.2 + // (Check-out) + + RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails); + ServiceRestUtils.checkSuccess(getServicesLatestVersion); + List serviceList = restResponseToResourceObjectList(getServicesLatestVersion); + assertTrue(serviceList.size() == 3); + Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, service1_UniqueIdFromResponse); + assertTrue(servcieFromList.getVersion().equals("2.0")); + servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_02.getUniqueId()); + assertTrue(servcieFromList.getVersion().equals("0.2")); + servcieFromList = getResourceObjectFromResourceListByUid(serviceList, service3_UniqueIdFromResponse); + assertTrue(servcieFromList.getVersion().equals("0.1")); + } + + /////////////////////////////////////////////////////////////// + private RestResponse certifyService(ServiceReqDetails serviceDetails) throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKOUT); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + ServiceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails, + LifeCycleStatesEnum.CERTIFY); + ServiceRestUtils.checkSuccess(restResponse); + return restResponse; + } + + protected List restResponseToResourceObjectList(RestResponse restResponse) { + JsonElement jelement = new JsonParser().parse(restResponse.getResponse()); + JsonArray jsonArray = jelement.getAsJsonArray(); + List restResponseArray = new ArrayList<>(); + Service service = null; + for (int i = 0; i < jsonArray.size(); i++) { + String serviceString = (String) jsonArray.get(i).toString(); + service = ResponseParser.convertServiceResponseToJavaObject(serviceString); + restResponseArray.add(service); + } + return restResponseArray; + } + + protected Service getResourceObjectFromResourceListByUid(List serviceList, String uid) { + if (serviceList != null && serviceList.size() > 0) { + for (Service service : serviceList) { + if (service.getUniqueId().equals(uid)) + return service; + } + } else + return null; + return null; + } + + private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception { + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponse; + if (restResponse.getErrorCode() == 200) { + restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails, + LifeCycleStatesEnum.CERTIFY); + if (restResponse.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponse); + resourceDetails.setVersion(newVersion); + resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId()); + resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(), + "uniqueId"); + resourceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponse; + } + + // private void certifyVf(ResourceReqDetails resource) throws Exception { + // RestResponse createAtomicResourceInstance = + // createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_01, + // sdncDesignerDetails); + // ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + // createAtomicResourceInstance = + // createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01, + // sdncDesignerDetails); + // ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + // createAtomicResourceInstance = + // createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01, + // sdncDesignerDetails); + // ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + // //createVFInstanceDuringSetup(service, resource, sdncDesignerDetails); + // RestResponse response = + // ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, + // sdncDesignerDetails, resource.getUniqueId()); + // ResourceRestUtils.checkSuccess(response); + // RestResponse changeResourceStateToCertified = + // changeResourceStateToCertified(resource); + // ResourceRestUtils.checkSuccess(changeResourceStateToCertified); + // } + + private void certifyVf(ResourceReqDetails resource) throws Exception { + RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String vlCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + // Fixing Vl/Cp req/cap + ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE; + User user = sdncDesignerDetails; + fulfillCpRequirement(resource, cpCompInstId, computeCompInstId, computeCompInstId, user, containerCompType); + consumeVlCapability(resource, cpCompInstId, vlCompInstId, cpCompInstId, user, containerCompType); + + RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, + sdncDesignerDetails, resource.getUniqueId()); + ResourceRestUtils.checkSuccess(response); + RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource); + ResourceRestUtils.checkSuccess(changeResourceStateToCertified); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java new file mode 100644 index 0000000000..c21deafcd8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java @@ -0,0 +1,1191 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +import org.apache.http.client.ClientProtocolException; +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.datatypes.enums.ResourceTypeEnum; +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.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +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.NormativeTypesEnum; +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.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.general.ImportUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils; +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.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class ReqCapOccurrencesTest extends ComponentInstanceBaseTest { + + private ImportReqDetails importReqDetails1; // atomic resource + private ImportReqDetails importReqDetails2; + private ImportReqDetails importReqDetails3; + private ImportReqDetails importReqDetails4; + private Resource resourceVFC1; + private Resource resourceVFC2; + private Resource resourceVFC3; + private Resource resourceVFC4; + private ResourceReqDetails resourceDetailsVF100; + private ResourceReqDetails resourceDetailsVF200; + private Resource resourceVF100; + private Resource resourceVF200; + protected String testResourcesPath; + + protected final String importYmlWithReq11 = "softwareComponentReq11.yml"; + protected final String importYmlWithReq12 = "softwareComponentReq12.yml"; + protected final String importYmlWithCap11 = "computeCap11.yml"; + protected final String importYmlWithCap1Unbounded = "computeCap1UNBOUNDED.yml"; + protected final String capabilitiesAndRequirementsType = "tosca.capabilities.Container"; + + public ReqCapOccurrencesTest() { + super(new TestName(), ReqCapOccurrencesTest.class.getSimpleName()); + } + + @BeforeMethod + public void before() throws Exception { + // Do not use call init() from ComponentInstanceBaseTest + expectedContainerCapabilities = new LinkedHashMap>(); + expectedContainerRequirements = new LinkedHashMap>(); + removedRequirements = new HashMap<>(); + expectedContInstReqCap = new HashMap<>(); + + RestResponse importResourceResponse; + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // import yml file location + String sourceDir = config.getResourceConfigDir(); + final String workDir = "importToscaResourceByCreateUrl"; + testResourcesPath = sourceDir + File.separator + workDir; + ///// Create atomic resources ///////////////////////// + // import VFC1 with Requirements : MIN=1 MAX=2 + ///// (tosca.capabilities.Container) + importReqDetails1 = ElementFactory.getDefaultImportResource("VFC1"); + importResourceResponse = importedResource(importReqDetails1, importYmlWithReq12); + // resourceVFC1 = + // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + RestResponse restResponse = LifecycleRestUtils.changeResourceState(importReqDetails1, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + resourceVFC1 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + // import VFC2 with Capabilities : MIN 1 MAX UNBOUNDED + // (tosca.capabilities.Container) + importReqDetails2 = ElementFactory.getDefaultImportResource("VFC2"); + importResourceResponse = importedResource(importReqDetails2, importYmlWithCap1Unbounded); + // resourceVFC2 = + // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + restResponse = LifecycleRestUtils.changeResourceState(importReqDetails2, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + resourceVFC2 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + // import VFC3 with Capabilities : MIN 1 MAX 1 + // (tosca.capabilities.Container) + importReqDetails3 = ElementFactory.getDefaultImportResource("VFC3"); + importResourceResponse = importedResource(importReqDetails3, importYmlWithCap11); + // resourceVFC3 = + // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + restResponse = LifecycleRestUtils.changeResourceState(importReqDetails3, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + resourceVFC3 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + // import VFC4 with Requirements : MIN 1 MAX 1 + // (tosca.capabilities.Container) + importReqDetails4 = ElementFactory.getDefaultImportResource("VFC4"); + importResourceResponse = importedResource(importReqDetails4, importYmlWithReq11); + // resourceVFC4 = + // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + restResponse = LifecycleRestUtils.changeResourceState(importReqDetails4, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + resourceVFC4 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + + // create VF100 + resourceDetailsVF100 = ElementFactory.getDefaultResourceByType("VF1000", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + RestResponse createResourceVF100 = ResourceRestUtils.createResource(resourceDetailsVF100, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceVF100); + // create VF200 + resourceDetailsVF200 = ElementFactory.getDefaultResourceByType("VF2000", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), + ResourceTypeEnum.VF.toString()); + RestResponse createResourceVF200 = ResourceRestUtils.createResource(resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createResourceVF200); + // Create Service + serviceDetails_01 = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY, + sdncDesignerDetails.getUserId()); + RestResponse createServiceRestResponse = ServiceRestUtils.createService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createServiceRestResponse); + + } + + // US628514 Capability/Requirement "Occurrences" attribute in CREATE/DELETE + // Relation APIs + // Container = SERVICE , Container instance = VF + @Test + public void capAndReqOccurrencesInServiceAndHisInstancesNoAssociation() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC21 (Cap MIN=1 MAX=UNBOUNDED) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "1"; + String containerMaxReq = "2"; + String containerMinCap = "1"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + } + + @Test + public void serviceInstanceAssociationReqMaxOccurrencesNotReached() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC2 (Cap MIN=1 MAX=UNBOUNDED) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VFs + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + } + + @Test + public void serviceInstanceAssociationReqMaxOccurrencesIsReached() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC4 (Req MIN=1 MAX=1) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails4, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC2 (Cap MIN=1 MAX=UNBOUNDED) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VFs + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "0"; + String containerMinCap = "0"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + } + + @Test + public void associateServiceInstanceWhenReqMaxOccurrencesAlreadyReached() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC4 (Req MIN=1 MAX=1) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails4, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC2 (Cap MIN=1 MAX=UNBOUNDED) to VF2.00 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String vf1Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name"); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String vf2Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name"); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VFs + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + // associate same instances again - when requirement Max Occurrences + // reached + associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails, + serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND, + associateInstances.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(vf1Name); + varibales.add(vf2Name); + varibales.add("host"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND.name(), varibales, + associateInstances.getResponse()); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "0"; + String containerMinCap = "0"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + } + + @Test + public void serviceInstanceAssociationCapMaxOccurrencesIsReached() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VFs + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + } + + @Test + public void associationServiceInstanceWhenCapMaxOccurrencesAlreadyReached() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + // RestResponse createVFInstResp = createVFInstance(serviceDetails_01, + // resourceDetailsVF100, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String vf1Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name"); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + // createVFInstResp = createVFInstance(serviceDetails_01, + // resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String vf2Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name"); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VFs + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + // associate same instances again - when requirement Max Occurrences + // reached + associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails, + serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND, + associateInstances.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(vf1Name); + varibales.add(vf2Name); + varibales.add("host"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(), + varibales, associateInstances.getResponse()); + } + + @Test + public void associationAndDisassociateServiceInstancesWhenReqMaxOccurrencesAlreadyReached() + throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC4 (Req MIN=1 MAX=1) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails4, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + sdncDesignerDetails); + // RestResponse createVFInstResp = createVFInstance(serviceDetails_01, + // resourceDetailsVF100, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + // createVFInstResp = createVFInstance(serviceDetails_01, + // resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VF Instances + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "0"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + // Disassociate 2 VF Instances + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, + dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF100.getUniqueId()).isEmpty()); + // get service and verify Occurrences in container and container + // instance requirements and Capabilities + getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + containerMinReq = "1"; + containerMaxReq = "1"; + containerMinCap = "1"; + containerMaxCap = "1"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + } + + @Test(enabled = false) + public void aaaa() throws Exception, Exception { + RestResponse getResourseRestResponse; + // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000 + ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceReq); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000 + ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF200); + assertNotNull(componentInstanceCap); + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF200.getUniqueId()); + resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Check-In both VFs + RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails, + LifeCycleStatesEnum.CHECKIN); + ResourceRestUtils.checkSuccess(restResponse); + // Create VF instances + // RestResponse createVFInstResp = + // createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100, + // sdncDesignerDetails); + RestResponse createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF100, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String vf1Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name"); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, + // resourceDetailsVF200, sdncDesignerDetails); + createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String vf2Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name"); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // associate 2 VFs + String capType = capabilitiesAndRequirementsType; + String reqName = "host"; + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, + capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId()); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + // get service + RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getServiceResponse); + Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq, + containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, + resourceVF200, resourceVF100); + // associate same instances again - when requirement Max Occurrences + // reached + associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails, + serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND, + associateInstances.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(vf1Name); + varibales.add(vf2Name); + varibales.add("host"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(), + varibales, associateInstances.getResponse()); + } + + ////////////////////////////////////////////////////////////////////////////////////////////////// + // US628514 Capability/Requirement "Occurrences" attribute in CREATE/DELETE + ////////////////////////////////////////////////////////////////////////////////////////////////// Relation + ////////////////////////////////////////////////////////////////////////////////////////////////// APIs + // Container = VF , Container instance = VFC + @Test + public void capAndReqOccurrencesInVfAndHisInstancesNoAssociation() throws Exception, Exception { + // Add VFC1 and VFC2 instances in VF + ComponentInstance createComponentInstance1 = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(createComponentInstance1); + ComponentInstance createComponentInstance2 = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(createComponentInstance2); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "1"; + String containerMaxReq = "2"; + String containerMinCap = "1"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC2, resourceVFC1); + } + + @Test + public void vfInstanceAssociationReqMaxOccurrencesNotReached() throws Exception, Exception { + // Add VFC1 (with Requirements: tosca.capabilities.Container, MIN=1 + // MAX=2) instance to VF + ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithReq); + // Add VFC2 (with Capabilities: tosca.capabilities.Container, MIN=1, + // MAX=UNBOUNDED ) instance to VF + ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithCap); + // associate Instances + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100); + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq, + componentInstanceWithCap, capReqDefBeforeAssociate); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF100.getUniqueId())); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC2, resourceVFC1); + + } + + @Test + public void vfInstanceAssociationReqMaxOccurrencesIsReached() throws Exception, Exception { + // Add VFC4 (with Requirements: tosca.capabilities.Container, MIN=1 + // MAX=1) instance to VF + ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails4, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithReq); + // Add VFC2 (with Capabilities: tosca.capabilities.Container, MIN=1, + // MAX=UNBOUNDED ) instance to VF + ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithCap); + // associate Instances + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100); + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq, + componentInstanceWithCap, capReqDefBeforeAssociate); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF100.getUniqueId())); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "0"; + String containerMinCap = "0"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC2, resourceVFC4); + } + + @Test + public void associateVfInstanceWhenReqMaxOccurrencesAlreadyReached() throws Exception, Exception { + // Add VFC4 (with Requirements: tosca.capabilities.Container, MIN=1 + // MAX=1) instance to VF + ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails4, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithReq); + // Add VFC2 (with Capabilities: tosca.capabilities.Container, MIN=1, + // MAX=UNBOUNDED ) instance to VF + ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails2, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithCap); + // associate Instances + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100); + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq, + componentInstanceWithCap, capReqDefBeforeAssociate); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF100.getUniqueId())); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "0"; + String containerMinCap = "0"; + String containerMaxCap = "UNBOUNDED"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC2, resourceVFC4); + // associate same instances again - when requirement Max Occurrences + // reached + associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails, + resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND, + associateInstances.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(componentInstanceWithReq.getName()); + varibales.add(componentInstanceWithCap.getName()); + varibales.add("host"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND.name(), varibales, + associateInstances.getResponse()); + + } + + @Test + public void vfInstanceAssociationCapMaxOccurrencesIsReached() throws Exception, Exception { + // Add VFC1 (with Requirements: tosca.capabilities.Container, MIN=1 + // MAX=2) instance to VF + ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithReq); + // Add VFC3 (with Capabilities: tosca.capabilities.Container, MIN=1 + // MAX=1 ) instance to VF + ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithCap); + // associate Instances + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100); + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq, + componentInstanceWithCap, capReqDefBeforeAssociate); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF100.getUniqueId())); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC3, resourceVFC1); + } + + @Test + public void associationVfInstanceWhenCapMaxOccurrencesAlreadyReached() throws Exception, Exception { + // Add VFC1 (with Requirements: tosca.capabilities.Container, MIN=1 + // MAX=2) instance to VF + ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails1, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithReq); + // Add VFC3 (with Capabilities: tosca.capabilities.Container, MIN=1 + // MAX=1 ) instance to VF + ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithCap); + // associate Instances + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100); + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq, + componentInstanceWithCap, capReqDefBeforeAssociate); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue()); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF100.getUniqueId())); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "1"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC3, resourceVFC1); + // associate same instances again - when requirement Max Occurrences + // reached + associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails, + resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND, + associateInstances.getErrorCode().intValue()); + ArrayList varibales = new ArrayList(); + varibales.add(componentInstanceWithReq.getName()); + varibales.add(componentInstanceWithCap.getName()); + varibales.add("host"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(), + varibales, associateInstances.getResponse()); + } + + @Test + public void associationAndDisassociateVfInstancesWhenReqMaxOccurrencesAlreadyReached() throws Exception, Exception { + // Add VFC4 (with Requirements: tosca.capabilities.Container, MIN=1 + // MAX=1) instance to VF + ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails4, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithReq); + // Add VFC3 (with Capabilities: tosca.capabilities.Container, MIN=1 + // MAX=1 ) instance to VF + ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails3, sdncDesignerDetails, + resourceDetailsVF100); + assertNotNull(componentInstanceWithCap); + // associate Instances + CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100); + RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq, + componentInstanceWithCap, capReqDefBeforeAssociate); + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkSuccess(associateInstances); + assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(), + resourceDetailsVF100.getUniqueId())); + // GET resource + RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + String containerMinReq = "0"; + String containerMaxReq = "0"; + String containerMinCap = "0"; + String containerMaxCap = "0"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC3, resourceVFC4); + // Disassociate 2 Instances + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE); + assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, + dissociateInstances.getErrorCode().intValue()); + assertTrue(getComponentInstancesRelations(resourceDetailsVF100.getUniqueId()).isEmpty()); + // GET resource + getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails, + resourceDetailsVF100.getUniqueId()); + resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class); + // Verify Container requirements and Capabilities + containerMinReq = "1"; + containerMaxReq = "1"; + containerMinCap = "1"; + containerMaxCap = "1"; + verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + containerMinReq, containerMaxReq, containerMinCap, containerMaxCap); + verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType, + resourceVFC3, resourceVFC4); + } + + /////////////////////////////////////// + + private boolean checkRealtionship(String fromNode, String toNode, String resourceUniqueId) throws Exception { + List componentInstancesRelations = getComponentInstancesRelations( + resourceUniqueId); + RequirementCapabilityRelDef requirementCapabilityRelDef = componentInstancesRelations.get(0); + boolean fromNodeCheck = requirementCapabilityRelDef.getFromNode().equals(fromNode); + boolean toNodeCheck = requirementCapabilityRelDef.getToNode().equals(toNode); + + return fromNodeCheck && toNodeCheck; + } + + private List getComponentInstancesRelations(String resourceUniqueId) + throws ClientProtocolException, IOException { + Resource resource = getVfAsResourceObject(resourceUniqueId); + List componenRelationInstances = resource.getComponentInstancesRelations(); + + return componenRelationInstances; + } + + private Resource getVfAsResourceObject(String resourceUniqueId) throws ClientProtocolException, IOException { + RestResponse getResource = ResourceRestUtils.getResource(resourceUniqueId); + Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class); + return resource; + } + + private RequirementCapabilityRelDef setRelationshipBetweenInstances(ComponentInstance riReq, + ComponentInstance riCap, CapReqDef capReqDef) throws Exception { + + String capbilityUid = capReqDef.getCapabilities().get("tosca.capabilities.Container").get(0).getUniqueId(); + String requirementUid = capReqDef.getRequirements().get("tosca.capabilities.Container").get(0).getUniqueId(); + + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + requirementDef.setFromNode(riReq.getUniqueId()); + requirementDef.setToNode(riCap.getUniqueId()); + + RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(); + pair.setRequirementOwnerId(riReq.getUniqueId()); + pair.setCapabilityOwnerId(riCap.getUniqueId()); + pair.setRequirement("host"); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("tosca.capabilities.Container"); + pair.setRelationships(relationship); + pair.setCapabilityUid(capbilityUid); + pair.setRequirementUid(requirementUid); + List relationships = new ArrayList<>(); + relationships.add(pair); + requirementDef.setRelationships(relationships); + return requirementDef; + } + + private CapReqDef getResourceReqCap(ResourceReqDetails res) throws IOException { + RestResponse getResourceBeforeAssociate = ComponentRestUtils + .getComponentRequirmentsCapabilities(sdncDesignerDetails, resourceDetailsVF100); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceBeforeAssociate.getResponse(), CapReqDef.class); + return capReqDef; + } + + private RestResponse importedResource(ImportReqDetails importReqDetails, String ymlFile) throws Exception { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, + ymlFile); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, + sdncDesignerDetails, null); + assertEquals("Check response code after importing resource", BaseRestUtils.STATUS_CODE_CREATED, + importResourceResponse.getErrorCode().intValue()); + return importResourceResponse; + } + + private ComponentInstance createComponentInstance(ResourceReqDetails res, User user, ResourceReqDetails vf) + throws Exception { + RestResponse response = ResourceRestUtils.createResourceInstance(res, user, vf.getUniqueId()); + ResourceRestUtils.checkCreateResponse(response); + ComponentInstance compInstance = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class); + return compInstance; + } + + private void verifyContainerCapabilitiesAndRequirementsOccurrences(Component component, + String CapabilitiesAndRequirementsType, String minReqOccurrences, String maxReqOccurrences, + String minCapabilities, String maxCapabilities) throws Exception { + boolean isRequirementAppear = false; + boolean isCapabilityAppear = false; + List requirements; + List capabilities; + requirements = component.getRequirements().get(CapabilitiesAndRequirementsType); + if (maxReqOccurrences == "0") { + assertTrue(requirements == null); + } // if container MAX requirement = 0 + if (maxReqOccurrences != "0") { + assertNotNull(requirements); + for (RequirementDefinition req : requirements) { + switch (req.getName()) { + case "host": + assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals(minReqOccurrences)); + assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals(maxReqOccurrences)); + isRequirementAppear = true; + break; + } + assertTrue(isRequirementAppear); + isRequirementAppear = false; + } + } + // Container Capabilities + capabilities = component.getCapabilities().get(CapabilitiesAndRequirementsType); + if (maxCapabilities == "0") {// if container MAX capabilities = 0 + assertTrue(capabilities == null); + } + if (maxCapabilities != "0") { + assertNotNull(capabilities); + for (CapabilityDefinition cap : capabilities) { + switch (cap.getName()) { + case "host": + assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals(minCapabilities)); + assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals(maxCapabilities)); + isCapabilityAppear = true; + break; + } + assertTrue(isCapabilityAppear); + isCapabilityAppear = false; + } + } + + } + + private void verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(Component component, + String CapabilitiesAndRequirementsType, Resource vfWithCapabilities, Resource vfWithRequirements) + throws Exception { + boolean isCapReqAppear = false; + List listOfComponentInstances = component.getComponentInstances(); + + for (ComponentInstance instance : listOfComponentInstances) { + if (instance.getComponentUid().equals(vfWithCapabilities.getUniqueId())) { + List capFromResource = vfWithCapabilities.getCapabilities() + .get(CapabilitiesAndRequirementsType); + List capFromInstance = instance.getCapabilities() + .get(CapabilitiesAndRequirementsType); + for (CapabilityDefinition resourceCap : capFromResource) + for (CapabilityDefinition instanceReq : capFromInstance) { + if (resourceCap.getUniqueId().equals(instanceReq.getUniqueId())) { + assertTrue("Check Min capability Occurrences ", + resourceCap.getMinOccurrences().equals(instanceReq.getMinOccurrences())); + assertTrue("Check Max capability Occurrences ", + resourceCap.getMaxOccurrences().equals(instanceReq.getMaxOccurrences())); + isCapReqAppear = true; + break; + } + + } + } + + if (instance.getComponentUid().equals(vfWithRequirements.getUniqueId())) { + List reqFromAtomicResource = vfWithRequirements.getRequirements() + .get(CapabilitiesAndRequirementsType); + List reqFromInstance = instance.getRequirements() + .get(CapabilitiesAndRequirementsType); + for (RequirementDefinition resourceReq : reqFromAtomicResource) + for (RequirementDefinition instanceReq : reqFromInstance) { + if (resourceReq.getUniqueId().equals(instanceReq.getUniqueId())) { + assertTrue("Check Min Requirement Occurrences ", + resourceReq.getMinOccurrences().equals(instanceReq.getMinOccurrences())); + assertTrue("Check Max Requirement Occurrences ", + resourceReq.getMaxOccurrences().equals(instanceReq.getMaxOccurrences())); + isCapReqAppear = true; + break; + } + } + } + assertTrue(isCapReqAppear); + isCapReqAppear = false; + } + + } + + private RequirementCapabilityRelDef getReqCapRelation(String reqCompInstId, String capCompInstId, String capType, + String reqName, List capList, List reqList, + String vfc1UniqueId, String vfc2UniqueId) { + return ElementFactory.getReqCapRelation(reqCompInstId, capCompInstId, vfc1UniqueId, vfc2UniqueId, capType, + reqName, capList, reqList); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java new file mode 100644 index 0000000000..7181549a27 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java @@ -0,0 +1,1627 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.codehaus.jettison.json.JSONException; +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.ci.tests.api.ComponentInstanceBaseTest; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +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.ServiceCategoriesEnum; +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.Utils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils; +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.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest { + private static Logger log = LoggerFactory.getLogger(ServiceComponentInstanceCRUDTest.class.getName()); + private static final String SPACE_STRING = " "; + private static String REQUIREMENT_NAME = "host"; + private static String CAPABILITY_TYPE = "tosca.capabilities.Container"; + + private String reqOwnerId; + private String capOwnerId; + + public ServiceComponentInstanceCRUDTest() { + super(new TestName(), ServiceComponentInstanceCRUDTest.class.getSimpleName()); + } + + @BeforeMethod(alwaysRun = true) + public void before() throws Exception { + init(); + createComponents(); + } + + private void createComponents() throws Exception { + createAtomicResource(resourceDetailsVFC_01); + createAtomicResource(resourceDetailsVFC_02); + createAtomicResource(resourceDetailsCP_01); + createAtomicResource(resourceDetailsVL_01); + createAtomicResource(resourceDetailsVL_02); + createVF(resourceDetailsVF_01); + createVF(resourceDetailsVF_02); + createService(serviceDetails_01); + certifyResource(resourceDetailsVFC_01); + certifyResource(resourceDetailsVFC_02); + RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_01, + resourceDetailsVFC_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + reqOwnerId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + capOwnerId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);// should + // be + // updated + // to + // getUniqueIdOfFirstInstance + // in + // service + // context + } + + private void certifyResource(ResourceReqDetails resource) throws Exception { + changeResourceLifecycleState(resource, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + changeResourceLifecycleState(resource, sdncTesterDetails.getUserId(), LifeCycleStatesEnum.STARTCERTIFICATION); + changeResourceLifecycleState(resource, sdncTesterDetails.getUserId(), LifeCycleStatesEnum.CERTIFY); + } + + private void changeResourceLifecycleState(ResourceReqDetails resourceDetails, String userUserId, + LifeCycleStatesEnum lifeCycleStates) throws Exception { + RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, userUserId, lifeCycleStates); + LifecycleRestUtils.checkLCS_Response(response); + } + + private void changeServiceLifecycleState(ServiceReqDetails serviceDetails, User user, + LifeCycleStatesEnum lifeCycleStates) throws Exception { + RestResponse response = LifecycleRestUtils.changeServiceState(serviceDetails, user, lifeCycleStates); + LifecycleRestUtils.checkLCS_Response(response); + } + + private void createVFInstanceFailWithoutChangeState(ActionStatus actionStatus, List variables, + ResourceReqDetails vfResource, User user, int errorCode) throws Exception { + RestResponse createVFInstanceSuccessfullyWithoutChangeStateResp = createVFInstance(serviceDetails_01, + vfResource, user); + checkErrorMessage(actionStatus, variables, errorCode, createVFInstanceSuccessfullyWithoutChangeStateResp); + } + + private void createVFInstanceFail(ActionStatus actionStatus, List variables, ResourceReqDetails vfResource, + User user, int errorCode) throws Exception, FileNotFoundException, JSONException { + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, vfResource, user); + checkErrorMessage(actionStatus, variables, errorCode, createVFInstResp); + } + + private void deleteVFInstanceFail(ActionStatus actionStatus, List variables, ResourceReqDetails vfResource, + User user, int errorCode) throws Exception, FileNotFoundException, JSONException { + RestResponse deleteVFInstResp = deleteVFInstance(vfResource.getUniqueId(), serviceDetails_01, user); + checkErrorMessage(actionStatus, variables, errorCode, deleteVFInstResp); + } + + private void createAtomicResourceInstanceFailWithoutChangeState(ActionStatus actionStatus, List variables, + ResourceReqDetails atomicResource, User user, int errorCode) + throws Exception, FileNotFoundException, JSONException { + RestResponse createAtomicInstResp = createAtomicInstanceForService(serviceDetails_01, atomicResource, user); + checkErrorMessage(actionStatus, variables, errorCode, createAtomicInstResp); + } + + private void createAtomicResourceInstanceFail(ActionStatus actionStatus, List variables, + ResourceReqDetails atomicResource, User user, int errorCode) + throws Exception, FileNotFoundException, JSONException { + RestResponse createAtomicInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, atomicResource, + user); + checkErrorMessage(actionStatus, variables, errorCode, createAtomicInstResp); + } + + private void deleteAtomicResourceInstanceFail(ActionStatus actionStatus, List variables, + ResourceReqDetails atomicResource, User user, int errorCode) + throws Exception, FileNotFoundException, JSONException { + RestResponse deleteAtomicInstResp = deleteAtomicInstanceForService(atomicResource.getUniqueId(), + serviceDetails_01, user); + checkErrorMessage(actionStatus, variables, errorCode, deleteAtomicInstResp); + } + + private void checkErrorMessage(ActionStatus actionStatus, List variables, int errorCode, + RestResponse response) throws Exception { + + log.debug(response.getResponse()); + AssertJUnit.assertEquals(errorCode, response.getErrorCode().intValue()); + ErrorValidationUtils.checkBodyResponseOnError(actionStatus.name(), variables, response.getResponse()); + } + + private RestResponse createCheckedinVFInstance(ServiceReqDetails containerDetails, + ResourceReqDetails compInstOriginDetails, User modifier) throws Exception { + changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(), + LifeCycleStatesEnum.CHECKIN); + return createVFInstance(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); + } + + private void createVFInstanceAndAtomicResourceInstanceWithoutCheckin(ResourceReqDetails vf, + ResourceReqDetails atomicResource, User user) throws Exception { + RestResponse createVFInstance = createVFInstance(serviceDetails_01, vf, user); + ResourceRestUtils.checkCreateResponse(createVFInstance); + RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, atomicResource, user); + ResourceRestUtils.checkCreateResponse(atomicInstanceForService); + } + + private void createVFInstanceAndAtomicResourceInstanceSuccessully(ResourceReqDetails vf, + ResourceReqDetails atomicResource) throws Exception, IOException { + createVFInstanceAndAtomicResourceInstanceSuccessully(vf, atomicResource, sdncDesignerDetails); + } + + private void createVFInstanceAndAtomicResourceInstanceSuccessully(ResourceReqDetails vf, + ResourceReqDetails atomicResource, User user) throws Exception, IOException { + changeResourceLifecycleState(vf, vf.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN); + changeResourceLifecycleState(atomicResource, atomicResource.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN); + createVFInstanceAndAtomicResourceInstanceWithoutCheckin(vf, atomicResource, user); + } + + @Test + public void createVFInstanceSuccessfullyTest() throws Exception { + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + 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); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + getComponentAndValidateRIs(serviceDetails_01, 4, 0); + } + + @Test + public void deleteAtomicInstanceTest() throws Exception { + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + // 1 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, + sdncDesignerDetails); + // 2 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, + sdncDesignerDetails); + // 3 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02, + sdncDesignerDetails); + // 4 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + // To delete + String compInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // 3 rel + createVFInstResp = deleteAtomicInstanceForService(compInstId, serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkDeleteResponse(createVFInstResp); + getComponentAndValidateRIs(serviceDetails_01, 3, 0); + } + + @Test + public void deleteVFInstanceTest() throws Exception { + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + // 1 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails); + String compInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + // 2 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, + sdncDesignerDetails); + // 3 rel + ResourceRestUtils.checkCreateResponse(createVFInstResp); + // 2 rel + createVFInstResp = deleteVFInstance(compInstId, serviceDetails_01, sdncDesignerDetails); + ResourceRestUtils.checkDeleteResponse(createVFInstResp); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void associateDissociateTwoVFs() throws Exception { + + RestResponse createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + + String capType = CAPABILITY_TYPE; + String reqName = REQUIREMENT_NAME; + + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List 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.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List list = capReqDef.getRequirements().get(capType); + AssertJUnit.assertEquals("Check requirement", null, list); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + + dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + list = capReqDef.getRequirements().get(capType); + AssertJUnit.assertEquals("Check requirement", 1, list.size()); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + private RequirementCapabilityRelDef getReqCapRelation(String reqCompInstId, String capCompInstId, String capType, + String reqName, List capList, List reqList) { + return ElementFactory.getReqCapRelation(reqCompInstId, capCompInstId, reqOwnerId, capOwnerId, capType, reqName, + capList, reqList); + } + + @Test + public void createResourceInstanceByDifferentDesignerTest() throws Exception { + createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409); + createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test + public void createResourceInstanceByDifferentDesignerTest_ServiceIsCheckedin() throws Exception { + User designer2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + changeServiceLifecycleState(serviceDetails_01, designer2, LifeCycleStatesEnum.CHECKOUT); + + createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01, designer2); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + + } + + @Test + public void createResourceInstanceByTester() throws Exception { + createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409); + createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test + public void createResourceInstanceWithNotASDCUserTest() throws Exception { + sdncDesignerDetails.setUserId("ab0001"); + createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + sdncDesignerDetails, 409); + createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, sdncDesignerDetails, 409); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test + public void createResourceInstanceWithEmptyUserIdTest() throws Exception { + sdncDesignerDetails.setUserId(""); + createVFInstanceFail(ActionStatus.MISSING_INFORMATION, new ArrayList(), resourceDetailsVF_01, + sdncDesignerDetails, 403); + createAtomicResourceInstanceFail(ActionStatus.MISSING_INFORMATION, new ArrayList(), + resourceDetailsCP_01, sdncDesignerDetails, 403); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test + public void createResourceInstanceWithEmptyServiceUidTest() throws Exception { + serviceDetails_01.setUniqueId(""); + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + assertEquals(404, createVFInstResp.getErrorCode().intValue()); + RestResponse createAtomicInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, + resourceDetailsCP_01, sdncDesignerDetails); + assertEquals(404, createAtomicInstResp.getErrorCode().intValue()); + } + + @Test + public void createResourceInstanceWhileResourceNotExistTest() throws Exception { + String vfResourceUniqueId = "1234"; + String atomicResourceUniqueId = "5678"; + + resourceDetailsVF_01.setUniqueId(vfResourceUniqueId); + resourceDetailsCP_01.setUniqueId(atomicResourceUniqueId); + + createVFInstanceFailWithoutChangeState(ActionStatus.RESOURCE_NOT_FOUND, + new ArrayList(Arrays.asList("")), resourceDetailsVF_01, sdncDesignerDetails, 404); + createAtomicResourceInstanceFailWithoutChangeState(ActionStatus.RESOURCE_NOT_FOUND, + new ArrayList(Arrays.asList("")), resourceDetailsCP_01, sdncDesignerDetails, 404); + } + + @Test + public void createResourceInstanceInServiceNotExistsTest() throws Exception { + serviceDetails_01.setUniqueId("1234"); + createVFInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList(Arrays.asList("")), + resourceDetailsVF_01, sdncDesignerDetails, 404); + createAtomicResourceInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList(Arrays.asList("")), + resourceDetailsCP_01, sdncDesignerDetails, 404); + } + + @Test + public void createResourceInstanceInCheckedinServiceTest() throws Exception { + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + + createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsVF_01, sdncDesignerDetails, 409); + createAtomicResourceInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, sdncDesignerDetails, 409); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test(enabled = false) + public void createResourceInstance_ResourceInCheckoutStateTest() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + RestResponse createVFInstanceWithoutChangeStateResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ComponentInstanceRestUtils.checkCreateResponse(createVFInstanceWithoutChangeStateResp); + RestResponse createAtomicInstWithoutCheangeStateResp = createAtomicInstanceForService(serviceDetails_01, + resourceDetailsCP_01, sdncDesignerDetails); + ComponentInstanceRestUtils.checkCreateResponse(createAtomicInstWithoutCheangeStateResp); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void createResourceInstance_ResourceInCertificationRequestStateTest() throws Exception { + changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + changeResourceLifecycleState(resourceDetailsCP_01, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + + createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void createResourceInstance_startCertificationStateTest() throws Exception { + changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + changeResourceLifecycleState(resourceDetailsCP_01, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + + changeResourceLifecycleState(resourceDetailsVF_01, sdncTesterDetails.getUserId(), + LifeCycleStatesEnum.STARTCERTIFICATION); + changeResourceLifecycleState(resourceDetailsCP_01, sdncTesterDetails.getUserId(), + LifeCycleStatesEnum.STARTCERTIFICATION); + + createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01, + sdncDesignerDetails); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + + } + + @Test + public void createResourceInstance_certifiedStateTest() throws Exception { + certifyResource(resourceDetailsVF_01); + certifyResource(resourceDetailsCP_01); + + createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01, + sdncDesignerDetails); + } + + @Test + public void createResourceInstance_OneHasDifferentOwner() throws Exception { + User designer2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2); + + ResourceReqDetails vfResource = new ResourceReqDetails(resourceDetailsVF_01, "0.1"); + vfResource.setUniqueId(null); + vfResource.setName("newVF"); + vfResource.setTags(new ArrayList(Arrays.asList(vfResource.getName()))); + createVF(vfResource, designer2); + + RestResponse atomicInstanceForService = createCheckedinAtomicInstanceForService(serviceDetails_01, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(atomicInstanceForService); + createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), vfResource, + designer2, 409); + + getComponentAndValidateRIs(serviceDetails_01, 1, 0); + } + + @Test + public void indexesOfVFInstancesTest() throws Exception { + String firstInstanceName = resourceDetailsVF_01.getName() + SPACE_STRING + "1"; + String secondInstanceName = resourceDetailsVF_01.getName() + SPACE_STRING + "2"; + String thirdInstanceName = resourceDetailsVF_01.getName() + SPACE_STRING + "3"; + + LifecycleRestUtils.changeResourceState(resourceDetailsVF_01, sdncDesignerDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + + RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createSecondVFInstResp); + RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createThirdVFInstResp); + + Component service = getComponentAndValidateRIs(serviceDetails_01, 3, 0); + List componentInstancesList = service.getComponentInstances(); + for (ComponentInstance instance : componentInstancesList) { + String instanceName = instance.getName(); + boolean isEqualToFirstInstanceName = instanceName.equals(firstInstanceName); + boolean isEqualToSecondInstanceName = instanceName.equals(secondInstanceName); + boolean isEqualToThirdInstanceName = instanceName.equals(thirdInstanceName); + assertTrue(isEqualToFirstInstanceName || isEqualToSecondInstanceName || isEqualToThirdInstanceName); + } + } + + @Test + public void vfInstancesAmountInTwoServiceVersionsTest() throws Exception { + String oldServiceUniqueId = serviceDetails_01.getUniqueId(); + + createTwoCheckedinVFInstances(); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); + + String newSerivceUniqueIdAfterChangeLifecycleState = serviceDetails_01.getUniqueId(); + getComponentAndValidateRIsAfterChangeLifecycleState(oldServiceUniqueId, serviceDetails_01, 2, 0); + + // Check old version + checkServiceOldVersionRIs(oldServiceUniqueId, newSerivceUniqueIdAfterChangeLifecycleState, 2, 0); + + // Add one more resource instance to second version of service + LifecycleRestUtils.changeResourceState(resourceDetailsVL_01, sdncDesignerDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + RestResponse createAtomicResourceInstResp = createAtomicResourceInstanceToSecondServiceVersion( + newSerivceUniqueIdAfterChangeLifecycleState, resourceDetailsVL_01); + String atomicResourceUniqueId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstResp); + getComponentAndValidateRIsAfterAddingAtomicResourceInstance(oldServiceUniqueId, serviceDetails_01, 3, 0); + + // Check that RIs are same as in the beginning - like in old version of + // service + deleteCompInstReqCapFromExpected(atomicResourceUniqueId); + checkServiceOldVersionRIs(oldServiceUniqueId, newSerivceUniqueIdAfterChangeLifecycleState, 2, 0); + + } + + private void createTwoCheckedinVFInstances() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createSecondVFInstResp); + } + + private void getComponentAndValidateRIsAfterAddingAtomicResourceInstance(String oldComponentUniqueId, + ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws Exception { + getComponentAndValidateRIsAfterChangeLifecycleState(oldComponentUniqueId, componentDetails, numOfRIs, + numOfRelations); + + } + + private void checkServiceOldVersionRIs(String oldUniqueId, String newUniqueId, int numOfRIs, int numOfRelations) + throws IOException, Exception { + serviceDetails_01.setUniqueId(oldUniqueId); + getComponentAndValidateRIsAfterChangeLifecycleState(newUniqueId, serviceDetails_01, numOfRIs, numOfRelations); + } + + private RestResponse createAtomicResourceInstanceToSecondServiceVersion(String secondServiceUniqueId, + ResourceReqDetails resourceToAdd) throws Exception { + serviceDetails_01.setUniqueId(secondServiceUniqueId); + RestResponse createAtomicResourceInstResp = createAtomicInstanceForService(serviceDetails_01, resourceToAdd, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstResp); + return createAtomicResourceInstResp; + } + + @Test + public void createResourceInstanceToUnsupportedComponentTest() throws Exception { + String unsupportedType = "unsupported"; + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetailsCP_01); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, sdncDesignerDetails, serviceDetails_01.getUniqueId(), unsupportedType); + checkErrorMessage(ActionStatus.UNSUPPORTED_ERROR, new ArrayList(Arrays.asList(unsupportedType)), 400, + createResourceInstanceResponse); + } + + @Test + public void deleteResourceInstanceByDifferentDesignerTest() throws Exception { + + createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01); + + deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409); + deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void deleteResourceInstanceByDifferentDesignerTest_ServiceIsCheckedin() throws Exception { + + String oldServiceUniqueId = serviceDetails_01.getUniqueId(); + + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + RestResponse createAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, + resourceDetailsCP_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstResp); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + changeServiceLifecycleState(serviceDetails_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), + LifeCycleStatesEnum.CHECKOUT); + String newServiceUniqueId = serviceDetails_01.getUniqueId(); + + String oldVFInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + String newVFInstanceUniqueId = oldVFInstanceUniqueId.replaceAll(oldServiceUniqueId, + serviceDetails_01.getUniqueId()); + String oldAtomicResourceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstResp); + String newAtomicResourceInstanceUniqueId = oldAtomicResourceInstanceUniqueId.replaceAll(oldServiceUniqueId, + serviceDetails_01.getUniqueId()); + + deleteVFInstanceAndAtomicResourceInstanceSuccessfully(newVFInstanceUniqueId, newAtomicResourceInstanceUniqueId, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2)); + + serviceDetails_01.setUniqueId(oldServiceUniqueId); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + + serviceDetails_01.setUniqueId(newServiceUniqueId); + updateExpectedReqCapAfterChangeLifecycleState(oldServiceUniqueId, serviceDetails_01.getUniqueId()); + deleteCompInstReqCapFromExpected(newVFInstanceUniqueId); + deleteCompInstReqCapFromExpected(newAtomicResourceInstanceUniqueId); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + private void deleteVFInstanceAndAtomicResourceInstanceSuccessfully(String vfInstanceUniqueId, + String atomicResourceInstanceUniqueId) throws IOException, Exception { + deleteVFInstanceAndAtomicResourceInstanceSuccessfully(vfInstanceUniqueId, atomicResourceInstanceUniqueId, + sdncDesignerDetails); + } + + private void deleteVFInstanceAndAtomicResourceInstanceSuccessfully(String vfInstanceUniqueId, + String atomicResourceInstanceUniqueId, User user) throws IOException, Exception { + RestResponse deleteVFInstResp = deleteVFInstance(vfInstanceUniqueId, serviceDetails_01, user); + ResourceRestUtils.checkDeleteResponse(deleteVFInstResp); + RestResponse deleteAtomicResourceInsResp = deleteAtomicInstanceForService(atomicResourceInstanceUniqueId, + serviceDetails_01, user); + ResourceRestUtils.checkDeleteResponse(deleteAtomicResourceInsResp); + } + + @Test + public void deleteResourceInstanceByTesterUserTest() throws Exception { + createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01); + deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409); + deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void deleteResourceInstanceByNotASDCUserTest() throws Exception { + createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01); + User notASDCUser = new User(); + notASDCUser.setUserId("ab0001"); + deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + notASDCUser, 409); + deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, notASDCUser, 409); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void deleteResourceInstanceFromCheckedinServiceTest() throws Exception { + createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01); + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + sdncDesignerDetails, 409); + deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, sdncDesignerDetails, 409); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void deleteResourceInstanceWhileResourceCertifiedStateTest() throws Exception { + certifyResource(resourceDetailsVF_01); + certifyResource(resourceDetailsCP_01); + + RestResponse createVFInstance = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstance); + String vfInstUniqueId = ResponseParser.getUniqueIdFromResponse(createVFInstance); + RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(atomicInstanceForService); + String atomicInstUniqueId = ResponseParser.getUniqueIdFromResponse(atomicInstanceForService); + + deleteVFInstanceAndAtomicResourceInstanceSuccessfully(vfInstUniqueId, atomicInstUniqueId); + + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + // fail - bug DE191849 + @Test + public void deleteNotFoundResourceInstanceTest() throws Exception, Throwable { + + resourceDetailsVF_01.setUniqueId("1234"); + resourceDetailsCP_01.setUniqueId("5678"); + + deleteVFInstanceFail(ActionStatus.RESOURCE_NOT_FOUND, new ArrayList(Arrays.asList("")), + resourceDetailsVF_01, sdncDesignerDetails, 404); + deleteAtomicResourceInstanceFail(ActionStatus.RESOURCE_NOT_FOUND, new ArrayList(Arrays.asList("")), + resourceDetailsCP_01, sdncDesignerDetails, 404); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + + // {"requestError":{"serviceException":{"messageId":"SVC4503","text":"Error: + // Requested '%1' service was not found.","variables":["1234"]}}}> + } + + @Test + public void deleteResourceInstanceFromServiceNotFoundTest() throws Exception, Throwable { + serviceDetails_01.setUniqueId("1234"); + deleteVFInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList(Arrays.asList("")), + resourceDetailsVF_01, sdncDesignerDetails, 404); + deleteAtomicResourceInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList(Arrays.asList("")), + resourceDetailsCP_01, sdncDesignerDetails, 404); + } + + @Test + public void deleteResourceInstanceFromUnsupportedTypeTest() throws Exception { + String unsupportedType = "unsupportedType"; + RestResponse deleteVFInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncDesignerDetails, + serviceDetails_01.getUniqueId(), resourceDetailsVF_01.getUniqueId(), unsupportedType); + checkErrorMessage(ActionStatus.UNSUPPORTED_ERROR, new ArrayList(Arrays.asList(unsupportedType)), 400, + deleteVFInstanceResponse); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test + public void deleteResourceInstanceWithEmptyServiceUidTest() throws Exception, Throwable { + serviceDetails_01.setUniqueId(""); + RestResponse deleteVFInstResp = deleteVFInstance(resourceDetailsVF_01.getUniqueId(), serviceDetails_01, + sdncDesignerDetails); + assertEquals(404, deleteVFInstResp.getErrorCode().intValue()); + } + + @Test + public void deleteResourceInstanceWithEmptyResourceInstanceUidTest() throws Exception, Throwable { + RestResponse deleteVFInstResp = deleteVFInstance("", serviceDetails_01, sdncDesignerDetails); + assertEquals(405, deleteVFInstResp.getErrorCode().intValue()); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + @Test + public void deleteResourceInstanceWithEmptyUserIdTest() throws Exception { + sdncDesignerDetails.setUserId(""); + deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), resourceDetailsVF_01, + sdncDesignerDetails, 409); + deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList(), + resourceDetailsCP_01, sdncDesignerDetails, 409); + getComponentAndValidateRIs(serviceDetails_01, 0, 0); + } + + // fail - bug DE188994 + @Test + public void associateResourceInstanceToResourceInstanceNotFoundTest() throws Exception, Throwable { + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + String capCompInstId = "1234"; + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + List capListBeforeAssociate = new ArrayList(); + CapabilityDefinition cap = new CapabilityDefinition(); + cap.setUniqueId(capCompInstId); + capListBeforeAssociate.add(cap); + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, 404, + new ArrayList(Arrays.asList(capCompInstId))); + + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, + // requirementsAfterAssoicate); + // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, + // capabilitiesAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 1, 0); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "VF100 1", + // "9ae76786-2a9c-4409-95cb-db32885ed07f.eece8aaf-eb9f-4aff-b9a5-a11ca11de9e5.vf1001", + // "host" + // ] + } + + // this case is not relevant any more, it is tested as part of occurrences + // story + @Test(enabled = false) + public void associateOnceAgainExistingRelationTest() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + ////////////////////////////////////////////// + // NO ERROR - RELATION ALREADY EXIST + // assocaiteInstancesFail(requirementDef, sdncDesignerDetails, + // ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, 404, new + // ArrayList(Arrays.asList(capCompInstId))); + ////////////////////////////////////////////// + + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListAfterAssociate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + // AssertJUnit.assertEquals("Check requirement", null, + // reqListAfterAssociate); + // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, + // capListAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + + // "messageId": "SVC4119", + // "text": "Error: No relation found between resource instances + // \u0027%1\u0027 and \u0027%2\u0027 for requirement \u0027%3\u0027.", + // "variables": [ + // "VF100 1", + // "VF_admin 2", + // "host" + + } + + @Test + public void associateInstancesInMissingServiceTest() throws Exception { + serviceDetails_01.setUniqueId("1234"); + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.SERVICE_NOT_FOUND, 404, + new ArrayList(Arrays.asList(""))); + } + + @Test + public void associateAfterDeletingResourceTest() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + ResourceRestUtils.deleteResource(resourceDetailsVF_01.getUniqueId(), sdncDesignerDetails.getUserId()); + + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + + // for (CapabilityDefinition capabilityDefinition : + // capListBeforeAssociate) { + // if (capabilityDefinition.getType().equals(CAPABILITY_TYPE)){ + // capabilityDefinition.setMinOccurrences("0"); + // } + // } + // + // List reqListAfterAssociate = + // capReqDefAfterAssociate.getRequirements().get(CAPABILITY_TYPE); + // + // AssertJUnit.assertEquals("Check requirement", null, + // reqListAfterAssociate); + // + // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, + // capListAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + } + + @Test + public void associateInstancesInCheckedinServiceTest() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + + assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409, + new ArrayList()); + + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, requirementsAfterAssoicate); + AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, capabilitiesAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + // fail - bug DE188994 + @Test + public void associateAfterCheckoutAllInstancesTest() throws Exception { + String firstVFUniqueId = resourceDetailsVF_01.getUniqueId(); + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + String secondVFUniqueId = resourceDetailsVF_02.getUniqueId(); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CHECKOUT); + changeResourceLifecycleState(resourceDetailsVF_02, sdncDesignerDetails.getUserId(), + LifeCycleStatesEnum.CHECKOUT); + + requirementDef.setFromNode( + requirementDef.getFromNode().replaceAll(firstVFUniqueId, resourceDetailsVF_01.getUniqueId())); + requirementDef + .setToNode(requirementDef.getToNode().replaceAll(secondVFUniqueId, resourceDetailsVF_02.getUniqueId())); + + assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409, + new ArrayList()); + + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, + // requirementsAfterAssoicate); + // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, + // capabilitiesAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + + // "messageId": "SVC4116", + // "text": "Error: Invalid Content.", + // "variables": [ + // "e9dcea15-ce27-4381-a554-4278973cefb1.d0b3affd-cf92-4626-adfe-961b44103924.vf1001", + // "e9dcea15-ce27-4381-a554-4278973cefb1.d0b3affd-cf92-4626-adfe-961b44103924.vf1001", + // "host" + // ] + + } + + @Test + public void associateInstancesByDifferentUsersTest() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), + ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList()); + assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), + ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList()); + assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), + ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList()); + assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.OPS), + ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList()); + assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1), + ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList()); + + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, requirementsAfterAssoicate); + AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, capabilitiesAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + private void assocaiteInstancesFail(RequirementCapabilityRelDef requirementDef, User user, + ActionStatus actionStatus, int errorCode, List variables) throws IOException, Exception { + RestResponse associateInstancesResp = ComponentInstanceRestUtils.associateInstances(requirementDef, user, + serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + checkErrorMessage(actionStatus, variables, errorCode, associateInstancesResp); + } + + private void dissoicateInstancesFail(RequirementCapabilityRelDef requirementDef, User user, + ActionStatus actionStatus, int errorCode, List variables) throws IOException, Exception { + RestResponse dissoicateInstancesResp = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user, + serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + checkErrorMessage(actionStatus, variables, errorCode, dissoicateInstancesResp); + } + + @Test + public void associateWithMissingServiceUidTest() throws Exception { + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + serviceDetails_01.setUniqueId(""); + RestResponse associateInstancesResp = ComponentInstanceRestUtils.associateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals(404, associateInstancesResp.getErrorCode().intValue()); + } + + // fail - bug DE191824 + @Test + public void associateNotCompitableReqCapTest() throws Exception { + RestResponse createFirstAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, + resourceDetailsCP_01, sdncDesignerDetails); + String reqCompInstName = ResponseParser.getNameFromResponse(createFirstAtomicResourceInstResp); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstAtomicResourceInstResp); + RestResponse createSecondAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, + resourceDetailsVL_02, sdncDesignerDetails); + String capCompInstName = ResponseParser.getNameFromResponse(createSecondAtomicResourceInstResp); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondAtomicResourceInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + List variables = new ArrayList(); + variables.add(reqCompInstName); + variables.add(capCompInstName); + variables.add(REQUIREMENT_NAME); + + assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND, 404, + variables); + + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, + // requirementsAfterAssoicate); + // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, + // capabilitiesAfterAssociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + + // {"requestError":{"serviceException":{"messageId":"SVC4119","text":"Error: + // No relation found between resource instances '%1' and '%2' for + // requirement '%3'.","variables":["CP100 1","VL200 2","host"]}}}> + } + + @Test + public void associateInstancesInTwoServiceVersionsTest() throws Exception { + String oldServiceUniqueId = serviceDetails_01.getUniqueId(); + RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); + String secondServiceUniqueId = serviceDetails_01.getUniqueId(); + + serviceDetails_01.setUniqueId(oldServiceUniqueId); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + + updateCapabilitiesOwnerId(oldServiceUniqueId, capListBeforeAssociate, secondServiceUniqueId); + updateExpectedReqCapAfterChangeLifecycleState(oldServiceUniqueId, secondServiceUniqueId); + CapReqDef capReqDefAfterAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListAfterAssociate = capReqDefAfterAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListAfterAssociate = capReqDefAfterAssociate.getRequirements() + .get(CAPABILITY_TYPE); + // AssertJUnit.assertEquals("Check requirement", null, + // reqListAfterAssociate); + // AssertJUnit.assertEquals("Check capabilities", + // capListBeforeAssociate, capListAfterAssociate); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + + RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqSecondCompInstId = ResponseParser.getUniqueIdFromResponse(createThirdVFInstResp); + + CapReqDef capReqDefBeforeSeconderyAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeSeconderyAssociate = capReqDefBeforeSeconderyAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeSeconderyAssociate = capReqDefBeforeSeconderyAssociate + .getRequirements().get(CAPABILITY_TYPE); + + capCompInstId = capCompInstId.replaceAll(oldServiceUniqueId, secondServiceUniqueId); + RequirementCapabilityRelDef secondRequirementDef = getReqCapRelation(reqSecondCompInstId, capCompInstId, + CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeSeconderyAssociate, reqListBeforeSeconderyAssociate); + associateComponentInstancesForService(secondRequirementDef, serviceDetails_01, sdncDesignerDetails); + + CapReqDef capReqDefAfterSeconderyAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListAfterSeconderyAssociate = capReqDefAfterSeconderyAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListAfterSeconderyAssociate = capReqDefAfterSeconderyAssociate.getRequirements() + .get(CAPABILITY_TYPE); + // AssertJUnit.assertEquals("Check requirement", null, + // reqListAfterSeconderyAssociate); + // AssertJUnit.assertEquals("Check capabilities", + // capListBeforeAssociate, capListAfterSeconderyAssociate); + getComponentAndValidateRIs(serviceDetails_01, 3, 2); + } + + private void updateCapabilitiesOwnerId(String oldUniqueId, List capList, String newUniqueId) { + serviceDetails_01.setUniqueId(newUniqueId); + for (CapabilityDefinition cap : capList) { + String oldOwnerId = cap.getOwnerId(); + String newOwnerId = oldOwnerId.replaceAll(oldUniqueId, newUniqueId); + cap.setOwnerId(newOwnerId); + } + } + + @Test + public void dissociateRelationNotFoundTest() throws Exception { + createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); + String reqCompInstId = "1234"; + createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails); + String capCompInstId = "4567"; + + CapReqDef capReqDef = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + List capList = capReqDef.getCapabilities().get(CAPABILITY_TYPE); + List reqList = capReqDef.getRequirements().get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capList, reqList); + + List variables = new ArrayList(); + variables.add(reqCompInstId); + variables.add(capCompInstId); + variables.add(REQUIREMENT_NAME); + dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, + 404, variables); + + CapReqDef capReqDefAfterDissociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListAfterDissociate = capReqDefAfterDissociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListAfterDissociate = capReqDefAfterDissociate.getRequirements() + .get(CAPABILITY_TYPE); + + AssertJUnit.assertEquals("Check requirement", 1, reqListAfterDissociate.size()); + AssertJUnit.assertEquals("Check requirement", reqList, reqListAfterDissociate); + AssertJUnit.assertEquals("Check capabilities", capList, capListAfterDissociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + + } + + @Test + public void dissociateRelationInServiceNotFoundTest() throws Exception { + String uniqueId = "1234"; + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + serviceDetails_01.setUniqueId(uniqueId); + dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.SERVICE_NOT_FOUND, 404, + new ArrayList(Arrays.asList(""))); + + } + + @Test + public void dissoicateRelationWhileInstanceNotFound() throws Exception { + String capUniqueId = "1234"; + + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails); + String capCompInstId = capUniqueId; + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + List variables = new ArrayList(); + variables.add(reqCompInstId); + variables.add(capCompInstId); + variables.add(REQUIREMENT_NAME); + dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, + 404, variables); + + CapReqDef capReqDefAfterDissociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListAfterDissociate = capReqDefAfterDissociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListAfterDissociate = capReqDefAfterDissociate.getRequirements() + .get(CAPABILITY_TYPE); + AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, reqListAfterDissociate); + AssertJUnit.assertEquals("Check capabilities", capListBeforeAssociate, capListAfterDissociate); + + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void dissociateWhileServiceCheckedinTest() throws Exception { + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409, + new ArrayList()); + } + + @Test + public void dissoicateWithEmptyUserIdHeaderTest() throws Exception { + sdncDesignerDetails.setUserId(""); + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409, + new ArrayList()); + } + + @Test + public void dissociateWithMissingUidOfServiceTest() throws Exception { + serviceDetails_01.setUniqueId(""); + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + RestResponse dissociateResp = ComponentInstanceRestUtils.dissociateInstances(requirementDef, + sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE); + assertEquals(404, dissociateResp.getErrorCode().intValue()); + } + + @Test + public void relationDeletedAfterDeletingResourceInstanceTest() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + + RestResponse deleteVFInstance = deleteVFInstance(reqCompInstId, serviceDetails_01, sdncDesignerDetails); + ComponentInstanceRestUtils.checkDeleteResponse(deleteVFInstance); + getComponentAndValidateRIs(serviceDetails_01, 1, 0); + } + + @Test + public void relationNotFoundInSecondVersionAfterDissociateTest() throws Exception { + String oldContainerUniqueIdToReplace = serviceDetails_01.getUniqueId(); + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); + + updateExpectedReqCapAfterChangeLifecycleState(oldContainerUniqueIdToReplace, serviceDetails_01.getUniqueId()); + getComponentAndValidateRIs(serviceDetails_01, 2, 0); + } + + @Test + public void dissociateOnceAgainTest() throws Exception { + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + String reqCompInsName = ResponseParser + .convertComponentInstanceResponseToJavaObject(createFirstVFInstResp.getResponse()).getName(); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + String capCompInstName = ResponseParser + .convertComponentInstanceResponseToJavaObject(createSecondVFInstResp.getResponse()).getName(); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, + REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + + List variables = new ArrayList(); + variables.add(reqCompInsName); + variables.add(capCompInstName); + variables.add(REQUIREMENT_NAME); + + dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, + 404, variables); + } + + // fail - bug : DE191707 + @Test + public void associateTwoRelations_CheckinCheckout_DissoicateOneRelationInSecondVersion() throws Exception { + String oldContainerUniqueIdToReplace = serviceDetails_01.getUniqueId(); + RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp); + RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp); + RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + String secondReqCompInstId = ResponseParser.getUniqueIdFromResponse(createThirdVFInstResp); + + CapReqDef capReqDefBeforeAssociate = ComponentRestUtils + .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01); + List capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities() + .get(CAPABILITY_TYPE); + List reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements() + .get(CAPABILITY_TYPE); + + RequirementCapabilityRelDef requirementDefFirstRelation = getReqCapRelation(reqCompInstId, capCompInstId, + CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + RequirementCapabilityRelDef requirementDefSecondRelation = getReqCapRelation(secondReqCompInstId, capCompInstId, + CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate); + + associateComponentInstancesForService(requirementDefFirstRelation, serviceDetails_01, sdncDesignerDetails); + associateComponentInstancesForService(requirementDefSecondRelation, serviceDetails_01, sdncDesignerDetails); + getComponentAndValidateRIs(serviceDetails_01, 3, 2); + + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT); + String newContainerUniqueId = serviceDetails_01.getUniqueId(); + + // check if dissoicate of old relation is possibile + // dissoicateInstancesFail(requirementDefFirstRelation, + // sdncDesignerDetails, actionStatus, errorCode, variables); + getComponentAndValidateRIs(serviceDetails_01, 3, 2); + + requirementDefFirstRelation + .setFromNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + requirementDefFirstRelation + .setToNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + + dissociateComponentInstancesForService(requirementDefFirstRelation, serviceDetails_01, sdncDesignerDetails); + + // updateCapabilitiesOwnerId(oldContainerUniqueIdToReplace, + // capListBeforeAssociate, newContainerUniqueId); + // CapReqDef capReqDefAfterAssociate = + // ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, + // serviceDetails_01); + // List capListAfterAssociate = + // capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE); + // List reqListAfterAssociate = + // capReqDefAfterAssociate.getRequirements().get(CAPABILITY_TYPE); + // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, + // reqListAfterAssociate); + // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, + // capListAfterAssociate); + updateExpectedReqCapAfterChangeLifecycleState(oldContainerUniqueIdToReplace, serviceDetails_01.getUniqueId()); + getComponentAndValidateRIs(serviceDetails_01, 3, 1); + } + + @Test + public void createResourceInstancesAndUpdatedServiceMetadataTest() throws Exception, Exception { + serviceDetails_02.setUniqueId(serviceDetails_01.getUniqueId()); + createTwoCheckedinVFInstances(); + LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncDesignerDetails, "0.1", + LifeCycleStatesEnum.CHECKIN); + createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01, + sdncDesignerDetails); + RestResponse updateServiceResp = ServiceRestUtils.updateService(serviceDetails_02, sdncDesignerDetails); + ServiceRestUtils.checkSuccess(updateServiceResp); + getComponentAndValidateRIs(serviceDetails_01, 4, 0); + } + + @Test(enabled = false) + public void forAcceptanceUserStory() throws Exception { + RestResponse createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + String capCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp); + + String capType = CAPABILITY_TYPE; + String reqName = REQUIREMENT_NAME; + + RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + ResourceRestUtils.checkSuccess(getResourceResponse); + CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List capList = capReqDef.getCapabilities().get(capType); + List reqList = capReqDef.getRequirements().get(capType); + + RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, capType, reqName, + capList, reqList); + + associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails); + getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, + serviceDetails_01); + capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class); + List list = capReqDef.getRequirements().get(capType); + AssertJUnit.assertEquals("Check requirement", null, list); + + serviceDetails_02.setUniqueId(serviceDetails_01.getUniqueId()); + RestResponse updateServiceResp = ServiceRestUtils.updateService(serviceDetails_02, sdncDesignerDetails); + ServiceRestUtils.checkSuccess(updateServiceResp); + changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN); + getComponentAndValidateRIs(serviceDetails_01, 2, 1); + } + + @Test + public void testUnsatisfiedCpReqInService() throws Exception { + + // Certify all the needed atomic resources + RestResponse response = LifecycleRestUtils.certifyResource(resourceDetailsCP_01); + ResourceRestUtils.checkSuccess(response); + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails, + resourceDetailsVF_02.getUniqueId()); + ResourceRestUtils.checkSuccess(response); + response = LifecycleRestUtils.certifyResource(resourceDetailsVF_02); + ResourceRestUtils.checkSuccess(response); + capOwnerId = getUniqueIdOfFirstInstanceFromResponse(response); + + RestResponse createAtomicResourceInstance = createVFInstance(serviceDetails_01, resourceDetailsVF_02, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String vfCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + createAtomicResourceInstance = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance); + String compInstName = ResponseParser.getNameFromResponse(createAtomicResourceInstance); + String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance); + + RestResponse submitForTesting = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + String[] variables = new String[] { serviceDetails_01.getName(), "service", "CP (Connection Point)", + compInstName, "requirement", "tosca.capabilities.network.Bindable", "fulfilled" }; + BaseValidationUtils.checkErrorResponse(submitForTesting, + ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, variables); + + fulfillCpRequirement(serviceDetails_01, cpCompInstId, vfCompInstId, capOwnerId, sdncDesignerDetails, + ComponentTypeEnum.SERVICE); + + submitForTesting = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, + LifeCycleStatesEnum.CERTIFICATIONREQUEST); + BaseValidationUtils.checkSuccess(submitForTesting); + } + + @Test + public void getVFInstanceSuccessfullyTest() throws Exception { + RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, + sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + System.out.println("instance successfuly created"); + RestResponse getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE, + serviceDetails_01.getUniqueId(), sdncDesignerDetails); + + for (int i = 0; i < 1500; i++) { + createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); + ResourceRestUtils.checkCreateResponse(createVFInstResp); + System.out.println("instance " + i + "successfuly created"); + } + + getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE, + serviceDetails_01.getUniqueId(), sdncDesignerDetails); + + BaseValidationUtils.checkSuccess(getInstancesResponce); + + } + + private String getUniqueIdOfFirstInstanceFromResponse(RestResponse response) { + try { + JSONArray value = ResponseParser.getListFromJson(response, "componentInstances"); + return ResponseParser.getValueFromJsonResponse(value.get(0).toString(), "uniqueId"); + } catch (Exception e) { + return null; + } + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java new file mode 100644 index 0000000000..262cb65adf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java @@ -0,0 +1,2158 @@ +/*- + * ============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.ci.tests.execute.service; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.codehaus.jettison.json.JSONException; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.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.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.LifecycleRestUtils; +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.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class UpdateServiceMetadataTest extends ComponentBaseTest { + + protected ArrayList listForMessage = new ArrayList(); + + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + protected User sdncDesignerDetails; + protected User sdncDesignerDetails2; + protected User sdncAdminDetails; + protected User sdncGovernorDeatails; + protected User sdncTesterDetails; + protected User sdncOpsDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails; + protected Component resourceDetailsVFCcomp; + protected Component serviceDetailsCompp; + + @Rule + public static TestName name = new TestName(); + protected ServiceReqDetails updatedServiceDetails; + + public UpdateServiceMetadataTest() { + super(name, UpdateServiceMetadataTest.class.getName()); + } + + @BeforeMethod + public void setUp() throws Exception { + + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN4); + sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + resourceDetailsVFCcomp = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + true, true); + + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, + LifeCycleStatesEnum.CERTIFY, true); + Service serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ, + UserRoleEnum.DESIGNER, true); + + serviceDetails = new ServiceReqDetails(serviceServ); + updatedServiceDetails = updatedServiceDetails(serviceDetails); + + } + + protected void certifyService(ServiceReqDetails serviceDetails, String version) throws Exception { + LifecycleRestUtils.certifyService(serviceDetails); + } + + protected ServiceReqDetails updatedServiceDetails(ServiceReqDetails service) { + ServiceReqDetails updatedServiceDetails = new ServiceReqDetails(service); + + updatedServiceDetails.setDescription("updatedDescription"); + updatedServiceDetails.setName(service.getName()); + updatedServiceDetails.setProjectCode("987654654"); + updatedServiceDetails.setIcon("icon-service-red3"); + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("updateTag", updatedServiceDetails.getName()))); + updatedServiceDetails.removeAllCategories(); + updatedServiceDetails.setCategories(null); + updatedServiceDetails.addCategory(ServiceCategoriesEnum.VOIP.getValue()); + updatedServiceDetails.setContactId("xy0123"); + + return updatedServiceDetails; + } + + protected void addMandatoryArtifactsToService() throws Exception { + // TODO Andrey US575052 + // ServiceRestUtils.addServiceMandatoryArtifacts(sdncDesignerDetails, + // createServiceResponse); + } + + protected void getServiceAndValidate(ServiceReqDetails excpectedService, User creator, User updater, + LifecycleStateEnum lifeCycleState) throws Exception { + RestResponse getServiceResponse = ServiceRestUtils.getService(excpectedService.getUniqueId(), + sdncDesignerDetails); + AssertJUnit.assertNotNull("check response object is not null after updating service", getServiceResponse); + AssertJUnit.assertNotNull("check if error code exists in response after updating service", + getServiceResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after updating service", 200, + getServiceResponse.getErrorCode().intValue()); + Service actualService = ResponseParser.convertServiceResponseToJavaObject(getServiceResponse.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(excpectedService, actualService, creator, updater, + lifeCycleState); + } + + public void getServiceAndValidate(ServiceReqDetails excpectedService, LifecycleStateEnum lifecycleState) + throws Exception { + getServiceAndValidate(excpectedService, sdncDesignerDetails, sdncDesignerDetails, lifecycleState); + } + + protected void validateResponse(RestResponse response, int errorCode, ActionStatus actionResponse, + List listOfVariables) throws Exception { + AssertJUnit.assertNotNull("check response object is not null after updating service", response); + AssertJUnit.assertNotNull("check if error code exists in response after updating service", + response.getErrorCode()); + AssertJUnit.assertEquals("Check response code after updating service", errorCode, + response.getErrorCode().intValue()); + + if (actionResponse != null) { + ErrorValidationUtils.checkBodyResponseOnError(actionResponse.name(), listOfVariables, + response.getResponse()); + return; + } + + Service actualService = ResponseParser.convertServiceResponseToJavaObject(response.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, actualService, + sdncDesignerDetails, sdncDesignerDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + protected void validateActualVsExpected(ServiceReqDetails expectedService, RestResponse actualServiceFromResponse) { + Service actualService = ResponseParser + .convertServiceResponseToJavaObject(actualServiceFromResponse.getResponse()); + ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, actualService, + sdncDesignerDetails, sdncDesignerDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + protected String multipleString(String ch, int repeat) { + return StringUtils.repeat(ch, repeat); + } + + protected void correctUpdate() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 200, null, listForMessage); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + protected void updateWithInvalidValue(ActionStatus invalidValue, List arr) throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, invalidValue, arr); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + protected void charactersInRangeChecking(int min, int max, String field) throws Exception { + if (field != null) { + if (field == "name") { + for (char ch = (char) min; ch <= (char) max; ch++) { + updatedServiceDetails.setName("testname" + String.valueOf(ch)); + updatedServiceDetails.setTags( + addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + updateWithInvalidValue(ActionStatus.INVALID_COMPONENT_NAME, + new ArrayList<>(Arrays.asList("Service"))); + } + } else if (field == "icon") { + for (char ch = (char) min; ch <= (char) max; ch++) { + updatedServiceDetails.setIcon("testname" + String.valueOf(ch)); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, + new ArrayList<>(Arrays.asList("Service"))); + } + } else if (field == "tags") { + List variables = Arrays.asList("Service", "tag"); + for (char ch = (char) min; ch <= (char) max; ch++) { + updatedServiceDetails.setTags( + new ArrayList<>(Arrays.asList(String.valueOf(ch), updatedServiceDetails.getName()))); + updateWithInvalidValue(ActionStatus.INVALID_FIELD_FORMAT, variables); + } + } else if (field == "category") { + for (char ch = (char) min; ch <= (char) max; ch++) { + updatedServiceDetails.addCategoryChain(multipleString("1", 5) + String.valueOf(ch), + multipleString("1", 5) + String.valueOf(ch)); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, + new ArrayList<>(Arrays.asList("Service"))); + } + } + + else if (field == "projectCode") { + for (char ch = (char) min; ch <= (char) max; ch++) { + updatedServiceDetails.setProjectCode(multipleString("1", 5) + String.valueOf(ch)); + updateWithInvalidValue(ActionStatus.INVALID_PROJECT_CODE, listForMessage); + } + } + + else + return; + } + + } + + protected void specialCharsChecking(String field) throws Exception { + charactersInRangeChecking(33, 44, field); + charactersInRangeChecking(47, 47, field); + charactersInRangeChecking(58, 64, field); + charactersInRangeChecking(91, 94, field); + charactersInRangeChecking(96, 96, field); + charactersInRangeChecking(123, 126, field); + } + + @Test + public void updateServiceSuccessfully() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 200, null, listForMessage); + + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + } + + protected void checkErrorResponse(ActionStatus actionStatus, ArrayList arrList, RestResponse response) + throws Exception, JSONException { + ErrorValidationUtils.checkBodyResponseOnError(actionStatus.name(), arrList, response.getResponse()); + } + + protected List addServiceNameToTagsList(String serviceName, List tagsList) { + tagsList.add(serviceName); + return tagsList; + + } + + // @Test + // public void updateMetadateSuccessTest() throws Exception { + // CloseableHttpClient httpClient = HttpClients.createDefault(); + // HttpGet httpGet = + // ServiceRestUtils.createGetServiceGetRquest(serviceDetails, + // sdncDesignerDetails); + // CloseableHttpResponse response = httpClient.execute(httpGet); + // assertTrue(response.getStatusLine().getStatusCode() == 200); + // String responseString = new + // BasicResponseHandler().handleResponse(response); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(responseString); + // assertTrue("service object creation failed the returned object is null", + // serviceObject != null); + // String currentCategory = serviceObject.getCategories().get(0).getName(); + // String currentServiceName = serviceObject.getName(); + // String currentProjectCode = serviceObject.getProjectCode(); + // String currentIcon = serviceObject.getIcon(); + // String currentDescription = serviceObject.getDescription(); + // List currentTags = serviceObject.getTags(); + // + // String newCategory = ServiceCategoriesEnum.VOIP.getValue(); + // serviceDetails.addCategory(newCategory); + // // String newServiceName = "updated name"; + // // serviceDetails.setServiceName(newServiceName); + // String newProjectCode = "68686868"; + // serviceDetails.setProjectCode(newProjectCode); + // String newIcon = "updated-icon"; + // serviceDetails.setIcon(newIcon); + // String newDescription = "updated description "; + // serviceDetails.setDescription(newDescription); + // List newTags = new ArrayList<>(); + // newTags.add("update1"); + // newTags.add("update2"); + // newTags.add(currentServiceName); + // serviceDetails.setTags(newTags); + // HttpPut httpPut = + // ServiceRestUtils.createUpdateServiceMetaDataPutRequest(serviceDetails, + // sdncDesignerDetails); + // response = httpClient.execute(httpPut); + // assertTrue(response.getStatusLine().getStatusCode() == 200); + // responseString = new BasicResponseHandler().handleResponse(response); + // String serviceUid = + // ServiceRestUtils.getServiceUniqueIdFromString(responseString); + // + // ServiceReqDetails details = new ServiceReqDetails(); + // details.setUniqueId(serviceUid); + // + // httpGet = ServiceRestUtils.createGetServiceGetRquest(details, + // sdncDesignerDetails); + // response = httpClient.execute(httpGet); + // assertTrue(response.getStatusLine().getStatusCode() == 200); + // responseString = new BasicResponseHandler().handleResponse(response); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(responseString); + // assertTrue("service object creation failed the returned object is null", + // serviceObject != null); + // String updatedCategory = serviceObject.getCategories().get(0).getName(); + // String updatedServiceName = serviceObject.getName(); + // String updatedProjectCode = serviceObject.getProjectCode(); + // String updatedIcon = serviceObject.getIcon(); + // String updatedDescription = serviceObject.getDescription(); + // List updatedTags = serviceObject.getTags(); + // assertFalse("category did not cahnge", + // currentCategory.equals(updatedCategory)); + // assertEquals("categoruy did not match expacted value", updatedCategory, + // newCategory); + // // assertFalse("service name did not change", + // currentServiceName.equals(updatedServiceName) ); + // // assertEquals("service name did not match expacted + // value",updatedServiceName,newServiceName); + // assertFalse("projectCode did not change", + // currentProjectCode.equals(updatedProjectCode)); + // assertEquals("projectCode not match expacted value", updatedProjectCode, + // newProjectCode); + // assertFalse("icon did not change", currentIcon.equals(updatedIcon)); + // assertEquals("icon did not match expacted value", updatedIcon, newIcon); + // assertFalse("description did not change", + // currentDescription.equals(updatedDescription)); + // assertEquals("description did not match expacted value", "updated + // description", updatedDescription); + // assertFalse("tags did not change", currentTags.containsAll(updatedTags)); + // assertTrue("tags did not match expacted value", + // updatedTags.containsAll(newTags)); + // } + + @Test + public void updateService_ByOtherDesigner() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails2); + validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage); + + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void updateService_ByAdmin() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncAdminDetails); + validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage); + + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void updateServiceNotExist() throws Exception { + updatedServiceDetails.setUniqueId("nnnnn"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 404, ActionStatus.SERVICE_NOT_FOUND, + new ArrayList(Arrays.asList(""))); + } + + @Test + public void updateCheckedinService() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + } + + @Test + public void updateCertifiedService() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage); + getServiceAndValidate(serviceDetails, sdncDesignerDetails, sdncAdminDetails, LifecycleStateEnum.CERTIFIED); + } + + // TODO Irrelevant + // @Test(enabled = false) + // public void updateService_NameCaseSensitiveTest() throws Exception { + // ServiceRestUtils.setServiceUniqueId(serviceDetails.getName().toUpperCase()); + // + // RestResponse updateServiceResponse = + // ServiceRestUtils.updateService(updatedServiceDetails, + // sdncDesignerDetails); + // validateResponse(updateServiceResponse, 200, null, listForMessage); + // + // Service serviceFromJsonResponse = + // ResponseParser.convertServiceResponseToJavaObject(updateServiceResponse.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, + // serviceFromJsonResponse, sdncDesignerDetails, (LifecycleStateEnum)null); + // + // getServiceAndValidate(updatedServiceDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // } + + // @Test + // public void updateApprovedDistributionServiceTest() throws Exception { + // // addMandatoryArtifactsToService(); + // certifyService(serviceDetails, serviceDetails.getVersion()); + // + // RestResponse approveResponse = + // ServiceRestUtils.sendApproveDistribution(sdncAdminDetails, + // serviceDetails.getUniqueId(), userRemarks); + // // validateResponse(approveResponse, 200, null, listForMessage); + // + // RestResponse updateServiceResponse = + // ServiceRestUtils.updateService(updatedServiceDetails, + // sdncDesignerDetails); + // validateResponse(updateServiceResponse, 409, + // ActionStatus.RESTRICTED_OPERATION, listForMessage); + // + // getServiceAndValidate(serviceDetails, sdncDesignerDetails, + // sdncAdminDetails,LifecycleStateEnum.CERTIFIED); + // } + + @Test + public void updateServiceByMethod_delete() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, + sdncDesignerDetails, "DELETE", Urls.UPDATE_SERVICE_METADATA); + validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage); + + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void updateServiceByMethod_get() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, + sdncDesignerDetails, "GET", Urls.UPDATE_SERVICE_METADATA); + validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage); + + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void updateServiceByMethod_post() throws Exception { + RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, + sdncDesignerDetails, "POST", Urls.UPDATE_SERVICE_METADATA); + validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage); + + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void updateCheckoutCertifiedService() throws Exception // certify a + // service + // and + // checkout + // it + { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED, listForMessage); + + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + // ---------------------------------------------------------Validation + // Tests--------------------------------------------------------- + + @Test + public void missingCategoryTest1() throws Exception { + List categories = updatedServiceDetails.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + CategoryDefinition categoryDefinition2 = categoryDefinition; + categoryDefinition2.setName(""); + categories.set(0, categoryDefinition2); + updatedServiceDetails.setCategories(categories); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingCategoryTest2() throws Exception { + updatedServiceDetails.setCategories(null); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingServiceNameTest1() throws Exception { + updatedServiceDetails.setName(StringUtils.EMPTY); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingServiceNameTest2() throws Exception { + + updatedServiceDetails.setName(null); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + // TODO Irrelevant + @Test(enabled = false) + public void missingProjectCodeTest1() throws Exception { + updatedServiceDetails.setProjectCode(StringUtils.EMPTY); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_PROJECT_CODE, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + // TODO Irrelevant + @Test(enabled = false) + public void missingProjectCodeTest2() throws Exception { + + updatedServiceDetails.setProjectCode(null); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_PROJECT_CODE, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingIconTest1() throws Exception { + updatedServiceDetails.setIcon(StringUtils.EMPTY); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingIconTest2() throws Exception { + updatedServiceDetails.setIcon(null); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingDescriptionTest1() throws Exception { + updatedServiceDetails.setDescription(StringUtils.EMPTY); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION, + Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingDescriptionTest2() throws Exception { + updatedServiceDetails.setDescription(null); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION, + Arrays.asList("Service")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingTagsTest1() throws Exception { + updatedServiceDetails.setTags(new ArrayList()); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_TAGS, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingTagsTest2() throws Exception { + updatedServiceDetails.setTags(null); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_TAGS, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingTagsTest3() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(StringUtils.EMPTY))); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.INVALID_FIELD_FORMAT, + Arrays.asList("Service", "tag")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void missingTagsTest4() throws Exception { + updatedServiceDetails + .setTags(new ArrayList<>(Arrays.asList(StringUtils.EMPTY, updatedServiceDetails.getName()))); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + validateResponse(updateServiceResponse, 400, ActionStatus.INVALID_FIELD_FORMAT, + Arrays.asList("Service", "tag")); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + // update non-settable/"updatable" parameters tests + + // ------------------------------------------correct + // values------------------------------------------ + @Test + public void contactIdValidationTest1() throws Exception { + updatedServiceDetails.setContactId("ab3456"); + correctUpdate(); + } + + @Test + public void contactIdValidationTest2() throws Exception { + + updatedServiceDetails.setContactId("cd789E"); + correctUpdate(); + } + + @Test + public void contactIdValidationTest3() throws Exception { + + updatedServiceDetails.setContactId("ef4567"); + correctUpdate(); + } + + @Test + public void contactIdValidationTest4() throws Exception { + updatedServiceDetails.setContactId("AA012A"); + correctUpdate(); + } + + @Test + public void contactIdValidationTest5() throws Exception { + updatedServiceDetails.setContactId("CD012c"); + correctUpdate(); + } + + @Test + public void contactIdValidationTest6() throws Exception { + updatedServiceDetails.setContactId("EF0123"); + correctUpdate(); + } + + // ------------------------------------------invalid + // values------------------------------------------ + @Test + public void contactIdValidationTest7() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + updatedServiceDetails.setContactId("ab0001"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void contactIdValidationTest8() throws Exception { + // addMandatoryArtifactsToService(); + + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + updatedServiceDetails = new ServiceReqDetails(certifyService); + updatedServiceDetails.setContactId("ab0001"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void contactIdValidationTest9() throws Exception { + updatedServiceDetails.setContactId("01345a"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service")); + } + + @Test + public void contactIdValidationTest10() throws Exception { + updatedServiceDetails.setContactId("0y000B"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service")); + } + + @Test + public void contactIdValidationTest11() throws Exception { + updatedServiceDetails.setContactId("Y1000b"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service")); + } + + @Test + public void contactIdValidationTest12() throws Exception { + updatedServiceDetails.setContactId("abxyzC"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service")); + } + + @Test + public void contactIdValidationTest13() throws Exception { + updatedServiceDetails.setContactId("cdXYZc"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest14() throws Exception { + updatedServiceDetails.setContactId("efXY1D"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest15() throws Exception { + updatedServiceDetails.setContactId("EFabcD"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest16() throws Exception { + updatedServiceDetails.setContactId("EFABCD"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest17() throws Exception { + updatedServiceDetails.setContactId("EFABC1"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest18() throws Exception { + updatedServiceDetails.setContactId("efui1D"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest19() throws Exception { + updatedServiceDetails.setContactId("efui1!"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest20() throws Exception { + updatedServiceDetails.setContactId("ef555!"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest21() throws Exception { + updatedServiceDetails.setContactId(",f555"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest22() throws Exception { + updatedServiceDetails.setContactId("EF55.5"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest23() throws Exception { + updatedServiceDetails.setContactId("ab000"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest24() throws Exception { + updatedServiceDetails.setContactId("ab000c0"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest25() throws Exception { + updatedServiceDetails.setContactId(" ab0001"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void contactIdValidationTest26() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + updatedServiceDetails = new ServiceReqDetails(serviceDetails); + updatedServiceDetails.setContactId("xy0002"); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest1() throws Exception { + updatedServiceDetails.setName(multipleString("a", 49)); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest2() throws Exception { + updatedServiceDetails.setName(multipleString("b", 50)); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest3() throws Exception { + updatedServiceDetails.setName("testNamE"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest4() throws Exception { + updatedServiceDetails.setName("Testname"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest5() throws Exception { + updatedServiceDetails.setName("Test_name"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest6() throws Exception { + updatedServiceDetails.setName("Test name"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest7() throws Exception { + updatedServiceDetails.setName("Test-name"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest8() throws Exception { + updatedServiceDetails.setName("Test.name"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest9() throws Exception { + updatedServiceDetails.setName("...1..."); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest10() throws Exception { + updatedServiceDetails.setName("-a_1. Arrrrrr"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest11() throws Exception { + updatedServiceDetails.setName("Testname1234567890"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + correctUpdate(); + } + + @Test + public void serviceNameValidationTest14() throws Exception { + updatedServiceDetails.setName(StringUtils.SPACE); // one space with + // nothing + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + // updateWithInvalidValue(ActionStatus.INVALID_COMPONENT_NAME, new + // ArrayList<>(Arrays.asList("Service"))); + validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_COMPONENT_NAME, + new ArrayList<>(Arrays.asList("Service"))); + } + + // ------------------------------------------invalid + // values------------------------------------------ + @Test + public void serviceNameValidationTest12() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + updatedServiceDetails.setName("TestNamE"); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + } + + @Test + public void serviceNameValidationTest13() throws Exception { + updatedServiceDetails.setName(multipleString("c", 51)); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + updateWithInvalidValue(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, + new ArrayList<>(Arrays.asList("Service", "50"))); + } + + @Test + public void serviceNameValidationTest15() throws Exception { + specialCharsChecking("name"); + } + + @Test + public void serviceNameValidationTest16() throws Exception { + // addMandatoryArtifactsToService(); + LifecycleRestUtils.certifyService(serviceDetails); + updatedServiceDetails.setName("testnamename"); + updatedServiceDetails.setCategories(serviceDetails.getCategories()); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + getServiceAndValidate(serviceDetails, sdncDesignerDetails, sdncTesterDetails, LifecycleStateEnum.CERTIFIED); + } + + @Test + public void serviceNameValidationTest17() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + updatedServiceDetails.setName("TestNamE"); + updatedServiceDetails.setCategories(serviceDetails.getCategories()); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + validateResponse(updateServiceResponse2, 400, ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void serviceNameValidationTest18() throws Exception { + updatedServiceDetails.setName(" testname "); + updatedServiceDetails + .setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags())); + RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse1); + assertNotNull(updateServiceResponse1.getErrorCode()); + assertEquals(200, updateServiceResponse1.getErrorCode().intValue()); + updatedServiceDetails.setName(updatedServiceDetails.getName()); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse1); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void iconValidationTest1() throws Exception { + updatedServiceDetails.setIcon(multipleString("a", 24)); + correctUpdate(); + } + + @Test + public void iconValidationTest2() throws Exception { + updatedServiceDetails.setIcon(multipleString("b", 25)); + correctUpdate(); + } + + @Test + public void iconValidationTest3() throws Exception { + updatedServiceDetails.setIcon("testNamE"); + correctUpdate(); + } + + @Test + public void iconValidationTest4() throws Exception { + updatedServiceDetails.setIcon("Testname"); + correctUpdate(); + } + + @Test + public void iconValidationTest5() throws Exception { + updatedServiceDetails.setIcon("Test_name"); + correctUpdate(); + } + + @Test + public void iconValidationTest6() throws Exception { + updatedServiceDetails.setIcon("Test-name"); + correctUpdate(); + } + + @Test + public void iconValidationTest7() throws Exception { + updatedServiceDetails.setIcon("Testname1234567890"); + correctUpdate(); + } + + @Test + public void iconValidationTest8() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + updatedServiceDetails.setIcon("TestNamE"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void iconValidationTest9() throws Exception { + // addMandatoryArtifactsToService(); + LifecycleRestUtils.certifyService(serviceDetails); + updatedServiceDetails.setIcon("testnamename"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + // ------------------------------------------invalid + // values------------------------------------------ + @Test + public void iconValidationTest10() throws Exception { + updatedServiceDetails.setIcon("Test name"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void iconValidationTest11() throws Exception { + updatedServiceDetails.setIcon(StringUtils.SPACE); // one space with + // nothing + updateWithInvalidValue(ActionStatus.COMPONENT_MISSING_ICON, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void iconValidationTest12() throws Exception { + updatedServiceDetails.setIcon("Test.name"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void iconValidationTest13() throws Exception { + specialCharsChecking("icon"); + charactersInRangeChecking(46, 46, "icon"); + } + + @Test + public void iconValidationTest14() throws Exception { + updatedServiceDetails.setIcon(multipleString("c", 26)); + updateWithInvalidValue(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, + new ArrayList<>(Arrays.asList("Service", "25"))); + } + + @Test + public void iconValidationTest15() throws Exception { + // addMandatoryArtifactsToService(); + RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); + Service certifyServiceServ = ResponseParser + .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); + ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); + updatedServiceDetails = new ServiceReqDetails(certifyService); + updatedServiceDetails.setIcon("testnamename"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void iconValidationTest16() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + updatedServiceDetails = new ServiceReqDetails(serviceDetails); + updatedServiceDetails.setIcon("TestNamE"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED, listForMessage, updateServiceResponse); + } + + @Test + public void iconValidationTest17() throws Exception { + updatedServiceDetails.setIcon(" Icon "); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void categoryValidationTest1() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + updatedServiceDetails.addCategory(ServiceCategoriesEnum.VOIP.getValue()); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void categoryValidationTest2() throws Exception { + // updatedServiceDetails.addCategory("someCategory"); + updatedServiceDetails.setCategories(null); + updatedServiceDetails.addCategoryChain("someCategory", null); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void categoryValidationTest3() throws Exception { + updatedServiceDetails.setCategories(null); + updatedServiceDetails.addCategoryChain("SomeCategory10", null); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void categoryValidationTest4() throws Exception { + updatedServiceDetails.setCategories(null); + updatedServiceDetails.addCategoryChain("some Category", null); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service"))); + } + + @Test + public void categoryValidationTest5() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + updatedServiceDetails = new ServiceReqDetails(serviceDetails); + updatedServiceDetails.addCategory("Network L1-3"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void categoryValidationTest6() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + updatedServiceDetails = new ServiceReqDetails(serviceDetails); + updatedServiceDetails = serviceDetails; + List categories = updatedServiceDetails.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + CategoryDefinition categoryDefinition2 = categoryDefinition; + categoryDefinition2.setName("ccc"); + categories.set(0, categoryDefinition2); + updatedServiceDetails.setCategories(categories); + RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + validateResponse(updateServiceResponse2, 400, ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED, listForMessage); + getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void categoryValidationTest7() throws Exception { + updatedServiceDetails.removeAllCategories(); + updatedServiceDetails.addCategory(ServiceCategoriesEnum.NETWORK_L3.getValue()); + correctUpdate(); + } + + @Test + public void categoryValidationTest8() throws Exception { + updatedServiceDetails.setCategories(null); + updatedServiceDetails.addCategoryChain("Network L1-3", null); + correctUpdate(); + } + + @Test + public void tagsValidationTest1() throws Exception { + updatedServiceDetails + .setTags(new ArrayList<>(Arrays.asList(multipleString("a", 49), updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest2() throws Exception { + updatedServiceDetails + .setTags(new ArrayList<>(Arrays.asList(multipleString("B", 50), updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest3() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>( + Arrays.asList(multipleString("A", 50), multipleString("B", 50), updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest5() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("testTaG", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest6() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Testtag", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest7() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test_tag", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest8() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test tag", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest9() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test-tag", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest10() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test.tag", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest11() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("...1...", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest12() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("-a_1. Arrrrrr", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest13() throws Exception { + updatedServiceDetails + .setTags(new ArrayList<>(Arrays.asList("Testtag1234567890", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest14() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("1", "2", "2", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest15() throws Exception { + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKIN); + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("TestTaG", updatedServiceDetails.getName()))); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void tagsValidationTest16() throws Exception { + // addMandatoryArtifactsToService(); + LifecycleRestUtils.certifyService(serviceDetails); + updatedServiceDetails = new ServiceReqDetails(serviceDetails); + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("testtagtag", updatedServiceDetails.getName()))); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse); + } + + @Test + public void tagsValidationTest17() throws Exception { + // addMandatoryArtifactsToService(); + certifyService(serviceDetails, serviceDetails.getVersion()); + LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), + LifeCycleStatesEnum.CHECKOUT); + updatedServiceDetails = new ServiceReqDetails(serviceDetails); + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("TestTaG", updatedServiceDetails.getName()))); + correctUpdate(); + } + + @Test + public void tagsValidationTest18() throws Exception { + int lengthOfServiceName = updatedServiceDetails.getName().length(); + int maxLengthTag = 50; + int tagsCount = 1024 - lengthOfServiceName; + ArrayList tagsList = new ArrayList<>(); + tagsList.add(updatedServiceDetails.getName()); + while (tagsCount > maxLengthTag) { + tagsList.add(multipleString("a", maxLengthTag)); + tagsCount -= maxLengthTag + 1 + + 1/* (50 and comma of each tag + one space, totally 52) */; + } + tagsList.add(multipleString("a", tagsCount)); + updatedServiceDetails.setTags(tagsList); + correctUpdate(); + } + + @Test + public void tagsValidationTest19() throws Exception { + updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(" Tag ", updatedServiceDetails.getName()))); + RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse1); + assertNotNull(updateServiceResponse1.getErrorCode()); + assertEquals(200, updateServiceResponse1.getErrorCode().intValue()); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse1); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void tagsValidationTest20() throws Exception { + ArrayList tagsList = new ArrayList<>(); + tagsList.add(updatedServiceDetails.getName()); + tagsList.add(""); + updatedServiceDetails.setTags(tagsList); + updateWithInvalidValue(ActionStatus.INVALID_FIELD_FORMAT, Arrays.asList("Service", "tag")); + } + + // ------------------------------------------invalid + // values------------------------------------------ + + @Test + public void tagsValidationTest21() throws Exception { + ArrayList tagsList = new ArrayList<>(); + tagsList.add("onetag"); + updatedServiceDetails.setTags(tagsList); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME, listForMessage); + + } + + @Test + public void tagsValidationTest22() throws Exception { + specialCharsChecking("tags"); + } + + @Test + public void descriptionValidationTest1() throws Exception { + updatedServiceDetails.setDescription(multipleString("a", 1023)); + correctUpdate(); + } + + @Test + public void descriptionValidationTest2() throws Exception { + updatedServiceDetails.setDescription(multipleString("a", 1024)); + correctUpdate(); + } + + @Test + public void descriptionValidationTest3() throws Exception { + updatedServiceDetails.setDescription(multipleString("aB", 1024 / 2)); + correctUpdate(); + } + + @Test + public void descriptionValidationTest4() throws Exception { + updatedServiceDetails.setDescription("1234567890"); + correctUpdate(); + } + + @Test + public void descriptionValidationTest5() throws Exception { + updatedServiceDetails.setDescription("desc ription"); + correctUpdate(); + } + + @Test + public void descriptionValidationTest6() throws Exception { + updatedServiceDetails.setDescription("desc\tription"); + RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse1); + assertNotNull(updateServiceResponse1.getErrorCode()); + assertEquals(200, updateServiceResponse1.getErrorCode().intValue()); + updatedServiceDetails.setDescription("desc ription"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse1); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest7() throws Exception { + updatedServiceDetails.setDescription("desc ription "); + RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse2); + assertNotNull(updateServiceResponse2.getErrorCode()); + assertEquals(200, updateServiceResponse2.getErrorCode().intValue()); + updatedServiceDetails.setDescription("desc ription"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse2); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest8() throws Exception { + updatedServiceDetails.setDescription("desc" + StringUtils.LF + "ription"); + RestResponse updateServiceResponse3 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse3); + assertNotNull(updateServiceResponse3.getErrorCode()); + assertEquals(200, updateServiceResponse3.getErrorCode().intValue()); + updatedServiceDetails.setDescription("desc ription"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse3); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest9() throws Exception { + updatedServiceDetails.setDescription("Hello, world!"); + RestResponse updateServiceResponse4 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse4); + assertNotNull(updateServiceResponse4.getErrorCode()); + assertEquals(200, updateServiceResponse4.getErrorCode().intValue()); + updatedServiceDetails.setDescription("Hello, world!"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse4); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest10() throws Exception { + updatedServiceDetails.setDescription("\uC2B5"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_DESCRIPTION, new ArrayList<>(Arrays.asList("Service"))); + + } + + @Test + public void descriptionValidationTest10_a() throws Exception { + updatedServiceDetails.setDescription("文"); + updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_DESCRIPTION, new ArrayList<>(Arrays.asList("Service"))); + + } + + @Test + public void descriptionValidationTest10_b() throws Exception { + updatedServiceDetails.setDescription("\uC2B5abc"); + RestResponse updateServiceResponse5 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse5); + assertNotNull(updateServiceResponse5.getErrorCode()); + assertEquals(200, updateServiceResponse5.getErrorCode().intValue()); + updatedServiceDetails.setDescription("abc"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse5); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + } + + @Test + public void descriptionValidationTest11() throws Exception { + updatedServiceDetails.setDescription("&<>"); + RestResponse updateServiceResponse6 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse6); + assertNotNull(updateServiceResponse6.getErrorCode()); + assertEquals(200, updateServiceResponse6.getErrorCode().intValue()); + updatedServiceDetails.setDescription("&<>"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse6); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest12() throws Exception { + updatedServiceDetails.setDescription("文 test"); + RestResponse updateServiceResponse7 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse7); + assertNotNull(updateServiceResponse7.getErrorCode()); + assertEquals(200, updateServiceResponse7.getErrorCode().intValue()); + updatedServiceDetails.setDescription("test"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse7); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest13() throws Exception { + updatedServiceDetails.setDescription(" description"); + RestResponse updateServiceResponse8 = ServiceRestUtils.updateService(updatedServiceDetails, + sdncDesignerDetails); + assertNotNull(updateServiceResponse8); + assertNotNull(updateServiceResponse8.getErrorCode()); + assertEquals(200, updateServiceResponse8.getErrorCode().intValue()); + updatedServiceDetails.setDescription("description"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse8); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + @Test + public void descriptionValidationTest14() throws Exception { + updatedServiceDetails.setDescription(multipleString("a", 1025)); + updateWithInvalidValue(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, + new ArrayList<>(Arrays.asList("Service", "1024"))); + } + + @Test + public void projectCodeValidationTest1() throws Exception { + String desc = StringUtils.EMPTY; + for (int i = 0; i < 10; i++) { + desc += Integer.toString(i); + if (i >= 4) { + updatedServiceDetails.setProjectCode(desc); + correctUpdate(); + } + } + } + + @Test + public void projectCodeValidationTest2() throws Exception { + updatedServiceDetails.setProjectCode(multipleString("1", 6)); + correctUpdate(); + } + + @Test + public void projectCodeValidationTest3() throws Exception { + this.specialCharsChecking("projectCode"); + } + + // TODO Irrelevant + @Test(enabled = false) + public void projectCodeValidationTest4() throws Exception { + updatedServiceDetails.setProjectCode(multipleString(" ", 5) + "99999"); + RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails); + assertNotNull(updateServiceResponse); + assertNotNull(updateServiceResponse.getErrorCode()); + assertEquals(200, updateServiceResponse.getErrorCode().intValue()); + updatedServiceDetails.setProjectCode("12345"); + validateActualVsExpected(updatedServiceDetails, updateServiceResponse); + getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + } + + @Test + public void projectCodeValidationTest5() throws Exception { + updatedServiceDetails.setProjectCode(multipleString("0", 11)); + updateWithInvalidValue(ActionStatus.INVALID_PROJECT_CODE, listForMessage); + } + + @Test + public void projectCodeValidationTest6() throws Exception { + updatedServiceDetails.setProjectCode(multipleString("1", 4)); + updateWithInvalidValue(ActionStatus.INVALID_PROJECT_CODE, listForMessage); + } + + @Test + public void projectCodeValidationTest7() throws Exception { + updatedServiceDetails.setProjectCode("123456789"); + correctUpdate(); + } + + // ////US553874 + // @JsonIgnore + // @Test + // public void UpdateServiceVersion01_isVNF_toTrue() throws Exception{ + // + // //choose the user to create service + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + // + // //Update Service IsVNF to True + // restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 200, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion02_isVNF_toFalse() throws Exception{ + // + // //choose the user to create service + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + // + // //Update Service IsVNF to True + // restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 200, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion01_isVNF_TrueToNull() throws Exception{ + // + // //choose the user to create service + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + // + // //Update Service IsVNF to True + // restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 400, restResponse.getErrorCode().intValue()); + // List variables = Arrays.asList("VNF Service Indicator"); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), + // variables, restResponse.getResponse()); + // + // //get service and verify that service created with isVNF is remained with + // isVNF = true + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion01_isVNF_FalseToNull() throws Exception{ + // + // //choose the user to create service + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + // + // //Update Service IsVNF to True + // restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 400, restResponse.getErrorCode().intValue()); + // List variables = Arrays.asList("VNF Service Indicator"); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), + // variables, restResponse.getResponse()); + // + // //get service and verify that service created with isVNF is remained with + // isVNF = true + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion02_IsVNF_toTrue() throws Exception{ + // + // //choose the user to create service + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // LifecycleRestUtils.changeServiceState(serviceDetails, + // sdncDesignerDetails, serviceDetails.getVersion(), + // LifeCycleStatesEnum.CHECKIN); + // LifecycleRestUtils.changeServiceState(serviceDetails, + // sdncDesignerDetails, serviceDetails.getVersion(), + // LifeCycleStatesEnum.CHECKOUT); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + // + // //Update Service IsVNF to True + // restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 200, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion02_IsVNF_toFalse() throws Exception{ + // + // //choose the user to create service + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // LifecycleRestUtils.changeServiceState(serviceDetails, + // sdncDesignerDetails, serviceDetails.getVersion(), + // LifeCycleStatesEnum.CHECKIN); + // LifecycleRestUtils.changeServiceState(serviceDetails, + // sdncDesignerDetails, serviceDetails.getVersion(), + // LifeCycleStatesEnum.CHECKOUT); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + // + // //Update Service IsVNF to false + // restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // //restResponse = + // ServiceRestUtils.updateService(serviceDetails.getUniqueId(), + // serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 200, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion11_IsVNF_toFalse() throws Exception{ + // // Can't update isVNF when service version is 1.X + // User sdncUserDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // //String serviceUniqueName = + // ServiceRestUtils.getServiceUniqueId(serviceByNameAndVersion); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1", + // sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + //// ServiceRestUtils.addServiceMandatoryArtifacts(sdncUserDetails, + // restResponse); + // RestResponse response = + // ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + // sdncUserDetails, serviceDetails.getUniqueId(), + // ComponentTypeEnum.SERVICE); + // assertTrue("response code is not 201, returned: " + + // response.getErrorCode(),response.getErrorCode() == 201); + // RestResponse changeServiceState = + // LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + // assertTrue("certify service request returned status:" + + // changeServiceState.getErrorCode(),changeServiceState.getErrorCode() == + // 200); + // LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails, + // LifeCycleStatesEnum.CHECKOUT); + // + // //Update Service IsVNF to false + // restResponse = ServiceRestUtils.updateService(serviceDetails, + // sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating service metadata", 400, + // restResponse.getErrorCode().intValue()); + // List variables = new ArrayList(); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_IS_VNF_CANNOT_BE_CHANGED.name(), + // variables, restResponse.getResponse()); + // + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "1.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // + // } + // + // @JsonIgnore + // @Test + // public void UpdateServiceVersion11_IsVNF_toTrue() throws Exception{ + // // Can't update isVNF when service version is 1.X + // User sdncUserDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // // new service details + // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + // // clean audit DB before updating service + // DbUtils.cleanAllAudits(); + // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(), + // sdncUserDetails.getUserId()); + // serviceDetails = ElementFactory.getDefaultService(); + // + // //send create service toward BE + // RestResponse restResponse = + // ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating Interface Artifact", + // 201, restResponse.getErrorCode().intValue()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // RestResponse serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "0.1"); + // Service serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // //String serviceUniqueName = + // ServiceRestUtils.getServiceUniqueId(serviceByNameAndVersion); + // + // //validate audit + // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, + // "0.1", sdncUserDetails); + // String auditAction="Create"; + // expectedResourceAuditJavaObject.setPrevState(""); + // expectedResourceAuditJavaObject.setPrevVersion(""); + // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // expectedResourceAuditJavaObject.setStatus("201"); + // expectedResourceAuditJavaObject.setDesc("OK"); + // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, + // auditAction, null, false); + // + //// ServiceRestUtils.addServiceMandatoryArtifacts(sdncUserDetails, + // restResponse); + // RestResponse response = + // ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, + // sdncUserDetails, serviceDetails.getUniqueId(), + // ComponentTypeEnum.SERVICE); + // assertTrue("response code is not 201, returned: " + + // response.getErrorCode(),response.getErrorCode() == 201); + // RestResponse changeServiceState = + // LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails); + // assertTrue("certify service request returned status:" + + // changeServiceState.getErrorCode(),changeServiceState.getErrorCode() == + // 200); + // LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails, + // LifeCycleStatesEnum.CHECKOUT); + // + // //Update Service IsVNF to false + // restResponse = ServiceRestUtils.updateService(serviceDetails, + // sdncUserDetails); + // assertNotNull("check error code exists in response after create service", + // restResponse.getErrorCode()); + // assertEquals("Check response code after updating service metadata", 400, + // restResponse.getErrorCode().intValue()); + // List variables = new ArrayList(); + // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_IS_VNF_CANNOT_BE_CHANGED.name(), + // variables, restResponse.getResponse()); + // + // //get service and verify that service created with isVNF defined in + // serviceDetails + // serviceByNameAndVersion = + // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, + // serviceDetails.getName(), "1.1"); + // serviceObject = + // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse()); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, + // serviceObject, sdncUserDetails, + // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java new file mode 100644 index 0000000000..24afcec40f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java @@ -0,0 +1,756 @@ +/*- + * ============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.ci.tests.execute.user; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpStatus; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +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.ResourceRespJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedUserCRUDAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.users.UserResponseMessageEnum; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils; +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.UserRestUtils; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.UserValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +/** + * @author alitvinsky + * + */ +public class ActivateDeActivateDeleteUser extends ComponentBaseTest { + private static Logger logger = LoggerFactory.getLogger(ActivateDeActivateDeleteUser.class.getName()); + protected Gson gson = new Gson(); + protected User sdncAdminUser; + + @BeforeMethod + public void init() { + sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + } + + @Rule + public static TestName name = new TestName(); + + public ActivateDeActivateDeleteUser() { + super(name, ActivateDeActivateDeleteUser.class.getName()); + } + + @Test + public void authorizeDeActivatedUser() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + // deActivate created user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + sdncUserDetails.setStatus(UserStatusEnum.INACTIVE); + validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + + AssertJUnit.assertEquals("Check response code after deActive user", errorInfo.getCode(), + getUserResponse.getErrorCode()); + + List variables = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables, + getUserResponse.getResponse()); + + // clean audit before authorization test + DbUtils.cleanAllAudits(); + + // Perform login from WebSeal + User sealUserDetails = sdncUserDetails; + RestResponse authorizedUserResponse = UserRestUtils.authorizedUserTowardsCatalogBeQA(sealUserDetails); + + // validate response + + ErrorInfo errorInfo2 = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name()); + + AssertJUnit.assertNotNull("check response object is not null after user login", authorizedUserResponse); + AssertJUnit.assertNotNull("check error code exists in response after user login", + authorizedUserResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after deActive user", errorInfo2.getCode(), + authorizedUserResponse.getErrorCode()); + + List variables2 = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_ACCESS.name(), variables2, + authorizedUserResponse.getResponse()); + + // validate against ES DB + + UserValidationUtils.validateDataAgainstAuditDB_access(sealUserDetails, + DbUtils.parseAuditRespByAction("Access"), authorizedUserResponse, errorInfo2, variables2); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + public User getDefaultUserDetails() { + + String httpCspUserId = "km2000"; + String userFirstName = "Kot"; + String userLastName = "May"; + String email = "km2000@intl.sdc.com"; + String role = UserRoleEnum.ADMIN.name(); + User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + + return sdncUserDetails; + } + + public void validateSuccessCreateUserResponse(User sdncUserDetails, RestResponse createUserResponse) + throws Exception { + + AssertJUnit.assertNotNull("check response object is not null after create user", createUserResponse); + AssertJUnit.assertNotNull("check error code exists in response after create user", + createUserResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create user", HttpStatus.SC_CREATED, + createUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse()); + // UserRestUtils.validateAddUserAuditMessage(sdncUserDetails, + // sdncAdminUser, String.valueOf(HttpStatus.SC_CREATED), + // UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + // UserRestUtils.getAddUserAuditMessage("AddUser")); + String addUser = "AddUser"; + ExpectedUserCRUDAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(addUser, + sdncAdminUser, ActionStatus.CREATED, sdncUserDetails, null); + AuditValidationUtils.validateAddUserAudit(constructFieldsForAuditValidation, addUser); + + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse()); + + } + + public void validateSuccessDeActivateUserResponse(User sdncUserDetails, RestResponse deActivateUserResponse) + throws Exception { + + AssertJUnit.assertNotNull("check response object is not null after deActive user", deActivateUserResponse); + AssertJUnit.assertNotNull("check error code exists in response after deActive user", + deActivateUserResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after deActive user", 200, + deActivateUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, deActivateUserResponse.getResponse()); + + String deleteUser = "DeleteUser"; + ExpectedUserCRUDAudit constructFieldsForAuditValidation = Convertor + .constructFieldsForAuditValidation(deleteUser, sdncAdminUser, ActionStatus.OK, null, sdncUserDetails); + AuditValidationUtils.validateAddUserAudit(constructFieldsForAuditValidation, deleteUser); + + } + + // US498322 - Add Status Field to USER + + @Test + public void createNewUser() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + @Test + public void createDefaultUser() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + sdncUserDetails.setFirstName(null); + sdncUserDetails.setLastName(null); + sdncUserDetails.setEmail(null); + sdncUserDetails.setRole(null); + + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + @Test + public void createTesterUser() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + sdncUserDetails.setLastName(null); + sdncUserDetails.setRole(UserRoleEnum.TESTER.name()); + + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + @Test + public void deActivateCreatedAdminUser() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + // deActivate created user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + sdncUserDetails.setStatus(UserStatusEnum.INACTIVE); + validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + + assertEquals("Check response code after get user", errorInfo.getCode(), getUserResponse.getErrorCode()); + + List variables = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables, + getUserResponse.getResponse()); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + @Test + public void deActivateTheSameUserTwice() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + // deActivate created user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + sdncUserDetails.setStatus(UserStatusEnum.INACTIVE); + validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + + assertEquals("Check response code after deActive user", errorInfo.getCode(), + getUserResponse.getErrorCode()); + + List variables = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables, + getUserResponse.getResponse()); + + // deActivate the same user once time more + RestResponse deActivateUserResponse2 = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + ErrorInfo errorInfo2 = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + assertEquals("Check response code after deActive user", errorInfo2.getCode(), + deActivateUserResponse2.getErrorCode()); + + List variables2 = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables2, + deActivateUserResponse2.getResponse()); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + @Test + public void createAgainDeActivatedUser() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + + try { + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + // deActivate created user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + sdncUserDetails.setStatus(UserStatusEnum.INACTIVE); + validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + + assertEquals("Check response code after deActive user", errorInfo.getCode(), + getUserResponse.getErrorCode()); + + List variables = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables, + getUserResponse.getResponse()); + + // create the user with the same UserId(details) as deActivated user + DbUtils.cleanAllAudits(); + + RestResponse createUserResponse2 = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + ErrorInfo errorInfo2 = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + assertEquals("Check response code after deActive user", errorInfo2.getCode(), + createUserResponse2.getErrorCode()); + + List variables2 = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables2, + createUserResponse2.getResponse()); + + } finally { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + // very not recommend to run this test, resources/services may be zombie + // @Test + public void deActivateLastAdminUser() throws Exception { + + try { + + // send get all ADMIN user request toward BE + RestResponse getAllAdminUsers = UserRestUtils.getAllAdminUsers(sdncAdminUser); + + assertNotNull("check response object is not null after create user", getAllAdminUsers); + assertNotNull("check error code exists in response after create user", getAllAdminUsers.getErrorCode()); + assertEquals("Check response code after create user", 200, getAllAdminUsers.getErrorCode().intValue()); + + TypeToken> typeToken = new TypeToken>() { + }; + List listOfUsersOnResponse = gson.fromJson(getAllAdminUsers.getResponse(), typeToken.getType()); + logger.debug("listOfUsers: {}", listOfUsersOnResponse); + + // build map of all Admin users from listOfUsersOnResponse from + // response + Map mapAllUsersOnResponse = new HashMap(); + for (User sdncUser : listOfUsersOnResponse) { + mapAllUsersOnResponse.put(sdncUser.getUserId(), sdncUser); + } + + // remove from mapAllUsersOnResponse map one of admin users + mapAllUsersOnResponse.remove(sdncAdminUser.getUserId()); + logger.debug("map Of all Admin users exclude one : {}", mapAllUsersOnResponse); + + // deActivate all Admin users from the userIdAllAdminList list + for (Entry entry : mapAllUsersOnResponse.entrySet()) { + UserRestUtils.deActivateUser(entry.getValue(), sdncAdminUser); + } + + // deActivate last Admin user user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncAdminUser, sdncAdminUser); + + ErrorInfo errorInfo = ErrorValidationUtils + .parseErrorConfigYaml(ActionStatus.DELETE_USER_ADMIN_CONFLICT.name()); + + assertEquals("Check response code after deActive user", errorInfo.getCode(), + deActivateUserResponse.getErrorCode()); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DELETE_USER_ADMIN_CONFLICT.name(), variables, + deActivateUserResponse.getResponse()); + + } finally { + // UserRestUtils.deleteUser(UserRestUtils.getAdminDetails2(), + // sdncAdminUser); + // UserRestUtils.deleteUser(UserRestUtils.getAdminDetails3(), + // sdncAdminUser); + // UserRestUtils.createUser(UserRestUtils.getAdminDetails2(), + // sdncAdminUser); + // UserRestUtils.createUser(UserRestUtils.getAdminDetails3(), + // sdncAdminUser); + } + + } + + // test check the resource accessibility via catalog view, resource was + // created by user which was deActivated + + @Test + public void resourceAccessibility() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource("tosca.nodes.newresource4test4", + NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003"); + String resourceBaseVersion = "0.1"; + + try { + // Delete resource + // resourceUtils.deleteResource_allVersions(resourceDetails, + // sdncAdminUser); + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + + DbUtils.cleanAllAudits(); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + // ------------------------Start create + // resource--------------------------------------------------------------------------------- + + // create resource + RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails); + assertEquals("Check response code after create", 201, createResponse.getErrorCode().intValue()); + + Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResponse.getResponse()); + + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncUserDetails, + createdResource.getUniqueId()); + assertEquals("Check response code after get", 200, resourceGetResponse.getErrorCode().intValue()); + + // validate get response + ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails, + resourceBaseVersion); + resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setAbstractt("false"); + resourceRespJavaObject.setCreatorUserId(sdncUserDetails.getUserId()); + resourceRespJavaObject.setLastUpdaterUserId(sdncUserDetails.getUserId()); + + resourceRespJavaObject + .setCreatorFullName(sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName()); + resourceRespJavaObject + .setLastUpdaterFullName(sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName()); + + ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject); + + // ------------------------End create + // resource--------------------------------------------------------------------------------- + + // clean audit before authorization test + DbUtils.cleanAllAudits(); + + // deActivate created user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + sdncUserDetails.setStatus(UserStatusEnum.INACTIVE); + validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse); + + UserValidationUtils.validateDeleteUserAuditMessage(sdncUserDetails, sdncAdminUser, "200", + UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("DeleteUser")); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + + assertEquals("Check response code after deActive user", errorInfo.getCode(), + getUserResponse.getErrorCode()); + + List variables = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables, + getUserResponse.getResponse()); + + // checking if created resource is accessible + DbUtils.cleanAllAudits(); + + RestResponse getCatalogDataResponse = CatalogRestUtils.getCatalog(sdncAdminUser.getUserId()); + + // validate response + + assertNotNull("check response object is not null after user login", getCatalogDataResponse); + assertNotNull("check error code exists in response after user login", + getCatalogDataResponse.getErrorCode()); + assertEquals("Check response code after deActive user", 200, + getCatalogDataResponse.getErrorCode().intValue()); + + // expected resource list + List resourceExpectedUniqIdList = new ArrayList(); + resourceExpectedUniqIdList.add(resourceDetails.getUniqueId()); + logger.debug("resourceExpectedUniqIdList: {}", resourceExpectedUniqIdList); + + compareResourceUniqIdList(getCatalogDataResponse.getResponse(), resourceExpectedUniqIdList, true); + + } finally { + // resourceUtils.deleteResource_allVersions(resourceDetails, + // sdncAdminUser); + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + // test check the resource accessibility via catalog view, resource was + // created by user which was deActivated + + @Test + public void resourceAccessibilityOnImport() throws Exception { + + User sdncUserDetails = getDefaultUserDetails(); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource("importResource4test", + NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003"); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), + ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); + // String resourceBaseVersion = "1.0"; + + try { + // Delete resource + // resourceUtils.deleteResource_allVersions(resourceDetails, + // sdncAdminUser); + RestResponse deleteUserResponse = UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + assertTrue("delete user request failed", + deleteUserResponse.getErrorCode() == 200 || deleteUserResponse.getErrorCode() == 404); + DbUtils.cleanAllAudits(); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse); + + // ------------------------Start import + // resource--------------------------------------------------------------------------------- + + // import new resource with CERTIFIED state + User importer = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN4); + RestResponse importResponse = ImportRestUtils.importResourceByName(resourceDetails, importer); + + assertNotNull("check response object is not null after create user", importResponse); + assertNotNull("check error code exists in response after create user", importResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, importResponse.getErrorCode().intValue()); + + // ------------------------End import + // resource--------------------------------------------------------------------------------- + + // clean audit before authorization test + DbUtils.cleanAllAudits(); + + // deActivate created user + RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser); + sdncUserDetails.setStatus(UserStatusEnum.INACTIVE); + validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse); + + UserValidationUtils.validateDeleteUserAuditMessage(sdncUserDetails, sdncAdminUser, "200", + UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("DeleteUser")); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name()); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + + assertEquals("Check response code after deActive user", errorInfo.getCode(), + getUserResponse.getErrorCode()); + + List variables = Arrays.asList(sdncUserDetails.getUserId()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables, + getUserResponse.getResponse()); + + // checking if created resource is accessible + DbUtils.cleanAllAudits(); + + RestResponse getCatalogDataResponse = CatalogRestUtils.getCatalog(sdncAdminUser.getUserId()); + + // validate response + + assertNotNull("check response object is not null after user login", getCatalogDataResponse); + assertNotNull("check error code exists in response after user login", + getCatalogDataResponse.getErrorCode()); + assertEquals("Check response code after deActive user", 200, + getCatalogDataResponse.getErrorCode().intValue()); + + // expected resource list + List resourceExpectedUniqIdList = new ArrayList(); + resourceExpectedUniqIdList.add(resourceDetails.getUniqueId()); + logger.debug("resourceExpectedUniqIdList: {}", resourceExpectedUniqIdList); + + compareResourceUniqIdList(getCatalogDataResponse.getResponse(), resourceExpectedUniqIdList, true); + + } finally { + // resourceUtils.deleteResource_allVersions(resourceDetails, + // sdncAdminUser); + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + } + + } + + public void compareServiceUniqIdList(String response, List expectedList, boolean flag) { + + JsonElement jelement = new JsonParser().parse(response); + JsonObject jobject = jelement.getAsJsonObject(); + JsonArray serviceArray = (JsonArray) jobject.get("services"); + logger.debug("{}", serviceArray); + assertTrue("expected service count: " + expectedList.size() + " or more" + ", actual: " + serviceArray.size(), + serviceArray.size() >= expectedList.size()); + + // build service list from response + List serviceReqDetailsListOnResponse = new ArrayList(); + for (int i = 0; i < serviceArray.size(); i++) { + ServiceReqDetails json = gson.fromJson(serviceArray.get(i), ServiceReqDetails.class); + serviceReqDetailsListOnResponse.add(json); + } + } + + public void compareResourceUniqIdList(String response, List expectedList, boolean flag) { + + JsonElement jelement = new JsonParser().parse(response); + JsonObject jobject = jelement.getAsJsonObject(); + JsonArray resourceArray = (JsonArray) jobject.get("resources"); + logger.debug("{}", resourceArray); + assertTrue("expected resource count: " + expectedList.size() + " or more" + ", actual: " + resourceArray.size(), + resourceArray.size() >= expectedList.size()); + + // build resource list from response + List resourceReqDetailsListOnResponse = new ArrayList(); + for (int i = 0; i < resourceArray.size(); i++) { + ResourceReqDetails json = gson.fromJson(resourceArray.get(i), ResourceReqDetails.class); + resourceReqDetailsListOnResponse.add(json); + } + + logger.debug("ResourceReqDetails list on response: {}", resourceReqDetailsListOnResponse); + + List resourceActualUniqIdList = new ArrayList(); + for (ResourceReqDetails resource : resourceReqDetailsListOnResponse) { + resourceActualUniqIdList.add(resource.getUniqueId()); + } + logger.debug("resourceActualUniqIdList on response: {}", resourceActualUniqIdList); + logger.debug("resourceExpectedUniqIdList on response: {}", expectedList); + + if (flag) { + assertTrue("actual list does not contain expected list", + resourceActualUniqIdList.containsAll(expectedList)); + } else { + assertFalse("actual list contains non expected list elements", + resourceActualUniqIdList.containsAll(expectedList)); + } + } + + // public User getDefaultUserDetails(){ + // + // String userFirstName = "Kot"; + // String userLastName = "May"; + // String role = UserRoleEnum.ADMIN.name(); + // User sdncUserDetails = new User(userFirstName, userLastName, + // httpCspUserId, email, role,null); + // + // return sdncUserDetails; + // } + // + // public void validateSuccessCreateUserResponse(User sdncUserDetails, + // RestResponse createUserResponse) throws Exception{ + // + // assertNotNull("check response object is not null after create user", + // createUserResponse); + // assertNotNull("check error code exists in response after create user", + // createUserResponse.getErrorCode()); + // assertEquals("Check response code after create user", + // HttpStatus.SC_CREATED, createUserResponse.getErrorCode().intValue()); + // + // UserRestUtils.validateUserDetailsOnResponse(sdncUserDetails, + // createUserResponse.getResponse()); + // UserRestUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, + // String.valueOf(HttpStatus.SC_CREATED), + // UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + // UserRestUtils.getAddUserAuditMessage("AddUser")); + // RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, + // sdncAdminUser); + // UserRestUtils.validateUserDetailsOnResponse(sdncUserDetails, + // getUserResponse.getResponse()); + // + // } + // + // public void validateSuccessDeActivateUserResponse(User sdncUserDetails, + // RestResponse deActivateUserResponse) throws Exception{ + // + // assertNotNull("check response object is not null after deActive user", + // deActivateUserResponse); + // assertNotNull("check error code exists in response after deActive user", + // deActivateUserResponse.getErrorCode()); + // assertEquals("Check response code after deActive user", 200, + // deActivateUserResponse.getErrorCode().intValue()); + // + // UserRestUtils.validateUserDetailsOnResponse(sdncUserDetails, + // deActivateUserResponse.getResponse()); + // UserRestUtils.validateDeleteUserAuditMessage(sdncUserDetails, + // sdncAdminUser, "200", UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + // UserRestUtils.getAddUserAuditMessage("DeleteUser")); + // + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java new file mode 100644 index 0000000000..2f979f3d15 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java @@ -0,0 +1,1693 @@ +/*- + * ============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.ci.tests.execute.user; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.IOException; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.users.UserResponseMessageEnum; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.UserValidationUtils; +import org.testng.AssertJUnit; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class CreateUserApiTest extends ComponentBaseTest { + + protected User sdncAdminUser; + protected User sdncDesignerUser; + protected User sdncGovernorUser; + protected User sdncTesterUser; + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_SUCSESS_CREATED = 201; + public static final int STATUS_CODE_SUCCESS_DELETE_GET = 200; + public static final int STATUS_CODE_INVALID_CONTENT = 400; + public static final int STATUS_CODE_MISSING_DATA = 400; + public static final int STATUS_CODE_MISSING_INFORMATION = 403; + public static final int STATUS_CODE_RESTRICTED_ACCESS = 403; + public static final int STATUS_CODE_NOT_FOUND = 404; + public static final int STATUS_CODE_RESTRICTED_OPERATION = 409; + public static final int USER_ALREADY_EXIST = 409; + public static final int INVALID_ROLE = 400; + + @Rule + public static TestName name = new TestName(); + + public CreateUserApiTest() { + super(name, CreateUserApiTest.class.getName()); + } + + @BeforeMethod + public void init() { + sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + sdncDesignerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncGovernorUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + sdncTesterUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + + } + + // Story : REST API to provision new user (POST) - US429379 + // must parameters: UserId and Email + + // **********************************************************201*************************************************** + // create user with full parameter set(UserID, First Name, Last Name, Email, + // Role = "DESIGNER", Creator details) + // expected 201 Created + @Test + public void createUser() throws Exception { + + // user initialization + String httpCspUserId = "km2000"; + String userFirstName = "Kot"; + String userLastName = "Matroskin"; + String email = "km2000@intl.sdc.com"; + String role = "ADMIN"; + User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + String addUser = "AddUser"; + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + + AssertJUnit.assertNotNull("check response object is not null after create user", createUserResponse); + AssertJUnit.assertNotNull("check error code exists in response after create user", + createUserResponse.getErrorCode()); + AssertJUnit.assertEquals("Check response code after create user", 201, + createUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse()); + + ExpectedUserCRUDAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(addUser, + sdncAdminUser, ActionStatus.CREATED, sdncUserDetails, null); + AuditValidationUtils.validateAddUserAudit(constructFieldsForAuditValidation, addUser); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse()); + } + + protected static final String ADD_USER = "AddUser"; + + private User mechIdUser = new User(); + private User emptyUser = new User(); + private static final User adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + @AfterMethod + public void setup() throws IOException { + UserRestUtils.deactivateUser(mechIdUser, adminUser); + } + + // create default user(UserID, Email, Creator details) + // expected: role = DESIGNER, first and last name = null, 201 Created + @Test + public void createDefaultUser() throws Exception { + // user initialization + String httpCspUserId = "km2000"; + String userFirstName = null; + String userLastName = null; + String email = null; + String role = null; + User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + + deleteUserAndAudit(sdncUserDetails); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse()); + UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201", + UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse()); + + } + + // create user with one optional parameter first name (UserID, Email, First + // Name, Creator details) + // expected: role = DESIGNER, last name = null, 201 Created + @Test + public void createUserFirstName() throws Exception { + // user initialization + String httpCspUserId = "km2000"; + String userFirstName = "Kot"; + String userLastName = null; + String email = null; + String role = null; + User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + + deleteUserAndAudit(sdncUserDetails); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse()); + UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201", + UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse()); + } + + @Test + public void createDeleteOpsUser() throws Exception { + + String httpCspUserId = "oo2000"; + String userFirstName = "ops"; + String userLastName = "opsLast"; + String email = "ops@intl.sdc.com"; + String role = "OPS"; + User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + + deleteUserAndAudit(sdncUserDetails); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse()); + UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201", + UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse()); + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + RestResponse getDeletedUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + assertEquals("Check response code after delete user", 404, getDeletedUserResponse.getErrorCode().intValue()); + + } + + @Test + public void createDeleteGOVERNORUser() throws Exception { + + String httpCspUserId = "gg2000"; + String userFirstName = "gov"; + String userLastName = "govLast"; + String email = "gov@intl.sdc.com"; + String role = "GOVERNOR"; + User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + + deleteUserAndAudit(sdncUserDetails); + RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse()); + UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201", + UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse()); + + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + RestResponse getDeletedUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser); + assertEquals("Check response code after delete user", 404, getDeletedUserResponse.getErrorCode().intValue()); + + } + + // Benny + // Admin Create OPS user + @Test + public void createOpsUser() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "aa1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedOpsUser); + RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedOpsUser, createUserResponse.getResponse()); + deleteAndCheckUserResponse(expectedOpsUser, 200); + + } + + // Admin Create GOVERNOR user + @Test + public void createGovernorUser() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "aa1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + User expectedUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedUser); + RestResponse createUserResponse = UserRestUtils.createUser(expectedUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedUser, createUserResponse.getResponse()); + RestResponse getUserResponse = UserRestUtils.getUser(expectedUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedUser, getUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(expectedUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from OPS to GOVERNOR + @Test + public void updateOpsUserRole() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ab1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "GOVERNOR"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(governerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(governerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Designer Create OPS user -409 Response Restricted operation + @Test + public void createOpsUserByDesigner() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "aa1122"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedOpsUser); + RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncDesignerUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 409, createUserResponse.getErrorCode().intValue()); + assertEquals("Check response code after create user", "Conflict", createUserResponse.getResponseMessage()); + } + + // Tester Create OPS user -409 Response Restricted operation + @Test + public void createOpsUserByTester() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "aa1122"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedOpsUser); + RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncTesterUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 409, createUserResponse.getErrorCode().intValue()); + assertEquals("Check response code after create user", "Conflict", createUserResponse.getResponseMessage()); + } + + // Designer Try Update OPS user role to GOVERNOR - Response 409 + @Test + public void updateOpsUserRolebyDesigner() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "bt751e"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "GOVERNOR"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // Admin create user with OPS role + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // Designer user try to update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncDesignerUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating user", "Conflict", + updateUserRoleResponse.getResponseMessage()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Tester Try Update OPS user role to GOVERNOR - Response 409 + @Test + public void updateOpsUserRolebyTester() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "bt751w"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "GOVERNOR"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // Admin create user with OPS role + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // Designer user try to update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncTesterUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating user", "Conflict", + updateUserRoleResponse.getResponseMessage()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from OPS to Designer + @Test + public void updateOpsUserRoleFromOpsToDesigner() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ab1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "DESIGNER"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(designerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(designerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from OPS to TESTER + @Test + public void updateOpsUserRoleFromOpsToTester() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ac1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "TESTER"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User testerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(testerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(testerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Tester try to Update user role from OPS to GOVERNOR - Response 409 + // Conflict + @Test + public void updateOpsUserRoleByTester() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ad1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "GOVERNOR"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + // Create user by Admin + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR by Tester + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncTesterUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating user", "Conflict", + updateUserRoleResponse.getResponseMessage()); + + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Designer try to Update user role from OPS to GOVERNOR - Response 409 + // Conflict + @Test + public void updateOpsUserRoleByDesigner() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ad1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + String updatedRole = "GOVERNOR"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + // User governerUser = new User(userFirstName, + // userLastName,httpCspUserId, email, updatedRole); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + // Create user by Admin + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR by Tester + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncDesignerUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating user", "Conflict", + updateUserRoleResponse.getResponseMessage()); + + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Create OPS user - user already exist + @Test + public void createOpsUserAlreadyExist() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "af1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "OPS"; + User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedOpsUser); + RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedOpsUser, createUserResponse.getResponse()); + // Create user that already exists + RestResponse createUserAgainResponse = UserRestUtils.createUser(expectedOpsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserAgainResponse); + assertNotNull("check error code exists in response after create user", createUserAgainResponse.getErrorCode()); + assertEquals("Check response code after create user", 409, createUserAgainResponse.getErrorCode().intValue()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(expectedOpsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from OPS to GOVERNOR - user already has GOVERNOR + // role + @Test + public void updateRoleToSameRole() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ag1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = "GOVERNOR"; + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse()); + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from GOVERNOR to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + opsUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(governerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(governerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from Tester to GOVERNOR - 200 response + + // Admin Update user role from Designer to GOVERNOR - 200 response + @Test + public void updateUserRoleDesignerToGovernor() throws Exception { + DbUtils.cleanAllAudits(); + String httpCspUserId = "ah1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "DESIGNER"; + String updatedRole = "GOVERNOR"; + User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(designerUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(designerUser, createUserResponse.getResponse()); + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from TESTER to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + designerUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + // Update user role + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(governerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(governerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(designerUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update deactivated user role - response 404 (user not found) + @Test + public void updateRoleToDeactivatedUser() throws Exception { + DbUtils.cleanAllAudits(); + String httpCspUserId = "aj1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "DESIGNER"; + String updatedRole = "GOVERNOR"; + User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(designerUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(designerUser, createUserResponse.getResponse()); + deleteAndCheckUserResponse(designerUser, 200); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role - user deActivted + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + designerUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after create user", 404, updateUserRoleResponse.getErrorCode().intValue()); + } + + // Admin Update user role, user does not exist in DB - response 404 (user + // not found) + @Test + public void updateRoleForNonExistingUser() throws Exception { + DbUtils.cleanAllAudits(); + String httpCspUserId = "aj1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "DESIGNER"; + String updatedRole = "GOVERNOR"; + User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + // User governerUser = new User(userFirstName, + // userLastName,httpCspUserId, email, updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role - user deActivted + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + designerUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 404, updateUserRoleResponse.getErrorCode().intValue()); + + } + + // Admin Update user role from GOVERNOR to TESTER + @Test + public void updateRoleFromGovernorToTester() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ak1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = "TESTER"; + User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User testerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse()); + + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + governorUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(testerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(testerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from GOVERNOR to DESIGNER + @Test + public void updateRoleFromGovernorToDesigner() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ak1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = "DESIGNER"; + User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse()); + + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + governorUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(designerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(designerUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role from GOVERNOR to OPS + @Test + public void updateRoleFromGovernorToOps() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ak1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = "OPS"; + User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse()); + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + governorUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(opsUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(opsUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + deleteAndCheckUserResponse(governorUser, 200); + + } + + private void deleteAndCheckUserResponse(User userDetailes, int expectedResponseCode) throws IOException { + RestResponse deleteUser = UserRestUtils.deleteUser(sdncGovernorUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteUser); + assertEquals("Check response code after deleting user", expectedResponseCode, + deleteUser.getErrorCode().intValue()); + } + + // Admin Update user role from GOVERNOR to ADMIN + @Test + public void updateRoleFromGovernorToAdmin() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ak1000"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = "ADMIN"; + User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User adminUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse()); + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + governorUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue()); + + RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(adminUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(adminUser, getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role to non existing role - Response 400 Bad Request + @Test + public void updateRoleToNonExistingRole() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "al1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = "VVVVVVV"; + User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User newUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse()); + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role from OPS to GOVERNOR + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + governorUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 400, updateUserRoleResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating user", "Bad Request", + updateUserRoleResponse.getResponseMessage()); + + // RestResponse getUpdatedRoleUserResponse = + // UserRestUtils.getUser(adminUser,sdncAdminUser); + // UserValidationUtils.validateUserDetailsOnResponse(adminUser,getUpdatedRoleUserResponse.getResponse()); + // Delete OPS user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // Admin Update user role to null - Response 400 Bad Request + @Test + public void updateRoleToNull() throws Exception { + DbUtils.cleanAllAudits(); + + String httpCspUserId = "ax1001"; + String userFirstName = "Benny"; + String userLastName = "Tal"; + String email = "optBenny@intl.sdc.com"; + String role = "GOVERNOR"; + String updatedRole = ""; + User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + User newUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null); + // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true); + // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser); + RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser); + assertNotNull("check response object is not null after create user", createUserResponse); + assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode()); + assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse()); + // opsUser.setRole(updatedRole); + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // update user role + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + governorUser.getUserId()); + assertNotNull("check response object is not null after updating user", updateUserRoleResponse); + assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode()); + assertEquals("Check response code after updating user", 400, updateUserRoleResponse.getErrorCode().intValue()); + assertEquals("Check response code after updating user", "Bad Request", + updateUserRoleResponse.getResponseMessage()); + // Delete user + RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true); + assertNotNull("check response object is not null after deleting user", deleteOpsUser); + assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue()); + + } + + // create user with one optional parameter last name (UserID, Email, Last + // Name, Creator details) + // expected: role = DESIGNER, first name = null, 201 Created + // @Test + // public void createUserLastName(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // // create user with one optional parameter role name (UserID, Email, Role + // = "TESTER", Creator details) + // // expected: first and last name = null, 201 Created + // @Test + // public void createUserRoleName(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // // create user with two optional parameters first name and role (UserID, + // Email, First Name, Role = "ADMIN", Creator details) + // // expected: last name = null, 201 Created + // @Test + // public void createUserFirstNameAndRole(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // // create user with two optional parameters first and last name(UserID, + // Email, First Name, Last name, Creator details) + // // expected: role = DESIGNER, 201 Created + // @Test + // public void createUserFirstAndLastName(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // + // + // + // + // // + // **********************************************************Create*user*failed*************************************************** + // + // // + // **********************************************************403*************************************************** + // // create default user without creator details (UserID, Email) + // // expected: 403 Forbidden, error message:"Error : Missing information" + // @Test + // public void createDefaultUserNonCreatorDetails(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // + // // create user with part of creator details (UserID, Email, First name, + // Last Name, Role, Part of creator details) + // // expected: 403 Forbidden, error message:"Error : Missing information" + // @Test + // public void createUserPartOfCreatorDetails(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // // create user with full parameter set, non admin creator(UserID, First + // Name, Last Name, Email, Role, Creator details) + // // expected: 403 Forbidden, error message: + // "Error : Restricted operation" + // @Test + // public void createUserNonAdminCreator(){ + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // + // // + // **********************************************************405*************************************************** + // + // // create user with full parameter set by sending http PUT request + // (UserID, First Name, Last Name, Email, Role, Creator details) + // // expected: 405 not Allowed, error message: + // "Error : Method not allowed" + // @Test + // public void createUserPutRequest(){ + // // send PUT create user request + // // validate data on response + // // check the audit message + // } + // + // + // // create default user by sending http PUT request (UserID, Email, + // Creator details) + // // expected: 405 not Allowed, error message: + // "Error : Method not allowed" + // @Test + // public void createDefaultUserPutRequest(){ + // // send PUT create user request + // // validate data on response + // // check the audit message + // } + // + // + // // create user with full parameter set by sending http DELETE request + // (UserID, First Name, Last Name, Email, Role, Creator details) + // // expected: 405 not Allowed, error message: + // "Error : Method not allowed" + // @Test + // public void createUserDeleteRequest(){ + // // send DELETE create user request + // // validate data on response + // // check the audit message + // } + // + // + // // create default user by sending http DELETE request (UserID, Email, + // Creator details) + // // expected: 405 not Allowed, error message: + // "Error : Method not allowed" + // @Test + // public void createDefaultUserDeleteRequest(){ + // // send DELETE create user request + // // validate data on response + // // check the audit message + // } + // + // + // // create user with full parameter set by sending http GET request + // (UserID, First Name, Last Name, Email, Role, Creator details) + // // expected: 405 not Allowed, error message: + // "Error : Method not allowed" + // @Test + // public void createUserGetRequest(){ + // // send GET create user request + // // validate data on response + // // check the audit message + // } + // + // + // // create default user by sending http GET request (UserID, Email, + // Creator details) + // // expected: 405 not Allowed, error message: + // "Error : Method not allowed" + // @Test + // public void createDefaultUserGetRequest(){ + // // send GET create user request + // // validate data on response + // // check the audit message + // } + // + // + // // + // **********************************************************409*************************************************** + // + // // create the same user twice with full parameter set(UserID, First Name, + // Last Name, Email, Role, Creator details) + // // expected 409 Conflict, error message: + // "Error : User with '%s' ID already exists", where: %s - USER_ID + // @Test + // public void createSameUserTwice(){ + // // send POST create user request + // // validate data on response + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // // create user twice, first full details (UserID, First Name, Last Name, + // Email, Role, Creator details), second default user (UserID, Email, Role, + // Creator details) + // // expected 409 Conflict, error message: + // "Error : User with '%s' ID already exists", where: %s - USER_ID + // @Test + // public void createFullThanDefaultUserTwice(){ + // // send POST create user request + // + // // validate data on response + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // // create user twice, first default user (UserID, Email, Role, Creator + // details), second full details (UserID, First Name, Last Name, Email, + // Role, Creator details) + // // expected 409 Conflict, error message: + // "Error : User with '%s' ID already exists", where: %s - USER_ID + // @Test + // public void createDefaulThanFullUserTwice(){ + // // send POST create user request + // + // // validate data on response + // // send POST create user request + // // validate data on response + // // check the audit message + // } + // + // + // // + // **********************************************************400*************************************************** + // // create default user with invalid email address format(UserID, Email, + // Creator details) + // // expected: 400, error message: + // "Error : Invalid Content . Invalid e-mail address '%s'", where %s - + // email address + // @Test + // public void createDefaultUserInvalidEmailAddressFormat(){ + // // send GET create user request + // // validate data on response + // // check the audit message + // } + // + // // create an user with invalid role type (UserID, Email,Role = "TESTER-1" + // ,Creator details) + // // expected: 400, error message: + // "Error : Invalid Content . Invalid role '%s'", where %s - role type + // @Test + // public void createUserInvalidRoleType(){ + // // send GET create user request + // // validate data on response + // // check the audit message + // } + // + // // + // **********************************************************500*************************************************** + // // create default user when BE is down (UserID, Email, Creator details) + // // expected: 500, error message: + // "Error : Internal Server Error . Try later again." + // @Test + // public void createDefaultUserBeNoAccess(){ + // // send GET create user request + // // validate data on response + // // check the audit message + // } + // + + // Benny US570551 + + @Test + public void createProductManagerUser() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Man"; + String email = "prodMan@intl.sdc.com"; + String role = "PRODUCT_MANAGER"; + User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, true); + DbUtils.deleteFromEsDbByPattern("_all"); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse()); + // Audit validation + UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser, + Integer.toString(STATUS_CODE_SUCSESS_CREATED), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse()); + // Delete ProductManager user + RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, + true); + assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS, + deleteProductManagerUser.getErrorCode().intValue()); + } + + @Test + public void createProductStrategistUser() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodStr@intl.sdc.com"; + String role = "PRODUCT_STRATEGIST"; + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, true); + DbUtils.deleteFromEsDbByPattern("_all"); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser, + createUserResponse.getResponse()); + // Audit validation + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncAdminUser, + Integer.toString(STATUS_CODE_SUCSESS_CREATED), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser, getUserResponse.getResponse()); + // Delete ProductStrategist user + RestResponse deleteProductStrategistUser = UserRestUtils.deleteUser(expectedProductStrategistUser, + sdncAdminUser, true); + assertNotNull("Check response object is not null after deleting OPS user", deleteProductStrategistUser); + assertEquals("Check response code after deleting OPS user", 200, + deleteProductStrategistUser.getErrorCode().intValue()); + } + + @Test + public void createProductStrategistUserByNonAdminUser() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodStr@intl.sdc.com"; + String role = "PRODUCT_STRATEGIST"; + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, true); + DbUtils.deleteFromEsDbByPattern("_all"); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncDesignerUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_RESTRICTED_OPERATION, + createUserResponse.getErrorCode().intValue()); + // Audit validation + expectedProductStrategistUser.setUserId(""); + expectedProductStrategistUser.setFirstName(null); + expectedProductStrategistUser.setLastName(null); + expectedProductStrategistUser.setEmail(""); + expectedProductStrategistUser.setRole(""); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncDesignerUser, + Integer.toString(STATUS_CODE_RESTRICTED_OPERATION), errorInfo.getAuditDesc(""), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // Try to get user - user is not created + expectedProductStrategistUser.setUserId("pm1000"); + expectedProductStrategistUser.setFirstName("Prod"); + expectedProductStrategistUser.setLastName("Strategist"); + expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com"); + expectedProductStrategistUser.setRole("PRODUCT_STRATEGIST"); + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue()); + } + + @Test + public void createProductManagerUserByNonAdminUser() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Man"; + String email = "prodStr@intl.sdc.com"; + String role = "PRODUCT_MANAGER"; + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, true); + DbUtils.deleteFromEsDbByPattern("_all"); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncDesignerUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_RESTRICTED_OPERATION, + createUserResponse.getErrorCode().intValue()); + // Audit validation + expectedProductStrategistUser.setUserId(""); + expectedProductStrategistUser.setFirstName(null); + expectedProductStrategistUser.setLastName(null); + expectedProductStrategistUser.setEmail(""); + expectedProductStrategistUser.setRole(""); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncDesignerUser, + Integer.toString(STATUS_CODE_RESTRICTED_OPERATION), errorInfo.getAuditDesc(""), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // Try to get user - user is not created + expectedProductStrategistUser.setUserId("pm1000"); + expectedProductStrategistUser.setFirstName("Prod"); + expectedProductStrategistUser.setLastName("Strategist"); + expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com"); + expectedProductStrategistUser.setRole("PRODUCT_MANAGER"); + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue()); + } + + @Test + public void createProductStrategistUserByNonExistingUser() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodStr@intl.sdc.com"; + String role = "PRODUCT_STRATEGIST"; + User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + noSdncUserDetails.setRole("blabla"); + noSdncUserDetails.setUserId("bt750h"); + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + DbUtils.deleteFromEsDbByPattern("_all"); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, noSdncUserDetails); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_NOT_FOUND, + createUserResponse.getErrorCode().intValue()); + // Audit validation + expectedProductStrategistUser.setUserId(""); + expectedProductStrategistUser.setFirstName(null); + expectedProductStrategistUser.setLastName(null); + expectedProductStrategistUser.setEmail(""); + expectedProductStrategistUser.setRole(""); + noSdncUserDetails.setFirstName(""); + noSdncUserDetails.setLastName(""); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_NOT_FOUND.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, noSdncUserDetails, + Integer.toString(STATUS_CODE_NOT_FOUND), errorInfo.getAuditDesc(noSdncUserDetails.getUserId()), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // Try to get user - user is not created + expectedProductStrategistUser.setUserId("pm1000"); + expectedProductStrategistUser.setFirstName("Prod"); + expectedProductStrategistUser.setLastName("Strategist"); + expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com"); + expectedProductStrategistUser.setRole("PRODUCT_STRATEGIST"); + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue()); + } + + @Test + public void createProductManagerUserByNonExistingUser() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Man"; + String email = "prodStr@intl.sdc.com"; + String role = "PRODUCT_MANAGER"; + User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + noSdncUserDetails.setRole("blabla"); + noSdncUserDetails.setUserId("bt750h"); + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + DbUtils.deleteFromEsDbByPattern("_all"); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, noSdncUserDetails); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_NOT_FOUND, + createUserResponse.getErrorCode().intValue()); + // Audit validation + expectedProductStrategistUser.setUserId(""); + expectedProductStrategistUser.setFirstName(null); + expectedProductStrategistUser.setLastName(null); + expectedProductStrategistUser.setEmail(""); + expectedProductStrategistUser.setRole(""); + noSdncUserDetails.setFirstName(""); + noSdncUserDetails.setLastName(""); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_NOT_FOUND.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, noSdncUserDetails, + Integer.toString(STATUS_CODE_NOT_FOUND), errorInfo.getAuditDesc(noSdncUserDetails.getUserId()), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // Try to get user - user is not created + expectedProductStrategistUser.setUserId("pm1000"); + expectedProductStrategistUser.setFirstName("Prod"); + expectedProductStrategistUser.setLastName("Strategist"); + expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com"); + expectedProductStrategistUser.setRole("PRODUCT_MANAGER"); + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue()); + } + + @Test(enabled = false) + public void updateProjectManagerRole() throws Exception { + // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Man"; + String email = "prodMan@intl.sdc.com"; + String role = "PRODUCT_MANAGER"; + String updatedRole = "GOVERNOR"; + User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedProductManagerUser); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse()); + // Update user role + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + expectedProductManagerUser.getUserId()); + assertEquals("Check response code after create user", STATUS_CODE_SUCCESS, + updateUserRoleResponse.getErrorCode().intValue()); + expectedProductManagerUser.setRole(updatedRole); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, + updateUserRoleResponse.getResponse()); + // Audit validation + UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser, + Integer.toString(STATUS_CODE_SUCCESS), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("UpdateUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse()); + // Delete ProductManager user + RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, + true); + assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS, + deleteProductManagerUser.getErrorCode().intValue()); + } + + @Test(enabled = false) + public void updateProductStrategistRole() throws Exception { + // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodMan@intl.sdc.com"; + String role = "PRODUCT_STRATEGIST"; + String updatedRole = "TESTER"; + User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedProductManagerUser); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse()); + // Update user role + User newRoleUser = new User(); + newRoleUser.setRole(updatedRole); + // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + expectedProductManagerUser.getUserId()); + assertEquals("Check response code after create user", STATUS_CODE_SUCCESS, + updateUserRoleResponse.getErrorCode().intValue()); + expectedProductManagerUser.setRole(updatedRole); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, + updateUserRoleResponse.getResponse()); + // Audit validation + UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser, + Integer.toString(STATUS_CODE_SUCCESS), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(), + UserValidationUtils.getAddUserAuditMessage("UpdateUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse()); + // Delete ProductManager user + RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, + true); + assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS, + deleteProductManagerUser.getErrorCode().intValue()); + } + + @Test + public void createProductManagerUserAlreadyExit() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Man"; + String email = "prodMan@intl.sdc.com"; + String role = "PRODUCT_MANAGER"; + User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedProductManagerUser); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse()); + // create same user again + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse createUserAgainResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", USER_ALREADY_EXIST, + createUserAgainResponse.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_ALREADY_EXIST.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser, + Integer.toString(USER_ALREADY_EXIST), errorInfo.getAuditDesc(expectedProductManagerUser.getUserId()), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse()); + // Delete ProductManager user + RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, + true); + assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS, + deleteProductManagerUser.getErrorCode().intValue()); + } + + @Test + public void createProductStrategistUserAlreadyExit() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodMan@intl.sdc.com"; + String role = "PRODUCT_STRATEGIST"; + User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedProductManagerUser); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse()); + // create same user again + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse createUserAgainResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", USER_ALREADY_EXIST, + createUserAgainResponse.getErrorCode().intValue()); + // Audit validation + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_ALREADY_EXIST.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser, + Integer.toString(USER_ALREADY_EXIST), errorInfo.getAuditDesc(expectedProductManagerUser.getUserId()), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse()); + // Delete ProductManager user + RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, + true); + assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS, + deleteProductManagerUser.getErrorCode().intValue()); + } + + @Test(enabled = false) + public void UpdateProductStrategistToNonExistingRole() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodMan@intl.sdc.com"; + String role = "PRODUCT_STRATEGIST"; + String nonExistingRole = "BLABLA"; + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedProductStrategistUser); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED, + createUserResponse.getErrorCode().intValue()); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser, + createUserResponse.getResponse()); + // Update user Role to non Existing role + User newRoleUser = new User(); + newRoleUser.setRole(nonExistingRole); + DbUtils.deleteFromEsDbByPattern("_all"); + RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser, + expectedProductStrategistUser.getUserId()); + assertEquals("Check response code after updating user role", INVALID_ROLE, + updateUserRoleResponse.getErrorCode().intValue()); + + // Audit validation + /* + * expectedProductStrategistUser.setUserId(""); + * expectedProductStrategistUser.setFirstName(null); + * expectedProductStrategistUser.setLastName(null); + * expectedProductStrategistUser.setEmail(""); + * expectedProductStrategistUser.setRole(""); + */ + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_ROLE.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncAdminUser, + Integer.toString(INVALID_ROLE), errorInfo.getAuditDesc(nonExistingRole), + UserValidationUtils.getAddUserAuditMessage("UpdateUser")); + // get user and compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser, getUserResponse.getResponse()); + // Delete ProductManager user + RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, + true); + assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS, + deleteProductManagerUser.getErrorCode().intValue()); + } + + @Test(enabled = false) + public void createUserWithNonExistingRole() throws Exception { + String httpCspUserId = "pm1000"; + String userFirstName = "Prod"; + String userLastName = "Strategist"; + String email = "prodMan@intl.sdc.com"; + String role = "BLABLA"; + User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null); + deleteUserAndAudit(expectedProductStrategistUser); + // create user + RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check response code after create Product-Manager user", INVALID_ROLE, + createUserResponse.getErrorCode().intValue()); + + // Audit validation + /* + * expectedProductStrategistUser.setUserId(""); + * expectedProductStrategistUser.setFirstName(null); + * expectedProductStrategistUser.setLastName(null); + * expectedProductStrategistUser.setEmail(""); + * expectedProductStrategistUser.setRole(""); + */ + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_ROLE.name()); + UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncAdminUser, + Integer.toString(INVALID_ROLE), errorInfo.getAuditDesc(role), + UserValidationUtils.getAddUserAuditMessage("AddUser")); + // get user - verify user is not createdand compare with expected + RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser); + assertEquals("Check user not created", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue()); + + } + + private void deleteUserAndAudit(User sdncUserDetails) throws IOException { + UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true); + DbUtils.cleanAllAudits(); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java new file mode 100644 index 0000000000..5dd1abcf24 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java @@ -0,0 +1,319 @@ +/*- + * ============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.ci.tests.execute.user; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +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.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +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.ServiceValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class GovernorWorkspaceApiTest extends ComponentBaseTest { + + private static Logger logger = LoggerFactory.getLogger(GovernorWorkspaceApiTest.class.getName()); + @Rule + public static TestName name = new TestName(); + + public GovernorWorkspaceApiTest() { + super(name, GovernorWorkspaceApiTest.class.getName()); + + } + + protected final User admin1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + protected final User governor = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + protected final User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + protected ResourceReqDetails resourceDetails1; + protected ComponentInstanceReqDetails componentInstanceReqDetails; + protected ArtifactReqDetails heatArtifactDetails; + + protected final String serviceVersion = "0.1"; + protected final String servicesString = "services"; + protected final String userRemarks = "commentTest"; + + protected ServiceReqDetails serviceDetails11 = null; + protected ServiceReqDetails serviceDetails22 = null; + protected ServiceReqDetails serviceDetails33 = null; + + @BeforeMethod + public void initBeforeTest() throws Exception { + DbUtils.deleteFromEsDbByPattern("_all"); + Resource resourceObj = AtomicOperationUtils + .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetails1 = new ResourceReqDetails(resourceObj); + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + createThreeServices(sdncDesignerDetails1); + } + + protected void createThreeServices(User user) throws Exception { + + String checkinComment = "good checkin"; + String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}"; + + RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource( + heatArtifactDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId()); + RestResponse certifyResource = LifecycleRestUtils.certifyResource(resourceDetails1); + componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance("defaultInstance", resourceDetails1); + + serviceDetails11 = ElementFactory.getDefaultService(); + serviceDetails22 = ElementFactory.getDefaultService(); + serviceDetails33 = ElementFactory.getDefaultService(); + + serviceDetails11.setName(serviceDetails11.getName() + "1"); + List tags = serviceDetails11.getTags(); + tags.add(serviceDetails11.getName()); + serviceDetails11.setTags(tags); + + serviceDetails22.setName(serviceDetails11.getName() + "2"); + tags = serviceDetails22.getTags(); + tags.add(serviceDetails22.getName()); + serviceDetails22.setTags(tags); + + serviceDetails33.setName(serviceDetails11.getName() + "3"); + tags = serviceDetails33.getTags(); + tags.add(serviceDetails33.getName()); + serviceDetails33.setTags(tags); + + RestResponse createServiceResponse1 = createService(user, serviceDetails11); + RestResponse createServiceResponse2 = createService(user, serviceDetails22); + RestResponse createServiceResponse3 = createService(user, serviceDetails33); + } + + protected RestResponse createService(User user, ServiceReqDetails serviceDetails) throws Exception, IOException { + RestResponse createServiceResponse1 = ServiceRestUtils.createService(serviceDetails, user); + assertNotNull("check response object is not null after creating service", createServiceResponse1); + assertNotNull("check if error code exists in response after creating service", + createServiceResponse1.getErrorCode()); + assertEquals("Check response code after creating service", 201, + createServiceResponse1.getErrorCode().intValue()); + Service convertServiceResponseToJavaObject = ResponseParser + .convertServiceResponseToJavaObject(createServiceResponse1.getResponse()); + serviceDetails.setUniqueId(convertServiceResponseToJavaObject.getUniqueId()); + logger.debug("Created service1 ={}", serviceDetails); + addResourceWithHeatArt(serviceDetails); + return createServiceResponse1; + } + + protected void addResourceWithHeatArt(ServiceReqDetails serviceDetails) throws Exception { + + RestResponse createResourceInstance = ComponentInstanceRestUtils.createComponentInstance( + componentInstanceReqDetails, sdncDesignerDetails1, serviceDetails.getUniqueId(), + ComponentTypeEnum.SERVICE); + // System.out.println("serviceUID --->" + serviceDetails.getUniqueId()); + assertEquals("Check response code ", 201, createResourceInstance.getErrorCode().intValue()); + } + + protected void certifyAllServices() throws Exception { + LifecycleRestUtils.certifyService(serviceDetails11); + LifecycleRestUtils.certifyService(serviceDetails22); + LifecycleRestUtils.certifyService(serviceDetails33); + } + + protected boolean isElementInArray(String elementId, JSONArray jsonArray) throws Exception { + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jobject = (JSONObject) jsonArray.get(i); + + if (jobject.get("uniqueId").toString().equals(elementId)) { + return true; + } + } + return false; + } + + protected void approveDistributionStatusOfCertifiedService(ServiceReqDetails serviceDetails, User user) + throws Exception { + approveDistributionStatusOfService(serviceDetails, user, "1.0"); + } + + protected void approveDistributionStatusOfService(ServiceReqDetails serviceDetails, User user, String version) + throws Exception { + RestResponse res = LifecycleRestUtils.sendApproveDistribution(user, serviceDetails.getUniqueId(), userRemarks); + assertEquals(200, res.getErrorCode().intValue()); + ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_APPROVED); + } + + protected void rejectDistributionStatusOfService(ServiceReqDetails serviceDetails, User user) throws Exception { + rejectDistributionStatusOfService(serviceDetails, user, "1.0"); + } + + protected void rejectDistributionStatusOfService(ServiceReqDetails serviceDetails, User user, String version) + throws Exception { + RestResponse res = LifecycleRestUtils.rejectDistribution(serviceDetails, version, user, userRemarks); + assertEquals(200, res.getErrorCode().intValue()); + ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_REJECTED); + } + + protected JSONArray getFollowedListAsJsonArray(User user) throws Exception { + RestResponse getGovernorFollowed = ServiceRestUtils.getFollowed(user); + assertNotNull(getGovernorFollowed); + assertNotNull(getGovernorFollowed.getErrorCode()); + assertEquals(200, getGovernorFollowed.getErrorCode().intValue()); + + JSONArray listArrayFromRestResponse = ServiceRestUtils.getListArrayFromRestResponse(getGovernorFollowed); + + return listArrayFromRestResponse; + } + + protected void changeDistributionStatusOfAllService(boolean approved, User user) throws Exception { + if (approved) { + approveDistributionStatusOfCertifiedService(serviceDetails11, user); + approveDistributionStatusOfCertifiedService(serviceDetails22, user); + approveDistributionStatusOfCertifiedService(serviceDetails33, user); + } else { + rejectDistributionStatusOfService(serviceDetails11, user); + rejectDistributionStatusOfService(serviceDetails22, user); + rejectDistributionStatusOfService(serviceDetails33, user); + } + + } + + protected JSONArray checkFollowed(User user) throws Exception { + JSONArray getFollowedList = getFollowedListAsJsonArray(user); + assertFalse(getFollowedList.isEmpty()); + assertTrue(isElementInArray(serviceDetails11.getUniqueId(), getFollowedList)); + assertTrue(isElementInArray(serviceDetails22.getUniqueId(), getFollowedList)); + assertTrue(isElementInArray(serviceDetails33.getUniqueId(), getFollowedList)); + + return getFollowedList; + } + + // -------------------------------------T E S T + // S------------------------------------------------------// + + @Test + public void governorList_AllCertifiedVersionsOfService() throws Exception { + certifyAllServices(); + String serviceUniqueIdCertified1 = serviceDetails11.getUniqueId(); + RestResponse res = LifecycleRestUtils.changeServiceState(serviceDetails11, sdncDesignerDetails1, "1.0", + LifeCycleStatesEnum.CHECKOUT); + assertEquals(200, res.getErrorCode().intValue()); + + JSONArray getFollowedList = getFollowedListAsJsonArray(governor); + assertFalse(getFollowedList.isEmpty()); + assertFalse(isElementInArray(serviceDetails11.getUniqueId(), getFollowedList)); + assertTrue(isElementInArray(serviceDetails22.getUniqueId(), getFollowedList)); + assertTrue(isElementInArray(serviceDetails33.getUniqueId(), getFollowedList)); + assertTrue(isElementInArray(serviceUniqueIdCertified1, getFollowedList)); + assertEquals(3, getFollowedList.size()); + + // certifyService(serviceDetails11, "1.1"); + LifecycleRestUtils.certifyService(serviceDetails11); + + JSONArray governorFollowedList2 = checkFollowed(governor); + assertEquals(4, governorFollowedList2.size()); + assertTrue(isElementInArray(serviceDetails11.getUniqueId(), governorFollowedList2)); + assertTrue(isElementInArray(serviceUniqueIdCertified1, governorFollowedList2)); + + } + + // -------------------------------------T E S T + // S------------------------------------------------------// + + @Test + public void governorList_distributionNotApproved() throws Exception { + certifyAllServices(); + + JSONArray checkFollowed = checkFollowed(governor); + assertEquals(3, checkFollowed.size()); + } + + @Test + public void governorGetEmptyListTest_notCertifiedServices() throws Exception { + JSONArray governorFollowedList = getFollowedListAsJsonArray(governor); + + assertTrue(governorFollowedList.isEmpty()); + } + + @Test + public void governorList_distributionApproved() throws Exception { + certifyAllServices(); + boolean approved = true; + changeDistributionStatusOfAllService(approved, governor); + + JSONArray checkFollowed = checkFollowed(governor); + assertEquals(3, checkFollowed.size()); + } + + @Test(enabled = false) + public void governorList_distributed() throws Exception { + certifyAllServices(); + + LifecycleRestUtils.changeDistributionStatus(serviceDetails11, "1.0", governor, userRemarks, + DistributionStatusEnum.DISTRIBUTED); + LifecycleRestUtils.changeDistributionStatus(serviceDetails22, "1.0", governor, userRemarks, + DistributionStatusEnum.DISTRIBUTED); + LifecycleRestUtils.changeDistributionStatus(serviceDetails33, "1.0", governor, userRemarks, + DistributionStatusEnum.DISTRIBUTED); + + JSONArray governorFollowedList = getFollowedListAsJsonArray(governor); + assertFalse(governorFollowedList.isEmpty()); + assertTrue(isElementInArray(serviceDetails11.getUniqueId(), governorFollowedList)); + assertTrue(isElementInArray(serviceDetails22.getUniqueId(), governorFollowedList)); + assertTrue(isElementInArray(serviceDetails33.getUniqueId(), governorFollowedList)); + } + + @Test + public void governorList_distributionRejected() throws Exception { + certifyAllServices(); + boolean distributionRejected = false; + changeDistributionStatusOfAllService(distributionRejected, governor); + + JSONArray checkFollowed = checkFollowed(governor); + assertEquals(3, checkFollowed.size()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java new file mode 100644 index 0000000000..c80f6c612d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java @@ -0,0 +1,141 @@ +/*- + * ============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.ci.tests.executeOnUGN.distributionClient; + +import java.util.ArrayList; +import java.util.List; + +public class ClientConfiguration { + + private String asdcAddress; + private String user; + private String password; + private Integer pollingInterval; + private Integer pollingTimeout; + private List relevantArtifactTypes; + private String consumerGroup; + private String environmentName; + private String consumerID; + + public ClientConfiguration() { + + super(); + + this.asdcAddress = "localhost:8443"; + this.consumerID = "mso-123456"; + this.consumerGroup = "mso-group"; + this.environmentName = "PROD"; + this.password = "password"; + this.pollingInterval = 20; + this.pollingTimeout = 20; + this.relevantArtifactTypes = new ArrayList(); + this.relevantArtifactTypes.add("SHELL"); + this.user = "mso-user"; + } + + public String getAsdcAddress() { + return asdcAddress; + } + + public void setAsdcAddress(String asdcAddress) { + this.asdcAddress = asdcAddress; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public int getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public int getPollingTimeout() { + return pollingTimeout; + } + + public void setPollingTimeout(Integer pollingTimeout) { + this.pollingTimeout = pollingTimeout; + } + + public List getRelevantArtifactTypes() { + return relevantArtifactTypes; + } + + public void setRelevantArtifactTypes(List relevantArtifactTypes) { + this.relevantArtifactTypes = relevantArtifactTypes; + } + + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public String getEnvironmentName() { + return environmentName; + } + + public void setEnvironmentName(String environmentName) { + this.environmentName = environmentName; + } + + public String getComsumerID() { + return consumerID; + } + + public void setComsumerID(String comsumerID) { + this.consumerID = comsumerID; + } + + public ClientConfiguration(String asdcAddress, String user, String password, Integer pollingInterval, + Integer pollingTimeout, List relevantArtifactTypes, String consumerGroup, String environmentName, + String comsumerID) { + super(); + this.asdcAddress = asdcAddress; + this.user = user; + this.password = password; + this.pollingInterval = pollingInterval; + this.pollingTimeout = pollingTimeout; + this.relevantArtifactTypes = relevantArtifactTypes; + this.consumerGroup = consumerGroup; + this.environmentName = environmentName; + this.consumerID = comsumerID; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java new file mode 100644 index 0000000000..14c7a37101 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java @@ -0,0 +1,177 @@ +/*- + * ============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.ci.tests.preRequisites; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest; +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.ComponentInstanceRestUtils; +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.annotations.BeforeMethod; + +public class ComplexResourceBaseTest extends ComponentBaseTest { + + protected ServiceReqDetails serviceDetails; + protected ResourceReqDetails resourceDetailsVFC; + protected ResourceReqDetails resourceDetailsVL; + protected ResourceReqDetails resourceDetailsVF; + protected ResourceReqDetails resourceDetailsCP; + protected ComponentInstanceReqDetails resourceInstanceReqDetailsVF; + protected ComponentInstanceReqDetails resourceInstanceReqDetailsVFC; + protected ComponentInstanceReqDetails resourceInstanceReqDetailsVL; + protected ComponentInstanceReqDetails resourceInstanceReqDetailsCP; + protected User sdncDesignerDetails1; + protected User sdncTesterDeatails1; + protected User sdncAdminDetails1; + protected ArtifactReqDetails heatArtifactDetails; + + protected ArtifactReqDetails defaultArtifactDetails; + protected int maxLength = 50; + protected Resource resourceVF = null; + + @Rule + public static TestName name = new TestName(); + + public ComplexResourceBaseTest() { + super(name, ComplexResourceBaseTest.class.getName()); + } + + @BeforeMethod + public void before() throws Exception { + + initializeMembers(); + + createComponents(); + + } + + public void initializeMembers() throws IOException, Exception { + + serviceDetails = ElementFactory.getDefaultService(); + resourceDetailsVFC = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC, "resourceVFC"); + resourceDetailsVF = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, "resourceVF3"); + resourceDetailsVL = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VL, "resourceVL"); + resourceDetailsCP = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.CP, "resourceCP"); + sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + + } + + protected void createComponents() throws Exception { + + RestResponse response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId()); + + response = ResourceRestUtils.createResource(resourceDetailsVFC, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetailsVFC.getUniqueId()); + response = LifecycleRestUtils.changeResourceState(resourceDetailsVFC, sdncDesignerDetails1, + resourceDetailsVFC.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertTrue("change LS state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + response = ResourceRestUtils.createResource(resourceDetailsVF, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetailsVF.getUniqueId()); + + response = ResourceRestUtils.createResource(resourceDetailsCP, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetailsCP.getUniqueId()); + response = LifecycleRestUtils.changeResourceState(resourceDetailsCP, sdncDesignerDetails1, + resourceDetailsCP.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertTrue("change LS state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + response = ResourceRestUtils.createResource(resourceDetailsVL, sdncDesignerDetails1); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + assertNotNull("resource uniqueId is null:", resourceDetailsVL.getUniqueId()); + response = LifecycleRestUtils.changeResourceState(resourceDetailsVL, sdncDesignerDetails1, + resourceDetailsVL.getVersion(), LifeCycleStatesEnum.CHECKIN); + assertTrue("change LS state to CHECKIN, returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + resourceInstanceReqDetailsVFC = ElementFactory.getDefaultComponentInstance("VFC", resourceDetailsVFC); + resourceInstanceReqDetailsVF = ElementFactory.getDefaultComponentInstance("VF", resourceDetailsVF); + resourceInstanceReqDetailsVL = ElementFactory.getDefaultComponentInstance("VL", resourceDetailsVL); + resourceInstanceReqDetailsCP = ElementFactory.getDefaultComponentInstance("CP", resourceDetailsCP); + + } + + protected void createVFWithCertifiedResourceInstance(ResourceReqDetails resourceDetails, + ComponentInstanceReqDetails resourceInstanceReqDetails) throws Exception { + + RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails1, + resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); + assertEquals("Check response code after CHECKOUT", 200, response.getErrorCode().intValue()); + + // add heat artifact to resource and certify + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, + resourceDetails.getUniqueId()); + assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + response = LCSbaseTest.certifyResource(resourceDetails, sdncDesignerDetails1); + assertEquals("Check response code after CERTIFY request", 200, response.getErrorCode().intValue()); + + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + + resourceInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerDetails1, + resourceVF); + assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue()); + + resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF); + } + + protected Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException { + RestResponse response = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails1); + assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue()); + return ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java new file mode 100644 index 0000000000..bde68528bf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java @@ -0,0 +1,125 @@ +/*- + * ============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.ci.tests.preRequisites; + +import java.io.IOException; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest; +import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +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.ComponentInstanceRestUtils; +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.BeforeMethod; + +public class DownloadArtifactBaseTest extends ComponentBaseTest { + + protected ResourceReqDetails downloadResourceDetails; + protected ServiceReqDetails serviceDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails; + protected User sdncUserDetails; + protected User sdncDesignerDetails1; + protected ArtifactReqDetails heatArtifactDetails; + + protected ArtifactReqDetails defaultArtifactDetails; + protected ResourceUtils resourceUtils; + protected ArtifactUtils artifactUtils; + protected Service service; + + public DownloadArtifactBaseTest(TestName testName, String className) { + super(testName, className); + } + + @BeforeMethod + public void before() throws Exception { + + initializeMembers(); + createComponents(); + + } + + public void initializeMembers() throws IOException, Exception { + downloadResourceDetails = ElementFactory.getDefaultResource(); + serviceDetails = ElementFactory.getDefaultService(); + sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + + } + + protected void createComponents() throws Exception { + + RestResponse response = ResourceRestUtils.createResource(downloadResourceDetails, sdncUserDetails); + AssertJUnit.assertTrue("create request returned status:" + response.getErrorCode(), + response.getErrorCode() == 201); + AssertJUnit.assertNotNull("resource uniqueId is null:", downloadResourceDetails.getUniqueId()); + + ArtifactReqDetails heatArtifactDetails = ElementFactory + .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncUserDetails, + downloadResourceDetails.getUniqueId()); + AssertJUnit.assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + // certified resource + response = LCSbaseTest.certifyResource(downloadResourceDetails, sdncDesignerDetails1); + AssertJUnit.assertTrue("certify resource request returned status:" + response.getErrorCode(), + response.getErrorCode() == 200); + + response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + AssertJUnit.assertTrue("create request returned status:" + response.getErrorCode(), + response.getErrorCode() == 201); + AssertJUnit.assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId()); + + // add resource instance with HEAT deployment artifact to the service + resourceInstanceReqDetails.setComponentUid(downloadResourceDetails.getUniqueId()); + response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncUserDetails, + serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + AssertJUnit.assertTrue("response code is not 201, returned: " + response.getErrorCode(), + response.getErrorCode() == 201); + + response = ServiceRestUtils.getService(serviceDetails, sdncUserDetails); + AssertJUnit.assertTrue("response code is not 200, returned: " + response.getErrorCode(), + response.getErrorCode() == 200); + service = ResponseParser.convertServiceResponseToJavaObject(response.getResponse()); + + DbUtils.cleanAllAudits(); + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java new file mode 100644 index 0000000000..add06a587c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java @@ -0,0 +1,96 @@ +/*- + * ============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.ci.tests.preRequisites; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; + +import org.apache.log4j.lf5.util.ResourceUtils; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +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.ServiceRestUtils; +import org.testng.annotations.BeforeMethod; + +public abstract class SimpleOneRsrcOneServiceTest extends ComponentBaseTest { + + protected ResourceReqDetails resourceDetails; + protected ServiceReqDetails serviceDetails; + protected ComponentInstanceReqDetails resourceInstanceReqDetails; + protected ArtifactReqDetails heatArtifactDetails1; + + private static final String heatExtension = "yaml"; + private static final String yangXmlExtension = "xml"; + private static final String muranoPkgExtension = "zip"; + private static final String extension = null; + private final String folderName = "heatEnv"; + + protected User sdncDesignerDetails; + protected ArtifactReqDetails defaultArtifactDetails; + protected ResourceUtils resourceUtils; + protected ArtifactUtils artifactUtils; + protected Utils utils; + + private static RestResponse createServiceResponse; + + public SimpleOneRsrcOneServiceTest(TestName testName, String className) { + super(testName, className); + } + + @BeforeMethod + public void before() throws Exception { + + initializeMembers(); + createComponents(); + + } + + public void initializeMembers() throws IOException, Exception { + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + resourceDetails = ElementFactory.getDefaultResource(); + serviceDetails = ElementFactory.getDefaultService(); + heatArtifactDetails1 = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()); + resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance("resourceInstanceReqDetails"); + } + + protected void createComponents() throws Exception { + + RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + + response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails); + assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java new file mode 100644 index 0000000000..bb2d2d579b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java @@ -0,0 +1,82 @@ +/*- + * ============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.ci.tests.rules; + +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; +import org.openecomp.sdc.ci.tests.api.AttSdcTest; + +public class MyTestWatcher extends TestWatcher { + + AttSdcTest odlTest; + + public MyTestWatcher(AttSdcTest odlTest) { + this.odlTest = odlTest; + } + + /** + * Invoked when a test succeeds + * + * @param description + */ + @Override + protected void succeeded(Description description) { + String testName = description.getMethodName(); + odlTest.addTestSummary(testName, true); + + } + + /** + * Invoked when a test fails + * + * @param e + * @param description + */ + @Override + protected void failed(Throwable e, Description description) { + String testName = description.getMethodName(); + odlTest.addTestSummary(testName, false, e); + } + + /** + * Invoked when a test is about to start + * + * @param description + */ + @Override + protected void starting(Description description) { + // System.out.println("protected void starting(Description description) + // {"); + this.odlTest.getLogger().debug("Start running test {}", description.getMethodName()); + } + + /** + * Invoked when a test method finishes (whether passing or failing) + * + * @param description + */ + @Override + protected void finished(Description description) { + // System.out.println("protected void finished(Description description) + // {"); + this.odlTest.getLogger().debug("Finish running test {}", description.getMethodName()); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java new file mode 100644 index 0000000000..9bb14d7f50 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java @@ -0,0 +1,279 @@ +/*- + * ============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.ci.tests.run; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utils.Utils; +//import org.junit.runner.JUnitCore; +//import org.junit.runner.Result; +//import org.junit.runner.notification.Failure; +import org.testng.TestListenerAdapter; +import org.testng.TestNG; +import org.testng.reporters.TestHTMLReporter; +import org.testng.xml.XmlSuite; + +public class StartTest { + + // private List> testClasses = new + // ArrayList>(); + public static long timeOfTest = 0; + + public static boolean debug = false; + + public static AtomicBoolean loggerInitialized = new AtomicBoolean(false); + + protected static Logger logger = null; + + public static void main(String[] args) { + + String debugEnabled = System.getProperty("debug"); + if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) { + debug = true; + } + System.out.println("Debug mode is " + (debug ? "enabled" : "disabled")); + + enableLogger(); + + Config config = null; + try { + config = Utils.getConfig(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if (config == null) { + logger.error("Failed to configuration file of ci tests."); + System.exit(1); + } + + TestNG testng = new TestNG(); + + List suites = new ArrayList(); + suites.add("testSuites/" + args[0]); + testng.setTestSuites(suites); + testng.setUseDefaultListeners(true); + testng.setOutputDirectory("target/"); + + testng.run(); + + } + + public StartTest() { + logger = Logger.getLogger(StartTest.class.getName()); + } + + public static void enableLogger() { + + if (false == loggerInitialized.get()) { + + loggerInitialized.set(true); + + String log4jPropsFile = System.getProperty("log4j.configuration"); + if (System.getProperty("os.name").contains("Windows")) { + String logProps = "src/main/resources/ci/conf/log4j.properties"; + if (log4jPropsFile == null) { + System.setProperty("targetlog", "target/"); + log4jPropsFile = logProps; + } + + } + PropertyConfigurator.configureAndWatch(log4jPropsFile); + + } + } + + private List getClassesForPackage(String pkgname) { + + List classes = new ArrayList(); + + // Get a File object for the package + File directory = null; + String fullPath; + String relPath = pkgname.replace('.', '/'); + + // System.out.println("ClassDiscovery: Package: " + pkgname + + // " becomes Path:" + relPath); + + URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); + + // System.out.println("ClassDiscovery: Resource = " + resource); + if (resource == null) { + throw new RuntimeException("No resource for " + relPath); + } + fullPath = resource.getFile(); + // System.out.println("ClassDiscovery: FullPath = " + resource); + + if (debug) { + System.out.println("fullPath is " + fullPath); + } + + try { + directory = new File(resource.toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException( + pkgname + " (" + resource + + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", + e); + } catch (IllegalArgumentException e) { + directory = null; + } + // System.out.println("ClassDiscovery: Directory = " + directory); + + if (directory != null && directory.exists()) { + + // Get the list of the files contained in the package + String[] files = directory.list(); + for (int i = 0; i < files.length; i++) { + + // we are only interested in .class files + if (files[i].endsWith(".class") && false == files[i].contains("$")) { + + // removes the .class extension + String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); + + // System.out.println("ClassDiscovery: className = " + + // className); + + if (debug) { + System.out.println("ClassDiscovery: className = " + className); + } + + try { + Class clas = Class.forName(className); + boolean isAddToRun = false; + Method[] methods = clas.getMethods(); + for (Method method : methods) { + Annotation[] anns = method.getAnnotations(); + for (Annotation an : anns) { + if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) { + isAddToRun = true; + break; + } + } + } + if (isAddToRun) + classes.add(clas); + } catch (ClassNotFoundException e) { + throw new RuntimeException("ClassNotFoundException loading " + className); + } + } + } + } else { + try { + String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); + + if (debug) { + System.out.println("jarPath is " + jarPath); + } + + JarFile jarFile = new JarFile(jarPath); + Enumeration entries = jarFile.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) { + + // System.out.println("ClassDiscovery: JarEntry: " + + // entryName); + String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); + + // System.out.println("ClassDiscovery: className = " + + // className); + + if (false == className.contains("$")) { + + if (debug) { + System.out.println("ClassDiscovery: className = " + className); + } + + try { + Class clas = Class.forName(className); + boolean isAddToRun = false; + Method[] methods = clas.getMethods(); + for (Method method : methods) { + Annotation[] anns = method.getAnnotations(); + for (Annotation an : anns) { + if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) { + isAddToRun = true; + break; + } + } + } + if (isAddToRun) + classes.add(clas); + } catch (ClassNotFoundException e) { + throw new RuntimeException("ClassNotFoundException loading " + className); + } + } + } + } + jarFile.close(); + + } catch (IOException e) { + throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); + } + } + return classes; + } + + private void addTableHead(StringBuilder results) { + results.append("
"); + results.append(""); + results.append(""); + results.append(""); + } + + // private void addUnitTestResult(StringBuilder results, + // Class testClass, Result unitTestResult) { + // + // boolean isSuccess = unitTestResult.wasSuccessful(); + // + // String result = (isSuccess) ? "success" : "fail"; + // String fileName = FileUtils.getFileName(testClass.getName()); + // results.append(""); + // // + // results.append(""); + // results.append(""); + // results.append(""); + // results.append(""); + // } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java new file mode 100644 index 0000000000..d5b06b396f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java @@ -0,0 +1,408 @@ +/*- + * ============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.ci.tests.run; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.net.URL; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.apache.log4j.PropertyConfigurator; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.openecomp.sdc.ci.tests.api.AttSdcTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StartTest2backup { + + private List> testClasses = new ArrayList>(); + public static long timeOfTest = 0; + + public static boolean debug = false; + + public static AtomicBoolean loggerInitialized = new AtomicBoolean(false); + + protected static Logger logger = null; + + public static void main(String[] args) { + + String debugEnabled = System.getProperty("debug"); + if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) { + debug = true; + } + System.out.println("Debug mode is " + (debug ? "enabled" : "disabled")); + + enableLogger(); + + Config config = null; + try { + config = Utils.getConfig(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if (config == null) { + logger.error("Failed to configuration file of ci tests."); + System.exit(1); + } + + List packagesToRun = config.getPackages(); + if (packagesToRun == null || true == packagesToRun.isEmpty()) { + logger.error("No package was configured to be executed."); + System.exit(2); + } + StartTest2backup tests = new StartTest2backup(); + + boolean stopOnClassFailure = false; + String stopOnClassFailureStr = System.getProperty("stopOnClassFailure"); + if (stopOnClassFailureStr != null && stopOnClassFailureStr.equalsIgnoreCase("true")) { + stopOnClassFailure = true; + } else { + Boolean stopOnClassFailureObj = config.isStopOnClassFailure(); + if (stopOnClassFailureObj != null) { + stopOnClassFailure = stopOnClassFailureObj.booleanValue(); + } + } + + tests.start(packagesToRun, stopOnClassFailure); + } + + public StartTest2backup() { + logger = LoggerFactory.getLogger(StartTest2backup.class.getName()); + } + + public static void enableLogger() { + + if (false == loggerInitialized.get()) { + + loggerInitialized.set(true); + + String log4jPropsFile = System.getProperty("log4j.configuration"); + if (System.getProperty("os.name").contains("Windows")) { + String logProps = "src/main/resources/ci/conf/log4j.properties"; + if (log4jPropsFile == null) { + System.setProperty("targetlog", "target/"); + log4jPropsFile = logProps; + } + + } + PropertyConfigurator.configureAndWatch(log4jPropsFile); + + } + } + + public void start(List packages, boolean exitOnFailure) { + + boolean success = true; + StringBuilder results = new StringBuilder(); + Result result; + + if (packages == null) { + return; + } + + for (String packageName : packages) { + // List classesForPackage = + // getClassesForPackage("org.openecomp.sdc.ci.tests.execute"); + List classesForPackage = getClassesForPackage(packageName); + if (classesForPackage != null && false == classesForPackage.isEmpty()) { + for (Class testUnit : classesForPackage) { + testClasses.add(testUnit); + } + } + } + + System.out.println(testClasses); + + // tsetClasses.add(LogValidatorTest.class); + // tsetClasses.add(AttNorthboundTest.class); + + results.append( + ""); + + Calendar calendar = Calendar.getInstance(); + timeOfTest = calendar.getTimeInMillis(); + SimpleDateFormat date_format = new SimpleDateFormat("MMM dd yyyy HH:mm:ss"); + results.append("

This report generated on " + date_format.format(calendar.getTime()) + "


"); + + results.append("
").append(testName).append("").append(result).append("").append(message).append("").append(convertExceptionToString(exception)).append(""); + + doc.append(""); + doc.append("
"); + + doc.append(convertExceptionToString(exception)); + + doc.append("
"); + doc.append("
").append("Unit Test").append("").append("Result").append("
").append(FileUtils.getFileName(testClass.getName())).append("") + // .append("" + // + fileName + "").append("").append(result) + // .append("
"); + addTableHead(results); + + int size = testClasses.size(); + int index = 0; + + int totalRunTests = 0; + int totalFailureTests = 0; + int totalIgnoreTests = 0; + int numOfFailureClasses = 0; + for (Class testClass : testClasses) { + + index++; + + StringBuilder builder = new StringBuilder(); + String str = "***************************************************************************"; + builder.append(str + "\n"); + String current = "class " + index + "/" + size + " failure(" + numOfFailureClasses + ") + RUNS(" + + totalRunTests + ")" + " FAILURES(" + totalFailureTests + ") IGNORED(" + totalIgnoreTests + ")"; + int interval = ((str.length() - current.length() - 2) / 2); + String substring = str.substring(0, interval); + builder.append(substring + " " + current + " " + substring + "\n"); + builder.append(str + "\n"); + + System.out.println(builder.toString()); + + logger.debug(builder.toString()); + logger.debug("Going to run test class {}", testClass.getName()); + + result = JUnitCore.runClasses(testClass); + if (result.wasSuccessful() == false) { + numOfFailureClasses++; + } + logger.debug("Test class {} finished {}",testClass.getName(),(result.wasSuccessful() ? "OK." : " WITH ERROR.")); + List failures = result.getFailures(); + if (failures != null) { + for (Failure failure : failures) { + logger.error("Test class {} failure test {}-{}",testClass.getName(),failure.getTestHeader(),failure.getTrace()); + } + } + int runsPerClass = result.getRunCount(); + int failuresPerClass = result.getFailureCount(); + int ignoredPerClass = result.getIgnoreCount(); + + totalRunTests += runsPerClass; + totalFailureTests += failuresPerClass; + totalIgnoreTests += ignoredPerClass; + + logger.debug("class {} Failed tests {} %",testClass.getName(),(failuresPerClass * 1.0) / runsPerClass * 100); + logger.debug("class {} Ignored tests {} %",testClass.getName(),(ignoredPerClass * 1.0) / runsPerClass * 100); + + // List failures = result.getFailures(); + // if (failures != null) { + // for (Failure failure : failures) { + // System.err.println("9999999999" + failure.getTestHeader()); + // } + // } + + addUnitTestResult(results, testClass, result); + success &= result.wasSuccessful(); + + if (numOfFailureClasses > 0) { + // if (exitOnFailure) { + if (exitOnFailure) { + break; + } + } + } + + results.append("
"); + results.append("

Tests Summary:


"); + results.append("Total Runs : " + totalRunTests + "
"); + results.append("Total Failure : " + totalFailureTests + "
"); + results.append("Total: " + totalFailureTests + "/" + totalRunTests + "
"); + results.append(""); + + FileUtils.writeToFile(Config.instance().getOutputFolder() + File.separator + Config.instance().getReportName(), + results.toString()); + + if (!success) { + System.out.println("FAILURE"); + logger.error("Failure tests : {} %",((totalFailureTests + totalIgnoreTests) * 1.0) / (totalRunTests + totalIgnoreTests)); + logger.error("Ignored tests : {} %",(totalIgnoreTests * 1.0) / (totalRunTests + totalIgnoreTests)); + System.exit(1); + } + + System.out.println("SUCCESS"); + } + + private List getClassesForPackage(String pkgname) { + + List classes = new ArrayList(); + + // Get a File object for the package + File directory = null; + String fullPath; + String relPath = pkgname.replace('.', '/'); + + // System.out.println("ClassDiscovery: Package: " + pkgname + + // " becomes Path:" + relPath); + + URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); + + // System.out.println("ClassDiscovery: Resource = " + resource); + if (resource == null) { + throw new RuntimeException("No resource for " + relPath); + } + fullPath = resource.getFile(); + // System.out.println("ClassDiscovery: FullPath = " + resource); + + if (debug) { + System.out.println("fullPath is " + fullPath); + } + + try { + directory = new File(resource.toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException( + pkgname + " (" + resource + + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", + e); + } catch (IllegalArgumentException e) { + directory = null; + } + // System.out.println("ClassDiscovery: Directory = " + directory); + + if (directory != null && directory.exists()) { + + // Get the list of the files contained in the package + String[] files = directory.list(); + for (int i = 0; i < files.length; i++) { + + // we are only interested in .class files + if (files[i].endsWith(".class") && false == files[i].contains("$")) { + + // removes the .class extension + String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); + + // System.out.println("ClassDiscovery: className = " + + // className); + + if (debug) { + System.out.println("ClassDiscovery: className = " + className); + } + + try { + Class clas = Class.forName(className); + boolean isAddToRun = false; + Method[] methods = clas.getMethods(); + for (Method method : methods) { + Annotation[] anns = method.getAnnotations(); + for (Annotation an : anns) { + if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) { + isAddToRun = true; + break; + } + } + } + if (isAddToRun) + classes.add(clas); + } catch (ClassNotFoundException e) { + throw new RuntimeException("ClassNotFoundException loading " + className); + } + } + } + } else { + try { + String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); + + if (debug) { + System.out.println("jarPath is " + jarPath); + } + + JarFile jarFile = new JarFile(jarPath); + Enumeration entries = jarFile.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) { + + // System.out.println("ClassDiscovery: JarEntry: " + + // entryName); + String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); + + // System.out.println("ClassDiscovery: className = " + + // className); + + if (false == className.contains("$")) { + + if (debug) { + System.out.println("ClassDiscovery: className = " + className); + } + + try { + Class clas = Class.forName(className); + boolean isAddToRun = false; + Method[] methods = clas.getMethods(); + for (Method method : methods) { + Annotation[] anns = method.getAnnotations(); + for (Annotation an : anns) { + if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) { + isAddToRun = true; + break; + } + } + } + if (isAddToRun) + classes.add(clas); + } catch (ClassNotFoundException e) { + throw new RuntimeException("ClassNotFoundException loading " + className); + } + } + } + } + jarFile.close(); + + } catch (IOException e) { + throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); + } + } + return classes; + } + + private void addTableHead(StringBuilder results) { + results.append(""); + results.append("").append("Unit Test").append(""); + results.append("").append("Result").append(""); + results.append(""); + } + + private void addUnitTestResult(StringBuilder results, Class testClass, + Result unitTestResult) { + + boolean isSuccess = unitTestResult.wasSuccessful(); + + String result = (isSuccess) ? "success" : "fail"; + String fileName = FileUtils.getFileName(testClass.getName()); + results.append(""); + // results.append("").append(FileUtils.getFileName(testClass.getName())).append(""); + results.append("") + .append("" + fileName + "").append(""); + results.append("").append(result).append(""); + results.append(""); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java new file mode 100644 index 0000000000..b676b29bda --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java @@ -0,0 +1,287 @@ +/*- + * ============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.ci.tests.sanity; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +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.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.AssocType; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.AtomicOperationUtils; +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.validation.ErrorValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +import fj.data.Either; + +public class CrudE2E extends ComponentBaseTest { + private static Logger log = LoggerFactory.getLogger(CrudE2E.class.getName()); + + public Component resourceDetailsVFCcomp_01; + public Component resourceDetailsVFCsoft_01; + public Component resourceDetailsCP_01; + public Component resourceDetailsVL_01; + public Component resourceDetailsVF_01; + public Component resourceDetailsVF_02; + + public ComponentInstance resourceDetailsVFC1compIns1; + public ComponentInstance resourceDetailsVFC1softIns1; + public ComponentInstance resourceDetailsCP1ins_01; + public ComponentInstance resourceDetailsVL1ins_01; + public ComponentInstance resourceDetailsVF1ins_01; + public Component defaultService1; + private List variablesAsList = new ArrayList(); + + @Rule + public static TestName name = new TestName(); + + public CrudE2E() { + super(name, CrudE2E.class.getName()); + } + + @Test + public void complexScenario() throws Exception { + + User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + //////// create defaultService1 /////////////////////// + + Either createDefaultService1e = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + defaultService1 = createDefaultService1e.left().value(); + + //////// create VFC1 (resourceDetailsVFCcomp_01) DerivedFrom COMPUTE + //////// type add all possible informational artifacts and change state + //////// to CERTIFY//////// + Either resourceDetailsVFCcompE = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, + true); + resourceDetailsVFCcomp_01 = resourceDetailsVFCcompE.left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.CHEF, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.PUPPET, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.SHELL_SCRIPT, + // resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, + // resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.DG_XML, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MURANO_PKG, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + + //////// create VFC2 (resourceDetailsVFCsoft_01) DerivedFrom SOFTWARE + //////// type and change state to CERTIFY//////// + Either resourceDetailsVFCsoftE = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, + true); + resourceDetailsVFCsoft_01 = resourceDetailsVFCsoftE.left().value(); + AtomicOperationUtils.changeComponentState(resourceDetailsVFCsoft_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + + //////// create CP1 (resourceDetailsVFCsoft_01) DerivedFrom PORT type + //////// and change state to CHECKIN//////// + Either resourceDetailsCP_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true); + resourceDetailsCP_01 = resourceDetailsCP_01e.left().value(); + AtomicOperationUtils.changeComponentState(resourceDetailsCP_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + + //////// create VL1 (resourceDetailsVFCsoft_01) DerivedFrom NETWORK type + //////// and change state to CERTIFY//////// + Either resourceDetailsVL_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VL, NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, + true); + resourceDetailsVL_01 = resourceDetailsVL_01e.left().value(); + AtomicOperationUtils.changeComponentState(resourceDetailsVL_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + + //////// create VF1 (resourceDetailsVFCcomp_01) DerivedFrom COMPUTE type + //////// add all possible deployment and informational artifacts + //////// ////////// + Either resourceDetailsVF_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetailsVF_01 = resourceDetailsVF_01e.left().value(); + ArtifactDefinition heatArtifact = AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_NET, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true); + + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.CHEF, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.PUPPET, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.SHELL_SCRIPT, + // resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, + // resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.DG_XML, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MURANO_PKG, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVF_01, UserRoleEnum.DESIGNER, false, true); + + //////// Add VFC1 VFC2 CP and VL to VF container ///////////// + resourceDetailsVFC1compIns1 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetailsVFC1softIns1 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCsoft_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetailsCP1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsCP_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true).left().value(); + resourceDetailsVL1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVL_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true).left().value(); + + //////// associate cp-vl vl-vfcComp and vfcComp-vfcSoft//////// + resourceDetailsVF_01 = AtomicOperationUtils.getResourceObject(resourceDetailsVF_01, UserRoleEnum.DESIGNER); + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01, resourceDetailsVL1ins_01, AssocType.LINKABLE.getAssocType(), UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01, resourceDetailsVFC1compIns1, AssocType.BINDABLE.getAssocType(), UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsVFC1compIns1, resourceDetailsVFC1softIns1, AssocType.NODE.getAssocType(), UserRoleEnum.DESIGNER, true); + + //////// download all VF1 artifacts//////// + + Collection artifacts = resourceDetailsVF_01.getDeploymentArtifacts().values(); + List collect = artifacts.stream().filter(p -> p.checkEsIdExist() == true).map(p -> p.getUniqueId()).collect(Collectors.toList()); + artifacts.stream().filter(p -> p.checkEsIdExist() == true).map(p -> p.getUniqueId()).forEach(item -> log.debug(item)); + + //////// get all VF1 artifacts//////// + + Collection> componentInstancesProperties = resourceDetailsVF_01.getComponentInstancesProperties().values(); + List collect2 = componentInstancesProperties.stream().filter(p -> p.isEmpty() == false).flatMap(l -> l.stream()).collect(Collectors.toList()).stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); + // PropertyRestUtils.updateProperty(resourceDetailsVF_01.getUniqueId(), + // propertyId, "1", designer); + // .forEach((someOtherString) -> { + // System.out.println("Content With Java: " + someOtherString); + // }); + // componentInstancesProperties.stream().filter(p -> + // p.isEmpty()==false).flatMap(l -> l.stream()).map(e -> + // e.getUniqueId()); + // resourceDetailsVF_01.getComponentInstancesProperties(). + + // ArtifactDefinition artifactDefinition = + // resourceDetailsVF_01.getDeploymentArtifacts().get(ArtifactTypeEnum.HEAT.getType().toLowerCase()).getEsId(); + // ArtifactDefinition artifactDefinition = + // resource.getDeploymentArtifacts().get(depResArtType); + // ArtifactReqDetails artifacJavaObject = + // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifactDefinition); + // ArtifactRestUtils.updateDeploymentArtifactToRI(artifactDetails, + // sdncModifierDetails, resourceInstanceId, serviceId) + + //////// certify VF1 - failed due to uncertified CP instance //////// + + RestResponse changeVfStateFailed = LifecycleRestUtils.changeComponentState(resourceDetailsVF_01, designer, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + Resource resResourceDetailsVF_01 = (Resource) resourceDetailsVF_01; + variablesAsList = Arrays.asList(resResourceDetailsVF_01.getResourceType().toString(), resourceDetailsCP_01.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name(), variablesAsList, changeVfStateFailed.getResponse()); + + //////// certify resources CP1 //////// + resourceDetailsCP_01 = AtomicOperationUtils.changeComponentState(resourceDetailsCP_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //////// replace VF1 instances with new certified instances (CP1 + //////// replaced) //////// + Either, RestResponse> changeComponentInstanceVersion = AtomicOperationUtils.changeComponentInstanceVersion(resourceDetailsVF_01, resourceDetailsCP1ins_01, resourceDetailsCP_01, UserRoleEnum.DESIGNER, true); + resourceDetailsVF_01 = changeComponentInstanceVersion.left().value().getLeft(); + resourceDetailsCP1ins_01 = changeComponentInstanceVersion.left().value().getRight(); + + //////// associate cp-vl and cp-vfc1,//////// + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01, resourceDetailsVL1ins_01, AssocType.LINKABLE.getAssocType(), UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01, resourceDetailsVFC1compIns1, AssocType.BINDABLE.getAssocType(), UserRoleEnum.DESIGNER, true); + + /////// change VF1 state to CHECK-IN and add it as instance to service1 + /////// container + resourceDetailsVF_01 = AtomicOperationUtils.changeComponentState(resourceDetailsVF_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resourceDetailsVF1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVF_01, defaultService1, UserRoleEnum.DESIGNER, true).left().value(); + + //////// distribute service1 - failed due to incorrect LifeCyclestatus + //////// //////// + RestResponse distributeService = AtomicOperationUtils.distributeService(defaultService1, false); + Assert.assertEquals(distributeService, null, "verification failed"); + + //////// certify service1 - failed due to uncertified instances //////// + designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + RestResponse changeServicetStateFailed = LifecycleRestUtils.changeComponentState(defaultService1, designer, LifeCycleStatesEnum.CERTIFICATIONREQUEST); + variablesAsList = Arrays.asList(defaultService1.getComponentType().toString().toLowerCase(), resourceDetailsVF_01.getName()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name(), variablesAsList, changeServicetStateFailed.getResponse()); + + ////// change VF1 state to CERTIFIED + resourceDetailsVF_01 = AtomicOperationUtils.changeComponentState(resourceDetailsVF_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //////// replace VF1 instances with new certified instances //////// + changeComponentInstanceVersion = AtomicOperationUtils.changeComponentInstanceVersion(defaultService1, resourceDetailsVF1ins_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true); + resourceDetailsVF_01 = changeComponentInstanceVersion.left().value().getLeft(); + resourceDetailsVFC1compIns1 = changeComponentInstanceVersion.left().value().getRight(); + + /////// certify service1 //////// + defaultService1 = AtomicOperationUtils.changeComponentState(defaultService1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //////// distribute service1 - successfully //////// + AtomicOperationUtils.distributeService(defaultService1, true); + + /////// create VF2 //////// + + Either resourceDetailsVF_02e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetailsVF_02 = resourceDetailsVF_02e.left().value(); + + } + + // private void updateArtParameterInResource(Resource resource) throws + // IOException { + // + // ArtifactRestUtils.uploadArtifact(artifactDetails, component, + // sdncModifierDetails) + // + // for (String depResArtType : Utils.getListOfDepResArtLabels(true)) { + // ArtifactDefinition artifactDefinition = + // resource.getDeploymentArtifacts().get(depResArtType); + // ArtifactReqDetails artifacJavaObject = + // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifactDefinition); + // + // //update parameter + // List resourceHeatParameters = + // resource.getDeploymentArtifacts().get(depResArtType).getHeatParameters(); + // for (HeatParameterDefinition heatParameterDefinition : + // resourceHeatParameters){ + // if (heatParameterDefinition.getName().equals("address")){ + // heatParameterDefinition.setCurrentValue("negev"); + // break; + // } + // } + // artifacJavaObject.setHeatParameters(resourceHeatParameters); + // artifacJavaObject.setPayloadData(null); + // RestResponse updateInformationalArtifactToResource = + // ArtifactRestUtils.updateDeploymentArtifactToResource(artifacJavaObject, + // sdncDesignerDetails, resource.getUniqueId()); + // assertTrue("response code is not 200, returned: " + + // updateInformationalArtifactToResource.getErrorCode(),updateInformationalArtifactToResource.getErrorCode() + // == 200); + // } + // } + +} 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 new file mode 100644 index 0000000000..0a7b4a98aa --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java @@ -0,0 +1,131 @@ +/*- + * ============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.ci.tests.sanity; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.AssocType; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.testng.annotations.Test; +import static org.testng.AssertJUnit.assertTrue; + +public class MultipleResourceUpdate extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public MultipleResourceUpdate() { + super(name, MultipleResourceUpdate.class.getName()); + } + + @Test + public void simpleScenario() throws Exception { + + // Creating VF and Resource instances + Resource vf = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left() + .value(); + Resource cp1 = AtomicOperationUtils + .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.PORT, + ResourceCategoryEnum.NETWORK_CONNECTIVITY_CON_POINT, UserRoleEnum.DESIGNER, true) + .left().value(); + Resource cp2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true) + .left().value(); + Resource vl = AtomicOperationUtils + .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VL, NormativeTypesEnum.NETWORK, + ResourceCategoryEnum.NETWORK_CONNECTIVITY_VIRTUAL_LINK, UserRoleEnum.DESIGNER, true) + .left().value(); + + vf.getCreatorUserId(); + + // Check In Resources + AtomicOperationUtils.changeComponentState(cp1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + AtomicOperationUtils.changeComponentState(cp2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + AtomicOperationUtils.changeComponentState(vl, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + + // CheckIn all other except VF + ComponentInstance instanceCP1 = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp1, vf, UserRoleEnum.DESIGNER, true).left().value(); + ComponentInstance instanceVL = AtomicOperationUtils + .addComponentInstanceToComponentContainer(vl, vf, UserRoleEnum.DESIGNER, true).left().value(); + ComponentInstance instanceCP2 = AtomicOperationUtils + .addComponentInstanceToComponentContainer(cp2, vf, UserRoleEnum.DESIGNER, true).left().value(); + + vf = (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER); + + // Create Vertex(Link/Associate 2 Resource Instances on Canvas) + AtomicOperationUtils.associate2ResourceInstances(vf, instanceCP1, instanceVL, AssocType.LINKABLE.getAssocType(), + UserRoleEnum.DESIGNER, true); + + List componentInstanceReqDetailsList = new ArrayList<>(); + componentInstanceReqDetailsList.add(new ComponentInstanceReqDetails(instanceCP1)); + componentInstanceReqDetailsList.add(new ComponentInstanceReqDetails(instanceCP2)); + componentInstanceReqDetailsList.add(new ComponentInstanceReqDetails(instanceVL)); + + ComponentInstanceReqDetails compInstDet = componentInstanceReqDetailsList.get(0); + compInstDet.setPosX("150"); + compInstDet.setPosY("150"); + compInstDet = componentInstanceReqDetailsList.get(1); + compInstDet.setPosX("400"); + compInstDet.setPosY("150"); + compInstDet = componentInstanceReqDetailsList.get(2); + compInstDet.setPosX("150"); + compInstDet.setPosY("300"); + + RestResponse response = ComponentInstanceRestUtils.updateMultipleComponentInstance( + componentInstanceReqDetailsList, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), vf.getUniqueId(), + vf.getComponentType()); + assertTrue("response code is not 200, returned: " + response.getErrorCode(), + response.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); + + compInstDet = componentInstanceReqDetailsList.get(0); + compInstDet.setPosX("350"); + compInstDet.setPosY("350"); + compInstDet = componentInstanceReqDetailsList.get(1); + compInstDet.setPosX("600"); + compInstDet.setPosY("350"); + compInstDet = componentInstanceReqDetailsList.get(2); + compInstDet.setPosX("350"); + compInstDet.setPosY("500"); + + response = ComponentInstanceRestUtils.updateMultipleComponentInstance(componentInstanceReqDetailsList, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), vf.getUniqueId(), vf.getComponentType()); + assertTrue("response code is not 200, returned: " + response.getErrorCode(), + response.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ParametersDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ParametersDefinition.java new file mode 100644 index 0000000000..a14dc8c76f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ParametersDefinition.java @@ -0,0 +1,105 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.List; + +public class ParametersDefinition { + + private String type; + private String description; + private Object Default; + private String status; +// private List constraints; + private String entry_schema; + private Object value; + + public ParametersDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public ParametersDefinition(String type, String description, Object default1, String status, String entry_schema, Object value) { + super(); + this.type = type; + this.description = description; + Default = default1; + this.status = status; + this.entry_schema = entry_schema; + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Object getDefault() { + return Default; + } + + public void setDefault(Object default1) { + Default = default1; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getEntry_schema() { + return entry_schema; + } + + public void setEntry_schema(String entry_schema) { + this.entry_schema = entry_schema; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + @Override + public String toString() { + return "ParametersDefinition [type=" + type + ", description=" + description + ", Default=" + Default + ", status=" + status + ", entry_schema=" + entry_schema + ", value=" + value + "]"; + } + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java new file mode 100644 index 0000000000..76c0c86680 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +public class ToscaCapabilitiesNodeTemplatesDefinition { + +} 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 new file mode 100644 index 0000000000..5a89a6766c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java @@ -0,0 +1,120 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.List; +import java.util.Map; + +import org.yaml.snakeyaml.TypeDescription; + +public class ToscaDefinition { + + String tosca_definitions_version; + Map metadata; +// Map imports; +// TODO waiting for answer about imports representation + Object imports; + Map node_types; + ToscaTopologyTemplateDefinition topology_template; + + public ToscaDefinition() { + super(); + } + + @Override + public String toString() { + return "ToscaDefinition [tosca_definitions_version=" + tosca_definitions_version + ", metadata=" + metadata + ", imports=" + imports + ", node_types=" + node_types + ", topology_template=" + topology_template + "]"; + } + + public String getTosca_definitions_version() { + return tosca_definitions_version; + } + + public void setTosca_definitions_version(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + + + +// public Map getImports() { +// return (Map) imports; +// } +// +// public void setImports(Map imports) { +// this.imports = imports; +// } +// +// public List getImports() { +// return (List) imports; +// } +// +// public void setImports(List imports) { +// this.imports = imports; +// } + + public Object getImports() { + return imports; + } + + public void setImports(Object imports) { + this.imports = imports; + } + + public Map getNode_types() { + return node_types; + } + + public void setNode_types(Map node_types) { + this.node_types = node_types; + } + + public ToscaTopologyTemplateDefinition getTopology_template() { + return topology_template; + } + + public void setTopology_template(ToscaTopologyTemplateDefinition topology_template) { + this.topology_template = topology_template; + } + + + + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaDefinition.class); + typeDescription.putMapPropertyType("metadata", String.class, String.class); +// TODO Andrey imports format + typeDescription.putMapPropertyType("imports", String.class, ToscaImportsDefinition.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/ToscaGroupsMetadataDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java new file mode 100644 index 0000000000..eec057ed52 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +public class ToscaGroupsMetadataDefinition { + + private String vfModuleModelName; + private String vfModuleModelInvariantUUID; + private String vfModuleModelCustomizationUUID; + private String vfModuleModelUUID; + private String vfModuleModelVersion; + + public ToscaGroupsMetadataDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public String getVfModuleModelName() { + return vfModuleModelName; + } + + public void setVfModuleModelName(String vfModuleModelName) { + this.vfModuleModelName = vfModuleModelName; + } + + public String getVfModuleModelInvariantUUID() { + return vfModuleModelInvariantUUID; + } + + public void setVfModuleModelInvariantUUID(String vfModuleModelInvariantUUID) { + this.vfModuleModelInvariantUUID = vfModuleModelInvariantUUID; + } + + public String getVfModuleModelCustomizationUUID() { + return vfModuleModelCustomizationUUID; + } + + public void setVfModuleModelCustomizationUUID(String vfModuleModelCustomizationUUID) { + this.vfModuleModelCustomizationUUID = vfModuleModelCustomizationUUID; + } + + public String getVfModuleModelUUID() { + return vfModuleModelUUID; + } + + public void setVfModuleModelUUID(String vfModuleModelUUID) { + this.vfModuleModelUUID = vfModuleModelUUID; + } + + public String getVfModuleModelVersion() { + return vfModuleModelVersion; + } + + public void setVfModuleModelVersion(String vfModuleModelVersion) { + this.vfModuleModelVersion = vfModuleModelVersion; + } + + @Override + public String toString() { + return "ToscaGroupsMetadataDefinition [vfModuleModelName=" + vfModuleModelName + ", vfModuleModelInvariantUUID=" + vfModuleModelInvariantUUID + ", vfModuleModelCustomizationUUID=" + vfModuleModelCustomizationUUID + + ", vfModuleModelUUID=" + vfModuleModelUUID + ", vfModuleModelVersion=" + vfModuleModelVersion + "]"; + } + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java new file mode 100644 index 0000000000..dc3c40751c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java @@ -0,0 +1,126 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.List; +import java.util.Map; + +import org.yaml.snakeyaml.TypeDescription; + +// spec page 102 +public class ToscaGroupsTopologyTemplateDefinition { + + private String type; // required + private String description; + private Map properties; + private Map targets; // required + private Map interfaces; + private List members; +// private Map metadata; + private ToscaGroupsMetadataDefinition metadata; + + public ToscaGroupsTopologyTemplateDefinition() { + super(); + } + + public ToscaGroupsMetadataDefinition getMetadata() { + return metadata; + } + + public void setMetadata(ToscaGroupsMetadataDefinition metadata) { + this.metadata = metadata; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public Map getTargets() { + return targets; + } + + public void setTargets(Map targets) { + this.targets = targets; + } + + public Map getInterfaces() { + return interfaces; + } + + public void setInterfaces(Map interfaces) { + this.interfaces = interfaces; + } + + public List getMembers() { + return members; + } + + public void setMembers(List members) { + this.members = members; + } + +// public Map getMetadata() { +// return metadata; +// } +// +// public void setMetadata(Map metadata) { +// this.metadata = metadata; +// } + + @Override + public String toString() { + return "ToscaGroupsTopologyTemplateDefinition [type=" + type + ", description=" + description + ", properties=" + properties + ", targets=" + targets + ", interfaces=" + interfaces + ", members=" + members + ", metadata=" + metadata + + "]"; + } + + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaGroupsTopologyTemplateDefinition.class); + typeDescription.putMapPropertyType("properties", String.class, Object.class); + typeDescription.putMapPropertyType("interfaces", String.class, Object.class); + typeDescription.putMapPropertyType("targets", String.class, Object.class); +// typeDescription.putMapPropertyType("metadata", String.class, String.class); + typeDescription.putMapPropertyType("metadata", String.class, String.class); + typeDescription.putListPropertyType("members", String.class); + return typeDescription; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java new file mode 100644 index 0000000000..d62e33e1dd --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java @@ -0,0 +1,81 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +public class ToscaImportsDefinition { + + private String file; + private String repository; + private String namespace_uri; + private String namespace_prefix; + + public ToscaImportsDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public ToscaImportsDefinition(String file, String repository, String namespace_uri, String namespace_prefix) { + super(); + this.file = file; + this.repository = repository; + this.namespace_uri = namespace_uri; + this.namespace_prefix = namespace_prefix; + } + + @Override + public String toString() { + return "ToscaImportsDefinition [file=" + file + ", repository=" + repository + ", namespace_uri=" + namespace_uri + ", namespace_prefix=" + namespace_prefix + "]"; + } + + public String getFile() { + return file; + } + + public void setFile(String file) { + this.file = file; + } + + public String getRepository() { + return repository; + } + + public void setRepository(String repository) { + this.repository = repository; + } + + public String getNamespace_uri() { + return namespace_uri; + } + + public void setNamespace_uri(String namespace_uri) { + this.namespace_uri = namespace_uri; + } + + public String getNamespace_prefix() { + return namespace_prefix; + } + + public void setNamespace_prefix(String namespace_prefix) { + this.namespace_prefix = namespace_prefix; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java new file mode 100644 index 0000000000..6f9590f0ae --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java @@ -0,0 +1,45 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.Map; + +public class ToscaInputsTopologyTemplateDefinition { + + private Map> inputs; + + public ToscaInputsTopologyTemplateDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public Map> getInputs() { + return inputs; + } + + public void setInputs(Map> inputs) { + this.inputs = inputs; + } + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java new file mode 100644 index 0000000000..d42ca8e307 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java @@ -0,0 +1,174 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.List; +import java.util.Map; + +import org.yaml.snakeyaml.TypeDescription; + +public class ToscaNodeTemplatesTopologyTemplateDefinition { + + private String name; + private String type; + private String description; + private String [] directives; + private Map properties; + private List> attributes; + private List> requirements; + private List> capabilities; + private List> interfaces; + private List> artifacts; + private List> node_filter; + private String copy; + private Map metadata; + + +// private Map properties; +// private Map requirements; +// private Map capabilities; + + public ToscaNodeTemplatesTopologyTemplateDefinition() { + super(); + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String[] getDirectives() { + return directives; + } + + public void setDirectives(String[] directives) { + this.directives = directives; + } + + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public List> getAttributes() { + return attributes; + } + + public void setAttributes(List> attributes) { + this.attributes = attributes; + } + + public List> getRequirements() { + return requirements; + } + + public void setRequirements(List> requirements) { + this.requirements = requirements; + } + + public List> getCapabilities() { + return capabilities; + } + + public void setCapabilities(List> capabilities) { + this.capabilities = capabilities; + } + + public List> getInterfaces() { + return interfaces; + } + + public void setInterfaces(List> interfaces) { + this.interfaces = interfaces; + } + + public List> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List> artifacts) { + this.artifacts = artifacts; + } + + public List> getNode_filter() { + return node_filter; + } + + public void setNode_filter(List> node_filter) { + this.node_filter = node_filter; + } + + public String getCopy() { + return copy; + } + + public void setCopy(String copy) { + this.copy = copy; + } + + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaNodeTemplatesTopologyTemplateDefinition.class); + typeDescription.putMapPropertyType("properties", String.class, Object.class); + typeDescription.putListPropertyType("requirements", Map.class); + typeDescription.putListPropertyType("capabilities", Map.class); + typeDescription.putListPropertyType("attributes", Map.class); + typeDescription.putListPropertyType("interfaces", Map.class); + typeDescription.putListPropertyType("artifacts", Map.class); + typeDescription.putListPropertyType("node_filter", Map.class); + typeDescription.putMapPropertyType("metadata", String.class, String.class); + return typeDescription; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java new file mode 100644 index 0000000000..07fd223d2c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java @@ -0,0 +1,141 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.Map; + +// spec page 88 +public class ToscaNodeTypesDefinition { + + private String name; + private String derived_from; + private String version; + private String description; + private Map properties; + private Map attributes; + private Map requirements; + private Map capabilities; + private Map interfaces; + private Map artifacts; + + public ToscaNodeTypesDefinition() { + super(); + } + + public ToscaNodeTypesDefinition(String name, String derived_from, String version, String description, Map properties, Map attributes, Map requirements, Map capabilities, + Map interfaces, Map artifacts) { + super(); + this.name = name; + this.derived_from = derived_from; + this.version = version; + this.description = description; + this.properties = properties; + this.attributes = attributes; + this.requirements = requirements; + this.capabilities = capabilities; + this.interfaces = interfaces; + this.artifacts = artifacts; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDerived_from() { + return derived_from; + } + + public void setDerived_from(String derived_from) { + this.derived_from = derived_from; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public Map getRequirements() { + return requirements; + } + + public void setRequirements(Map requirements) { + this.requirements = requirements; + } + + public Map getCapabilities() { + return capabilities; + } + + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } + + public Map getInterfaces() { + return interfaces; + } + + public void setInterfaces(Map interfaces) { + this.interfaces = interfaces; + } + + public Map getArtifacts() { + return artifacts; + } + + public void setArtifacts(Map artifacts) { + this.artifacts = artifacts; + } + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaOutputsTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaOutputsTopologyTemplateDefinition.java new file mode 100644 index 0000000000..02ca03dfa5 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaOutputsTopologyTemplateDefinition.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +import java.util.Map; + +public class ToscaOutputsTopologyTemplateDefinition { + + private Map outputs; + + public ToscaOutputsTopologyTemplateDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public Map getOutputs() { + return outputs; + } + + public void setOutputs(Map outputs) { + this.outputs = outputs; + } + + @Override + public String toString() { + return "ToscaOutputsTopologyTemplateDefinition [outputs=" + outputs + "]"; + } + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPoliciesTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPoliciesTopologyTemplateDefinition.java new file mode 100644 index 0000000000..7ac3e876b4 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPoliciesTopologyTemplateDefinition.java @@ -0,0 +1,67 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.Map; + +public class ToscaPoliciesTopologyTemplateDefinition { + + public ToscaPoliciesTopologyTemplateDefinition() { + super(); + } + + private String type; // required + private String description; + private Map properties; + private Map targets; + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public Map getProperties() { + return properties; + } + public void setProperties(Map properties) { + this.properties = properties; + } + public Map getTargets() { + return targets; + } + public void setTargets(Map targets) { + this.targets = targets; + } + @Override + public String toString() { + return "ToscaPoliciesTopologyTemplateDefinition [type=" + type + ", description=" + description + ", properties=" + properties + ", targets=" + targets + "]"; + } + + + +} + diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRelationshipTemplatesTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRelationshipTemplatesTopologyTemplateDefinition.java new file mode 100644 index 0000000000..392ffc4e42 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRelationshipTemplatesTopologyTemplateDefinition.java @@ -0,0 +1,79 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.Map; + +public class ToscaRelationshipTemplatesTopologyTemplateDefinition { + + public ToscaRelationshipTemplatesTopologyTemplateDefinition() { + // TODO Auto-generated constructor stub + } + + private String type; + private String description; + private Map properties; + private Map attributes; + private Map interfaces; + private String copy; + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public Map getProperties() { + return properties; + } + public void setProperties(Map properties) { + this.properties = properties; + } + public Map getAttributes() { + return attributes; + } + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + public Map getInterfaces() { + return interfaces; + } + public void setInterfaces(Map interfaces) { + this.interfaces = interfaces; + } + public String getCopy() { + return copy; + } + public void setCopy(String copy) { + this.copy = copy; + } + @Override + public String toString() { + return "ToscaRelationshipTemplatesTopologyTemplateDefinition [type=" + type + ", description=" + description + ", properties=" + properties + ", attributes=" + attributes + ", interfaces=" + interfaces + ", copy=" + copy + "]"; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java new file mode 100644 index 0000000000..bd9f0f0f5e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java @@ -0,0 +1,72 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +public class ToscaRequirementsNodeTemplatesDefinition { + + String name; + String capability; + String node; + String relationship; + + public ToscaRequirementsNodeTemplatesDefinition() { + super(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCapability() { + return capability; + } + + public void setCapability(String capability) { + this.capability = capability; + } + + public String getNode() { + return node; + } + + public void setNode(String node) { + this.node = node; + } + + public String getRelationship() { + return relationship; + } + + public void setRelationship(String relationship) { + this.relationship = relationship; + } + + @Override + public String toString() { + return "ToscaRequirementsDefinition [name=" + name + ", capability=" + capability + ", node=" + node + + ", relationship=" + relationship + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaSubstitutionMappingsDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaSubstitutionMappingsDefinition.java new file mode 100644 index 0000000000..957d988c4d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaSubstitutionMappingsDefinition.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +import java.util.Map; + +import org.yaml.snakeyaml.TypeDescription; + +public class ToscaSubstitutionMappingsDefinition { + + private String node_type; + private Map requirements; + private Map capabilities; + + public ToscaSubstitutionMappingsDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public String getNode_type() { + return node_type; + } + + public void setNode_type(String node_type) { + this.node_type = node_type; + } + + public Map getRequirements() { + return requirements; + } + + public void setRequirements(Map requirements) { + this.requirements = requirements; + } + + public Map getCapabilities() { + return capabilities; + } + + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } + +// gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaSubstitutionMappingsDefinition.class); + typeDescription.putMapPropertyType("requirements", String.class, Object.class); + typeDescription.putMapPropertyType("capabilities", String.class, Object.class); + return typeDescription; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java new file mode 100644 index 0000000000..539c9b4d63 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java @@ -0,0 +1,135 @@ +/*- + * ============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.ci.tests.tosca.datatypes; + +import java.util.List; +import java.util.Map; + +import org.yaml.snakeyaml.TypeDescription; + +// spec page 104 +public class ToscaTopologyTemplateDefinition { + + String description; + Map inputs; + Map node_templates; +// Map relationship_templates; + Map groups; +// Map policies; +// Map outputs; + ToscaSubstitutionMappingsDefinition substitution_mappings; + + public ToscaTopologyTemplateDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + + public ToscaSubstitutionMappingsDefinition getSubstitution_mappings() { + return substitution_mappings; + } + + + public void setSubstitution_mappings(ToscaSubstitutionMappingsDefinition substitution_mappings) { + this.substitution_mappings = substitution_mappings; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getInputs() { + return inputs; + } + + public void setInputs(Map inputs) { + this.inputs = inputs; + } + + public Map getNode_templates() { + return node_templates; + } + + public void setNode_templates(Map node_templates) { + this.node_templates = node_templates; + } + +// public Map getRelationship_templates() { +// return relationship_templates; +// } +// +// public void setRelationship_templates(Map relationship_templates) { +// this.relationship_templates = relationship_templates; +// } + + public Map getGroups() { + return groups; + } + + public void setGroups(Map groups) { + this.groups = groups; + } +// +// public Map getPolicies() { +// return policies; +// } +// +// public void setPolicies(Map policies) { +// this.policies = policies; +// } +// +// public Map getOutputs() { +// return outputs; +// } +// +// public void setOutputs(Map outputs) { +// this.outputs = outputs; +// } +// +// public Map getSubstitution_mappings() { +// return substitution_mappings; +// } +// +// public void setSubstitution_mappings(Map substitution_mappings) { +// this.substitution_mappings = substitution_mappings; +// } + +// @Override +// public String toString() { +// return "ToscaTopologyTemplateDefinition [description=" + description + ", inputs=" + inputs + ", node_templates=" + node_templates + ", relationship_templates=" + relationship_templates + ", groups=" + groups + ", policies=" +// + policies + ", outputs=" + outputs + ", substitution_mappings=" + substitution_mappings + "]"; +// } + + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaTopologyTemplateDefinition.class); + typeDescription.putMapPropertyType("inputs", String.class, Object.class); + typeDescription.putMapPropertyType("node_templates", String.class, ToscaNodeTemplatesTopologyTemplateDefinition.class); + typeDescription.putMapPropertyType("groups", String.class, ToscaGroupsTopologyTemplateDefinition.class); + return typeDescription; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition2.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition2.java new file mode 100644 index 0000000000..735c8a0f95 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition2.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +import java.util.Map; + +// spec page 104 +public class ToscaTopologyTemplateDefinition2 { + + String description; + Map> inputs; + Map node_templates; +// Map relationship_templates; + Map groups; +// Map policies; +// Map outputs; +// Map substitution_mappings; + + public ToscaTopologyTemplateDefinition2() { + super(); + // TODO Auto-generated constructor stub + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + public Map> getInputs() { + return inputs; + } + + public void setInputs(Map> inputs) { + this.inputs = inputs; + } + + public Map getNode_templates() { + return node_templates; + } + + public void setNode_templates(Map node_templates) { + this.node_templates = node_templates; + } + + public Map getGroups() { + return groups; + } + + public void setGroups(Map groups) { + this.groups = groups; + } + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java new file mode 100644 index 0000000000..9ca8adee53 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java @@ -0,0 +1,113 @@ +/*- + * ============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.ci.tests.users; + +public class AddUserAuditMessageInfo { + + String TIMESTAMP; + String ACTION; + // String MODIFIER_NAME; + String MODIFIER; + // String USER_UID; + // String USER_NAME; + // String USER_EMAIL; + // String USER_ROLE; + String USER; + String STATUS; + String DESC; + + public AddUserAuditMessageInfo(String timestamp, String action, String modifierName, String modifierUid, + String user, String status, String desc) { + super(); + this.TIMESTAMP = timestamp; + this.ACTION = action; + // this.MODIFIER_NAME = modifierName; + this.MODIFIER = modifierUid; + this.USER = user; + this.STATUS = status; + this.DESC = desc; + } + + public AddUserAuditMessageInfo() { + super(); + } + + public String getTIMESTAMP() { + return TIMESTAMP; + } + + public void setTIMESTAMP(String tIMESTAMP) { + TIMESTAMP = tIMESTAMP; + } + + public String getACTION() { + return ACTION; + } + + public void setACTION(String aCTION) { + ACTION = aCTION; + } + + // public String getMODIFIER_NAME() { + // return MODIFIER_NAME; + // } + // public void setMODIFIER_NAME(String mODIFIER_NAME) { + // MODIFIER_NAME = mODIFIER_NAME; + // } + public String getMODIFIER() { + return MODIFIER; + } + + public void setMODIFIER(String mODIFIER_UID) { + MODIFIER = mODIFIER_UID; + } + + public String getUSER() { + return USER; + } + + public void setUSER(String uSER) { + USER = uSER; + } + + public String getSTATUS() { + return STATUS; + } + + public void setSTATUS(String sTATUS) { + STATUS = sTATUS; + } + + public String getDESC() { + return DESC; + } + + public void setDESC(String dESC) { + DESC = dESC; + } + + @Override + public String toString() { + return "AddUserAuditMessageInfo [timestamp=" + TIMESTAMP + ", action=" + ACTION + ", modifierUid=" + MODIFIER + + ", user=" + USER + ", status=" + STATUS + ", desc=" + DESC + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java new file mode 100644 index 0000000000..b34d474cf0 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java @@ -0,0 +1,133 @@ +/*- + * ============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.ci.tests.users; + +public class UserAuditJavaObject { + + String TIMESTAMP; + String ACTION; + // String MODIFIER_NAME; + String MODIFIER; + String USER; + // String USER_NAME; + // String USER_EMAIL; + // String USER_ROLE; + String STATUS; + String DESC; + + public UserAuditJavaObject(String timestamp, String action, String modifier, String user, String status, + String desc) { + super(); + this.TIMESTAMP = timestamp; + this.ACTION = action; + // this.MODIFIER_NAME = modifierName; + this.MODIFIER = modifier; + this.USER = user; + // this.USER_NAME = userName; + // this.USER_EMAIL = userEmail; + // this.USER_ROLE = userRole; + this.STATUS = status; + this.DESC = desc; + } + + public UserAuditJavaObject() { + super(); + } + + public String getTIMESTAMP() { + return TIMESTAMP; + } + + public void setTIMESTAMP(String tIMESTAMP) { + TIMESTAMP = tIMESTAMP; + } + + public String getACTION() { + return ACTION; + } + + public void setACTION(String aCTION) { + ACTION = aCTION; + } + + // public String getMODIFIER_NAME() { + // return MODIFIER_NAME; + // } + // public void setMODIFIER_NAME(String mODIFIER_NAME) { + // MODIFIER_NAME = mODIFIER_NAME; + // } + public String getMODIFIER() { + return MODIFIER; + } + + public void setMODIFIER(String mODIFIER_UID) { + MODIFIER = mODIFIER_UID; + } + + public String getUSER() { + return USER; + } + + public void setUSER(String uSER) { + USER = uSER; + } + + // public String getUSER_NAME() { + // return USER_NAME; + // } + // public void setUSER_NAME(String uSER_NAME) { + // USER_NAME = uSER_NAME; + // } + // public String getUSER_EMAIL() { + // return USER_EMAIL; + // } + // public void setUSER_EMAIL(String uSER_EMAIL) { + // USER_EMAIL = uSER_EMAIL; + // } + // public String getUSER_ROLE() { + // return USER_ROLE; + // } + // public void setUSER_ROLE(String uSER_ROLE) { + // USER_ROLE = uSER_ROLE; + // } + public String getSTATUS() { + return STATUS; + } + + public void setSTATUS(String sTATUS) { + STATUS = sTATUS; + } + + public String getDESC() { + return DESC; + } + + public void setDESC(String dESC) { + DESC = dESC; + } + + @Override + public String toString() { + return "UserAuditJavaObject [timestamp=" + TIMESTAMP + ", action=" + ACTION + ", modifier=" + MODIFIER + + ", user=" + USER + ", status=" + STATUS + ", desc=" + DESC + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java new file mode 100644 index 0000000000..06320bcb5f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java @@ -0,0 +1,59 @@ +/*- + * ============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.ci.tests.users; + +public class UserHeaderData { + String contentType; + String httpCspUserId; + String accept; + + public UserHeaderData(String contentType, String httpCspUserId, String accept) { + super(); + this.contentType = contentType; + this.httpCspUserId = httpCspUserId; + this.accept = accept; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getHttpCspUserId() { + return httpCspUserId; + } + + public void setHttpCspUserId(String httpCspUserId) { + this.httpCspUserId = httpCspUserId; + } + + public String getAccept() { + return accept; + } + + public void setAccept(String accept) { + this.accept = accept; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java new file mode 100644 index 0000000000..97a08479f8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java @@ -0,0 +1,39 @@ +/*- + * ============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.ci.tests.users; + +public enum UserResponseMessageEnum { + + SUCCESS_MESSAGE("OK"), MISSING_INFORMATION("Error: Missing information"), METHOD_NOT_ALLOWED("Error: Method not allowed"), RESTRICTED_OPERATION("Error: Restricted operation"), USER_ALREADY_EXISTS("Error: User with %s ID already exists"), + INVALID_EMAIL("Error: Invalid Content. Invalid e-mail address %s"), INVALID_ROLE("Error: Invalid Content. Invalid role %s"), INVALID_CONTENT("Error: Invalid content"), USER_NOT_FOUND("Error: User with %s ID is not found"), + INTERNAL_SERVER_ERROR("Error: Internal Server Error. Try later again"), ADMINISTARTOR_CAN_BE_DELETED("Error: Administrator can be deleted by other administrator only"), RESTRICTED_ACCESS("Error: Restricted access"); + + String value; + + private UserResponseMessageEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java new file mode 100644 index 0000000000..609ebf22b7 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java @@ -0,0 +1,74 @@ +/*- + * ============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.ci.tests.users; + +public class WebSealUserDetails { + String firstName; + String lastName; + String userId; + String email; + + public WebSealUserDetails() { + super(); + } + + public WebSealUserDetails(String firstName, String lastName, String userId, String emailAddress) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.userId = userId; + this.email = emailAddress; + + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getEmailAddress() { + return email; + } + + public void setEmailAddress(String emailAddress) { + this.email = emailAddress; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java new file mode 100644 index 0000000000..12f8ffe984 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java @@ -0,0 +1,43 @@ +/*- + * ============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.ci.tests.utils; + +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; + +public class ArtifactUtils { + + public static ArtifactDefinition convertArtifactReqToDefinition(ArtifactReqDetails artifactReq) { + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactLabel(artifactReq.getArtifactLabel()); + artifact.setArtifactDisplayName(artifactReq.getArtifactDisplayName()); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifactReq.getArtifactGroupType())); + artifact.setArtifactType(artifactReq.getArtifactType().toUpperCase()); + artifact.setArtifactName(artifactReq.getArtifactName()); + artifact.setDescription(artifactReq.getDescription()); + artifact.setUniqueId(artifactReq.getUniqueId()); + artifact.setTimeout(artifactReq.getTimeout()); + artifact.setEsId(artifactReq.getUniqueId()); + + return artifact; + } +} 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 new file mode 100644 index 0000000000..69c8b2fe2f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java @@ -0,0 +1,174 @@ +/*- + * ============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.ci.tests.utils; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +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.utils.validation.CsarValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CsarParserUtils { + private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName()); + + public static List 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 listHeatMetaDefenition = new ArrayList(); + listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition); + return listHeatMetaDefenition; + } + return null; + + } + + public static List getListTypeHeatMetaDefinition(String 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 listHeatMetaDefenition = new ArrayList(); + listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition); + return listHeatMetaDefenition; + } + return null; + + } + + protected static List getArtifactsByGroup(JSONObject jsonObjectImportStructure, List listHeatMetaDefenition) { + + @SuppressWarnings("unchecked") + Set typeSet = jsonObjectImportStructure.keySet(); + for (Object type : typeSet) { + TypeHeatMetaDefinition heatMetaDefenition = new TypeHeatMetaDefinition(); + log.debug(type.toString()); + log.debug("{}", jsonObjectImportStructure.get(type)); + JSONArray array = (JSONArray) jsonObjectImportStructure.get(type); + heatMetaDefenition.setTypeName((String) type); + List groupHeatMetaDefinitions = new ArrayList(); + heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroupFromJsonArray(array, groupHeatMetaDefinitions, true, false)); + listHeatMetaDefenition.add(heatMetaDefenition); + } + return listHeatMetaDefenition; + } + + protected static List fetchArtifactByGroupFromJsonArray(JSONArray array, List listGroupHeatMetaDefinition, Boolean openNewGroup, Boolean isNested) { + + GroupHeatMetaDefinition groupHeatMetaDefinition; + + if (array != null) { + for (int i = 0; i < array.size(); i++) { + if (openNewGroup) { + groupHeatMetaDefinition = new GroupHeatMetaDefinition(); + int groupNumber = listGroupHeatMetaDefinition.size() + 1; + log.debug("groupName={}", groupNumber); + groupHeatMetaDefinition.setGroup(groupNumber); + listGroupHeatMetaDefinition.add(groupHeatMetaDefinition); + PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition(); + propertyHeatMetaDefinition.setName("isBase"); + propertyHeatMetaDefinition.setValue(false); + groupHeatMetaDefinition.setPropertyHeatMetaDefinition(propertyHeatMetaDefinition); + } + groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1); + JSONObject jsonObject = (JSONObject) array.get(i); + fetchArtifactByGroupFromJsonObject(listGroupHeatMetaDefinition, groupHeatMetaDefinition, jsonObject, isNested); + } + } + return listGroupHeatMetaDefinition; + } + + + public static void fetchArtifactByGroupFromJsonObject(List listGroupHeatMetaDefinition, GroupHeatMetaDefinition groupHeatMetaDefinition, JSONObject jsonObject, Boolean isNested) { + @SuppressWarnings("unchecked") + Set groupsKey = jsonObject.keySet(); + for (Object groupKey : groupsKey) { + String groupKeyStr = (String) groupKey; + if (groupKeyStr.equals("isBase")) { + PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition(); + propertyHeatMetaDefinition.setName(groupKeyStr); + propertyHeatMetaDefinition.setValue((boolean) jsonObject.get(groupKeyStr)); + if (!groupHeatMetaDefinition.getPropertyHeatMetaDefinition().equals(propertyHeatMetaDefinition)) { + groupHeatMetaDefinition.getPropertyHeatMetaDefinition().setValue((boolean) jsonObject.get(groupKeyStr)); + } + } + if (groupKeyStr.equals("fileName")) { + String artifactName = (String) jsonObject.get(groupKeyStr); + String artifactType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); + if(isNested){ + artifactType = ArtifactTypeEnum.HEAT_NESTED.getType(); + } + if(jsonObject.get("type") != null && isNested == false){ + artifactType = (String) jsonObject.get("type"); + } + HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition = new HeatMetaFirstLevelDefinition(artifactName, artifactType, null); + List listArtifactNames = groupHeatMetaDefinition.getArtifactList(); + listArtifactNames.add(heatMetaFirstLevelDefinition); + groupHeatMetaDefinition.setArtifactList(listArtifactNames); + } else { + if((groupKeyStr.equals("env"))){ + if (jsonObject.get(groupKeyStr) instanceof JSONObject){ + fetchArtifactByGroupFromJsonObject(listGroupHeatMetaDefinition, groupHeatMetaDefinition, (JSONObject) jsonObject.get(groupKeyStr), false); + }else{ + assertTrue("Expected object is JSONObject, but actual: " + jsonObject.get(groupKeyStr).getClass(), jsonObject.get(groupKeyStr).getClass().equals("JSONObject")); + } + } + if((groupKeyStr.equals("nested"))){ + if (jsonObject.get(groupKeyStr) instanceof JSONArray){ + fetchArtifactByGroupFromJsonArray((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, false, true); + }else{ + assertTrue("Expected object is JSONArray, but actual: " + jsonObject.get(groupKeyStr).getClass(), jsonObject.get(groupKeyStr).getClass().equals("JSONArray")); + } + + }else if (!(groupKeyStr.equals("isBase") || groupKeyStr.equals("type") || groupKeyStr.equals("env"))) { + if (jsonObject.get(groupKeyStr) instanceof JSONArray){ + fetchArtifactByGroupFromJsonArray((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, false, false); + }else{ + assertTrue("Expected object is JSONArray, but actual: " + jsonObject.get(groupKeyStr).getClass(), jsonObject.get(groupKeyStr).getClass().equals("JSONArray")); + } + } + } + } + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java new file mode 100644 index 0000000000..8e611a32d7 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java @@ -0,0 +1,293 @@ +/*- + * ============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.ci.tests.utils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.thinkaurelius.titan.core.TitanEdge; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject; +import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Property; + +public class DbUtils { + + private static String titanConfigFilePath; + private static TitanGraph titanGraph; + + + public static void cleanAllAudits() throws IOException { + CassandraUtils.truncateAllTables("sdcaudit"); + } + + public static RestResponse deleteFromEsDbByPattern(String patternToDelete) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), + patternToDelete); + HttpRequest httpRequest = new HttpRequest(); + RestResponse restResponse = httpRequest.httpSendDelete(url, null); + restResponse.getErrorCode(); + cleanAllAudits(); + + return restResponse; + } + + public static RestResponse getFromEsByPattern(String patternToGet) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), patternToGet); + HttpRequest httpRequest = new HttpRequest(); + RestResponse restResponse = httpRequest.httpSendGet(url, null); + restResponse.getErrorCode(); + + return restResponse; + } + + public Either getVertexByUId(String uid) { + TitanGraph titanGraph = getTitanGraph(); + Either result = Either.right(false); + // Iterator vertexItr = titanGraph.getVertices().iterator(); + + Iterator vertexItr = titanGraph.query().vertices().iterator(); + while (vertexItr.hasNext()) { + Vertex vertex = vertexItr.next(); + // String uidFoundVal = vertex.getProperty("uid"); + String uidFoundVal = vertex.value("uid"); + if (uid.equals(uidFoundVal)) { + result = Either.left(vertex); + } + } + return result; + } + + public static TitanState getCurrentTitanState() { + TitanGraph titanGraph = getTitanGraph(); + List vertices = new ArrayList<>(); + List edges = new ArrayList<>(); + // Iterator edgesItr = titanGraph.getEdges().iterator(); + Iterator edgesItr = titanGraph.query().edges().iterator(); + // Iterator verticesItr = titanGraph.getVertices().iterator(); + Iterator verticesItr = titanGraph.query().vertices().iterator(); + while (edgesItr.hasNext()) { + edges.add(edgesItr.next()); + } + while (verticesItr.hasNext()) { + vertices.add(verticesItr.next()); + } + + TitanState currState = new TitanState(edges, vertices); + return currState; + + } + + // + private static TitanGraph getTitanGraph() { + if (titanGraph == null) { + titanGraph = TitanFactory.open(titanConfigFilePath); + } + return titanGraph; + } + + public void restoreToTitanState(TitanState titanStateToRestoreTo) { + List verticesToRemove = new ArrayList<>(), verticesToAdd = new ArrayList<>(); + List edgesToRemove = new ArrayList<>(), edgesToAdd = new ArrayList<>(); + + TitanState currentTitanState = getCurrentTitanState(); + + List joinedEdges = new ArrayList<>(); + joinedEdges.addAll(titanStateToRestoreTo.edges); + joinedEdges.retainAll(currentTitanState.edges); + + List joinedVertices = new ArrayList<>(); + joinedVertices.addAll(titanStateToRestoreTo.vertices); + joinedVertices.retainAll(currentTitanState.vertices); + + edgesToRemove.addAll(currentTitanState.edges); + edgesToRemove.removeAll(joinedEdges); + + verticesToRemove.addAll(currentTitanState.vertices); + verticesToRemove.removeAll(joinedVertices); + + edgesToAdd.addAll(titanStateToRestoreTo.edges); + edgesToAdd.removeAll(joinedEdges); + + verticesToAdd.addAll(titanStateToRestoreTo.vertices); + verticesToAdd.removeAll(joinedVertices); + + modifyGraphAccordingToDelta(verticesToRemove, verticesToAdd, edgesToRemove, edgesToAdd); + + } + + private void modifyGraphAccordingToDelta(List verticesToRemove, List verticesToAdd, + List edgesToRemove, List edgesToAdd) { + + TitanGraph titanGraph = getTitanGraph(); + + for (Vertex vertex : verticesToRemove) { + // titanGraph.removeVertex(vertex); + vertex.remove(); + } + for (Vertex vertex : verticesToAdd) { + TitanVertex titanVertex = titanGraph.addVertex(); + copyProperties(vertex, titanVertex); + } + + for (Edge edge : edgesToRemove) { + // titanGraph.removeEdge(edge); + edge.remove(); + } + + for (Edge edge : edgesToAdd) { + // Element addedEdge = titanGraph.addEdge(edge.getId(), + // edge.getVertex(Direction.OUT), edge.getVertex(Direction.IN), + // edge.getLabel()); + + // Edge edge = tGraph.addEdge(null, fromV.left().value(), + // toV.left().value(), type); + + Element addedEdge = edge.outVertex().addEdge(edge.label(), edge.inVertex()); + + copyProperties(edge, addedEdge); + + } + + // titanGraph.commit(); + titanGraph.tx().commit(); + + } + + private void copyProperties(Element copyFrom, Element copyTo) { + // Set properties = copyFrom.getPropertyKeys(); + Set properties = copyFrom.keys(); + for (String propertyKey : properties) { + // copyTo.setProperty(propertyKey, + // copyFrom.getProperty(propertyKey)); + copyTo.property(propertyKey, copyFrom.value(propertyKey)); + } + + } + + public static class TitanState { + private List edges; + private List vertices; + + private TitanState(List edges, List vertices) { + this.edges = edges; + this.vertices = vertices; + } + + @Override + public String toString() { + return "TitanState [edges=" + edges.size() + ", vertices=" + vertices.size() + "]"; + } + + } + + public void shutDowntitan() { + if (titanGraph != null) { + // titanGraph.shutdown(); + titanGraph.close(); + } + } + + public static void setProperties(Element element, Map properties) { + + if (properties != null && false == properties.isEmpty()) { + + Object[] propertyKeyValues = new Object[properties.size() * 2]; + int i = 0; + for (Entry entry : properties.entrySet()) { + propertyKeyValues[i++] = entry.getKey(); + propertyKeyValues[i++] = entry.getValue(); + } + + ElementHelper.attachProperties(element, propertyKeyValues); + + } + + } + + public static UserAuditJavaObject parseAuditRespByAction(String action) throws Exception { + + // String index = "auditingevents*"; + // String type = "useradminevent"; + // String pattern = "/_search?q=action:\""+action+"\""; + // String auditingMessage = retrieveAuditMessageByIndexType(index, type, + // pattern); + UserAuditJavaObject auditParsedResp = new UserAuditJavaObject(); + Gson gson = new Gson(); + + String pattern = "/_search?q=ACTION:\"" + action + "\""; + String auditingMessage = retrieveAuditMessagesByPattern(pattern); + JsonElement jElement = new JsonParser().parse(auditingMessage); + JsonObject jObject = jElement.getAsJsonObject(); + JsonObject hitsObject = (JsonObject) jObject.get("hits"); + JsonArray hitsArray = (JsonArray) hitsObject.get("hits"); + // for (int i = 0; i < hitsArray.size();){ + if (hitsArray.size() == 0) { + return auditParsedResp; + } + JsonObject jHitObject = (JsonObject) hitsArray.get(0); + JsonObject jSourceObject = (JsonObject) jHitObject.get("_source"); + + auditParsedResp = gson.fromJson(jSourceObject, UserAuditJavaObject.class); + + return auditParsedResp; + + } + + public static String retrieveAuditMessagesByPattern(String pattern) throws IOException { + + Config config = Utils.getConfig(); + HttpRequest getAuditingMessage = new HttpRequest(); + String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), pattern); + RestResponse restResponse = getAuditingMessage.httpSendGet(url, null); + + return restResponse.getResponse(); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java new file mode 100644 index 0000000000..7d90eb0b6d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java @@ -0,0 +1,62 @@ +/*- + * ============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.ci.tests.utils; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +import org.apache.commons.codec.binary.Base64; + +public class Decoder { + + public static String encode(byte[] byteArrayToEncode) { + + byte[] bytesEncoded = Base64.encodeBase64(byteArrayToEncode); + String strEncoded = new String(bytesEncoded); + return strEncoded; + } + + public static String decode(String strEncoded) throws IOException { + + byte[] byteDecoded = Base64.decodeBase64(strEncoded); + String decoded = new String(byteDecoded); + + return decoded; + + } + + public static String readFileToString(String file) throws IOException { + + BufferedReader reader = new BufferedReader(new FileReader(file)); + String line = null; + StringBuilder stringBuilder = new StringBuilder(); + String ls = System.getProperty("line.separator"); + + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); + } + reader.close(); + return stringBuilder.toString(); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java new file mode 100644 index 0000000000..4838d55a3d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java @@ -0,0 +1,144 @@ +/*- + * ============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.ci.tests.utils; + +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus; +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.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; + + public class DistributionUtils { + + final static String serviceDistributionSuffix = "/sdc/v1/catalog/services/"; + + public static ServiceDistributionStatus getLatestServiceDistributionObject(Service service) throws IOException, ParseException { + ServiceDistributionStatus serviceDistributionStatus = null; + RestResponse distributionServiceList = ServiceRestUtils.getDistributionServiceList(service, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + Map serviveDistributionStatusMap = ResponseParser.convertServiceDistributionStatusToObject(distributionServiceList.getResponse()); + if(serviveDistributionStatusMap.size() != 0){ + serviceDistributionStatus = getLatestServiceDistributionObjectFromMap(serviveDistributionStatusMap); + return serviceDistributionStatus; + } + + return null; + } + + public static ServiceDistributionStatus getLatestServiceDistributionObjectFromMap(Map serviceDistributionStatusMap) { + + ServiceDistributionStatus serviceDistributionStatus = null; + if (serviceDistributionStatusMap.size() == 1 ){ + for (Entry entry : serviceDistributionStatusMap.entrySet()) { + return entry.getValue(); + } + } + else{ + serviceDistributionStatus = getFilteredServiceDistributionObject(serviceDistributionStatusMap); + } + + return serviceDistributionStatus; + } + + private static ServiceDistributionStatus getFilteredServiceDistributionObject(Map serviceDistributionStatusMap) { + + List list = new ArrayList(); + list.addAll(serviceDistributionStatusMap.keySet()); + Collections.sort(list); + return serviceDistributionStatusMap.get(list.get(list.size() - 1)); + } + + public static Map getArtifactsMapOfDistributedService(Service service) throws Exception{ + + Map expectedDistributionArtifactMap = new HashMap(); + expectedDistributionArtifactMap = addServiceDeploymentArtifactToMap(service, expectedDistributionArtifactMap); + expectedDistributionArtifactMap = addComponentInstancesDeploymentArtifactToMap(service, expectedDistributionArtifactMap); + + return expectedDistributionArtifactMap; + } + + + public static Map addServiceDeploymentArtifactToMap(Service service, Map distributionArtifactMap){ + + Map deploymentArtifacts = service.getDeploymentArtifacts(); + if (deploymentArtifacts != null && deploymentArtifacts.size() > 0){ + for(Entry artifact : deploymentArtifacts.entrySet()){ + String url = buildServiceDeploymentUrl(service, artifact.getValue().getArtifactName(), artifact.getValue().getArtifactUUID()); + distributionArtifactMap.put(artifact.getKey(), url); + } + } + + return distributionArtifactMap; + } + + private static String buildServiceDeploymentUrl(Service service, String artifactName, String artifactUUID) { +// 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){ + +// /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; + } + + public static String getResourceInstanceNormalizeName(Service service, String artifactName, String artifactUUID) { + for (ComponentInstance componentInstance : service.getComponentInstances()){ + for(String key : componentInstance.getDeploymentArtifacts().keySet()){ + if(componentInstance.getDeploymentArtifacts().get(key).getArtifactUUID().equals(artifactUUID)) { + return componentInstance.getNormalizedName(); + } + } + } + return null; + } + + public static Map addComponentInstancesDeploymentArtifactToMap(Service service, Map distributionArtifactMap){ +// TODO Andrey create correct method to build RI url + if(service.getComponentInstances() != null && service.getComponentInstances().size() != 0){ + for(ComponentInstance componentInstance : service.getComponentInstances()){ + if (componentInstance.getDeploymentArtifacts() != null && componentInstance.getDeploymentArtifacts().size() != 0){ + for(Entry artifact : componentInstance.getDeploymentArtifacts().entrySet()){ + String url = buildResourceInstanceDeploymentUrl(service, artifact.getValue().getArtifactName(), artifact.getValue().getArtifactUUID());; + distributionArtifactMap.put(artifact.getKey(), url); + } + } + } + } + + return distributionArtifactMap; + } + + + } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java new file mode 100644 index 0000000000..3f000d750a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java @@ -0,0 +1,630 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.Product; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.Assert; + +public class ReqCap { + + public static Map> expectedContainerCapabilities; + public static Map> expectedContainerRequirements; + public static Map removedRequirements; + public static Map>, Map>>> expectedContInstReqCap; + + public static void verifyVFReqCap(String componentId) throws Exception { + RestResponse restResponse = ResourceRestUtils.getResource(componentId); + Resource resource = ResponseParser.parseToObject(restResponse.getResponse(), Resource.class); + verifyReqCap(resource); + } + + public static void verifyServiceReqCap(String componentId, User sdncDesignerDetails) throws Exception { + RestResponse restResponse = ServiceRestUtils.getService(componentId, sdncDesignerDetails); + Service service = ResponseParser.parseToObject(restResponse.getResponse(), Service.class); + verifyReqCap(service); + } + + public static void verifyProductReqCap(String componentId, User sdncPsDetails1) throws Exception { + RestResponse restResponse = ProductRestUtils.getProduct(componentId, sdncPsDetails1.getUserId()); + Product product = ResponseParser.parseToObject(restResponse.getResponse(), Product.class); + verifyReqCap(product); + } + + public static void verifyReqCap(Component actualComponent) { + verifyContainerReqCap(actualComponent); + verifyCompInstReqCap(actualComponent); + } + + public RestResponse changeServiceInstanceVersion(String componentUniqueId, String serviceInstanceToReplaceUniqueId, + String serviceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType, boolean isHighestLevel) + throws Exception { + RestResponse changeResourceInstanceVersion = ProductRestUtils.changeServiceInstanceVersion(componentUniqueId, + serviceInstanceToReplaceUniqueId, serviceUniqueId, sdncModifierDetails, componentType); + if (changeResourceInstanceVersion.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS) && isHighestLevel) { + /* + * // Add RI Capabilities and Requirements to expected MAP --> + * expectedVfCapabilities and expectedVfRequirements + * + * ComponentInstance componentInstance = + * ResponseParser.parseToObjectUsingMapper( + * changeResourceInstanceVersion.getResponse(), + * ComponentInstance.class); + * addCompInstReqCapToExpected(componentInstance, componentType); + */ + } + return changeResourceInstanceVersion; + } + + public static void updateExpectedReqCapAfterChangeLifecycleState(String oldContainerUniqueIdToReplace, + String newContainerUniqueId) { + + // Update of container req/cap + + Set compInstKeysToChange = new HashSet<>(); + + for (String expKey : expectedContainerCapabilities.keySet()) { + List expCapList = expectedContainerCapabilities.get(expKey); + for (CapabilityDefinition cap : expCapList) { + String ownerId = cap.getOwnerId(); + + if (ownerId.contains(oldContainerUniqueIdToReplace)) { + compInstKeysToChange.add(ownerId); + cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + } + } + } + + for (String expKey : expectedContainerRequirements.keySet()) { + List expCapList = expectedContainerRequirements.get(expKey); + for (RequirementDefinition cap : expCapList) { + String ownerId = cap.getOwnerId(); + if (ownerId.contains(oldContainerUniqueIdToReplace)) { + compInstKeysToChange.add(ownerId); + cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId)); + } + } + } + + // Update of internal comp instances req/cap + for (String oldKey : compInstKeysToChange) { + ImmutablePair>, Map>> immutablePair = expectedContInstReqCap + .get(oldKey); + if (immutablePair != null) { + expectedContInstReqCap.remove(oldKey); + String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId); + expectedContInstReqCap.put(newKey, immutablePair); + } + } + } + + private static void verifyCompInstReqCap(Component actualComponent) { + List componentInstances = actualComponent.getComponentInstances(); + if (componentInstances != null) { + assertEquals(expectedContInstReqCap.size(), componentInstances.size()); + for (ComponentInstance compInst : componentInstances) { + String uniqueId = compInst.getUniqueId(); + // System.out.println("Verifying req/cap of component instance + // "+ uniqueId); + Map> actualCompInstReq = compInst.getRequirements(); + if (actualCompInstReq == null) { + actualCompInstReq = new HashMap<>(); + } + Map> actualCompInstCap = compInst.getCapabilities(); + if (actualCompInstCap == null) { + actualCompInstCap = new HashMap<>(); + } + ImmutablePair>, Map>> expReqCap = expectedContInstReqCap + .get(uniqueId); + assertNotNull(expReqCap); + // System.out.println("expected instance requirements: + // "+expReqCap.right); + // System.out.println("expected instance capabilities: + // "+expReqCap.left); + // System.out.println("actual instance requirements: + // "+actualCompInstReq); + // System.out.println("actual instance capabilities: + // "+actualCompInstCap); + + // REQ comparison + compareReqCapMaps(expReqCap.right, actualCompInstReq); + + // CAP comparison + compareReqCapMaps(expReqCap.left, actualCompInstCap); + } + + } else { + assertTrue(expectedContInstReqCap.isEmpty()); + } + } + + private static void verifyContainerReqCap(Component actualComponent) { + Map> actualContainerRequirements = actualComponent.getRequirements(); + if (actualContainerRequirements == null) { + actualContainerRequirements = new HashMap<>(); + } + Map> actualContainerCapabilities = actualComponent.getCapabilities(); + if (actualContainerCapabilities == null) { + actualContainerCapabilities = new HashMap<>(); + } + // System.out.println("Verifying req/cap of container component "+ + // actualComponent.getUniqueId()); + // System.out.println("expected container requirements: + // "+expectedContainerRequirements); + // System.out.println("expected container capabilities: + // "+expectedContainerCapabilities); + // System.out.println("actual container requirements: + // "+actualContainerRequirements); + // System.out.println("actual container capabilities: + // "+actualContainerCapabilities); + + // REQ comparison + compareReqCapMaps(expectedContainerRequirements, actualContainerRequirements); + + // CAP comparison + compareReqCapMaps(expectedContainerCapabilities, actualContainerCapabilities); + } + + private static void compareReqCapMaps(Map> expectedMap, Map> actualMap) { + assertEquals(expectedMap.size(), actualMap.size()); + for (String expKey : expectedMap.keySet()) { + List expCapList = expectedMap.get(expKey); + List actCapList = actualMap.get(expKey); + assertEquals(expCapList.size(), actCapList.size()); + assertEquals(new HashSet<>(expCapList), new HashSet<>(actCapList)); + } + } + + public static void addCompInstReqCapToExpected(ComponentInstance componentInstance, + ComponentTypeEnum containerComponentType, User sdncDesignerDetails) throws Exception { + + sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String uniqueId = componentInstance.getUniqueId(); + String name = componentInstance.getName(); + String originComponentId = componentInstance.getComponentUid(); + RestResponse getResponse = null; + ComponentTypeEnum compInstType = getCompInstTypeByContainerType(containerComponentType); + Component component = null; + if (compInstType == ComponentTypeEnum.RESOURCE) { + getResponse = ResourceRestUtils.getResource(sdncDesignerDetails, originComponentId); + ResourceRestUtils.checkSuccess(getResponse); + component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class); + } else if (compInstType == ComponentTypeEnum.SERVICE) { + getResponse = ServiceRestUtils.getService(originComponentId, sdncDesignerDetails); + ResourceRestUtils.checkSuccess(getResponse); + component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class); + } else { + Assert.fail("Unsupported type - " + containerComponentType); + } + + Map> resourceRequirements = component.getRequirements(); + if (resourceRequirements == null) { + resourceRequirements = new HashMap<>(); + } + + Function>, List> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList())); + Map> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper)); + + Map> resourceCapabilities = component.getCapabilities(); + if (resourceCapabilities == null) { + resourceCapabilities = new HashMap<>(); + } + + Function>, List> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList())); + Map> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper)); + + setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities); + if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) + && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) { + setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy); + } + + // adding entry for expected componentInstance + ImmutablePair>, Map>> compInstReqCapPair = new ImmutablePair>, Map>>( + capCopy, reqCopy); + expectedContInstReqCap.put(uniqueId, compInstReqCapPair); + } + + private static void setupContainerExpectedReqCap(String uniqueId, String name, + Map> componentRequirements, + Map> componentCapabilities) { + for (Entry> resReq : componentRequirements.entrySet()) { + List reqListToAdd = resReq.getValue(); + for (RequirementDefinition requirementDefinition : reqListToAdd) { + requirementDefinition.setOwnerId(uniqueId); + requirementDefinition.setOwnerName(name); + } + List expectedReqList = expectedContainerRequirements.get(resReq.getKey()); + if (expectedReqList == null) { + expectedReqList = reqListToAdd; + } else { + expectedReqList.addAll(reqListToAdd); + } + expectedContainerRequirements.put(resReq.getKey(), expectedReqList); + } + + for (Entry> resCap : componentCapabilities.entrySet()) { + List capListToAdd = resCap.getValue(); + for (CapabilityDefinition capDefinition : capListToAdd) { + capDefinition.setOwnerId(uniqueId); + capDefinition.setOwnerName(name); + } + List expectedCapList = expectedContainerCapabilities.get(resCap.getKey()); + if (expectedCapList == null) { + expectedCapList = capListToAdd; + } else { + expectedCapList.addAll(capListToAdd); + } + expectedContainerCapabilities.put(resCap.getKey(), expectedCapList); + } + } + + private static void setupConstInstExpectedReqCap(String uniqueId, String name, + Map> componentRequirements, + Map> componentCapabilities) { + for (Entry> resReq : componentRequirements.entrySet()) { + List reqListToAdd = resReq.getValue(); + for (RequirementDefinition requirementDefinition : reqListToAdd) { + requirementDefinition.setOwnerId(uniqueId); + requirementDefinition.setOwnerName(name); + } + } + + for (Entry> resCap : componentCapabilities.entrySet()) { + List capListToAdd = resCap.getValue(); + for (CapabilityDefinition capDefinition : capListToAdd) { + capDefinition.setOwnerId(uniqueId); + capDefinition.setOwnerName(name); + } + } + } + + private static ComponentTypeEnum getCompInstTypeByContainerType(ComponentTypeEnum componentType) { + switch (componentType) { + case RESOURCE: + return ComponentTypeEnum.RESOURCE; + case SERVICE: + return ComponentTypeEnum.RESOURCE; + case PRODUCT: + return ComponentTypeEnum.SERVICE; + default: + break; + } + return null; + } + + public static void deleteCompInstReqCapFromExpected(String componentInstanceId) { + List entriesRequirementsToRemove = new ArrayList<>(); + List entriesCapabilitiesToRemove = new ArrayList<>(); + for (Entry> reqEntry : expectedContainerRequirements.entrySet()) { + List reqList = reqEntry.getValue(); + List reqListToDelete = new ArrayList<>(); + for (RequirementDefinition requirementDefinition : reqList) { + if (requirementDefinition.getOwnerId().equals(componentInstanceId)) { + reqListToDelete.add(requirementDefinition); + } + } + reqList.removeAll(reqListToDelete); + if (reqList.isEmpty()) { + entriesRequirementsToRemove.add(reqEntry.getKey()); + } + } + + for (String ekey : entriesRequirementsToRemove) { + expectedContainerRequirements.remove(ekey); + } + + for (Entry> capEntry : expectedContainerCapabilities.entrySet()) { + List capList = capEntry.getValue(); + List capListToDelete = new ArrayList<>(); + for (CapabilityDefinition capabilityDefinition : capList) { + if (capabilityDefinition.getOwnerId().equals(componentInstanceId)) { + capListToDelete.add(capabilityDefinition); + } + } + capList.removeAll(capListToDelete); + if (capList.isEmpty()) { + entriesCapabilitiesToRemove.add(capEntry.getKey()); + } + } + for (String ekey : entriesCapabilitiesToRemove) { + expectedContainerCapabilities.remove(ekey); + } + + expectedContInstReqCap.remove(componentInstanceId); + + } + + // Automatically updates the expected req/cap of the container + public static RestResponse createAtomicInstanceForVF(Resource containerDetails, Resource compInstOriginDetails, + User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, + true); + } + + // Automatically updates the expected req/cap of the container + public static RestResponse createAtomicInstanceForService(Service containerDetails, Resource compInstOriginDetails, + User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, + true); + } + + // Automatically updates the expected req/cap of the container + public static RestResponse createVFInstance(Service containerDetails, Resource compInstOriginDetails, User modifier) + throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, + true); + } + + // Automatically updates the expected req/cap of the container + public static RestResponse createServiceInstance(Product containerDetails, Service compInstOriginDetails, + User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, + true); + } + + // Automatically updates the expected req/cap of the container + public static RestResponse deleteAtomicInstanceForVF(String compInstUniqueId, Resource containerDetails, + User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, true); + } + + // Automatically updates the expected req/cap of the container + public static RestResponse deleteAtomicInstanceForService(String compInstUniqueId, Service containerDetails, + User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true); + } + + // Automatically updates the expected req/cap of the container + public static RestResponse deleteVFInstance(String compInstUniqueId, Service containerDetails, User modifier) + throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true); + + } + + // Automatically updates the expected req/cap of the container + public static RestResponse deleteServiceInstance(String compInstUniqueId, Product containerDetails, User modifier) + throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, true); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse createAtomicInstanceForVFDuringSetup(Resource containerDetails, + Resource compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, + false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse createAtomicInstanceForServiceDuringSetup(Service containerDetails, + Resource compInstOriginDetails, User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, + false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse createVFInstanceDuringSetup(Service containerDetails, Resource compInstOriginDetails, + User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, + false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse createServiceInstanceDuringSetup(Product containerDetails, Service compInstOriginDetails, + User modifier) throws Exception { + return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, + false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse deleteAtomicInstanceForVFDuringSetup(String compInstUniqueId, Resource containerDetails, + User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse deleteAtomicInstanceForServiceDuringSetup(String compInstUniqueId, + Service containerDetails, User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false); + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse deleteVFInstanceDuringSetup(String compInstUniqueId, Service containerDetails, + User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false); + + } + + // Setup of lower components - Doesn't affect req/cap of the container (for + // example, setup of VF for testing a Product) + public static RestResponse deleteServiceInstanceDuringSetup(String compInstUniqueId, Product containerDetails, + User modifier) throws IOException, Exception { + return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, false); + } + + public static Component getComponentAndValidateRIs(Component componentDetails, int numberOfRIs, + int numberOfRelations, User sdncAdminDetails) throws IOException, Exception { + + RestResponse getResponse = null; + Component component = null; + if (componentDetails instanceof Resource) { + getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId()); + component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class); + } else if (componentDetails instanceof Service) { + getResponse = ServiceRestUtils.getService((componentDetails.getUniqueId()), sdncAdminDetails); + component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class); + } else if (componentDetails instanceof Product) { + 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); + verifyReqCap(component); + + return component; + } + + public static void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, + Component componentDetails, int numOfRIs, int numOfRelations, User sdncAdminDetails) + throws IOException, Exception { + updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId()); + getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations, sdncAdminDetails); + } + + private static RestResponse createComponentInstance(Component containerDetails, Component compInstOriginDetails, + User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel) + throws IOException, Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentInstance(compInstOriginDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum); + if (createResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED) && isHighestLevel) { + // Add RI Capabilities and Requirements to expected MAP --> + // expectedVfCapabilities and expectedVfRequirements + ComponentInstance componentInstance = ResponseParser + .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class); + addCompInstReqCapToExpected(componentInstance, containerComponentTypeEnum, modifier); + } + return createResourceInstanceResponse; + } + + private static RestResponse deleteComponentInstance(String compInstUniqueId, Component containerDetails, + User modifier, ComponentTypeEnum componentTypeEnum, boolean isHighestLevel) throws Exception { + RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(modifier, + containerDetails.getUniqueId(), compInstUniqueId, componentTypeEnum); + if (deleteResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_DELETE) && isHighestLevel) { + deleteCompInstReqCapFromExpected(compInstUniqueId); + } + return deleteResourceInstanceResponse; + } + + public static RestResponse associateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, + ComponentReqDetails containerDetails, User user) throws IOException { + + RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, user, + containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(associateInstances); + deleteAssociatedFromExpected(requirementDef); + return associateInstances; + } + + private static void deleteAssociatedFromExpected(RequirementCapabilityRelDef requirementDef) { + // removing from requirements + RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0); + String type = relationship.getRelationship().getType(); + String fromId = requirementDef.getFromNode(); + List reqList = expectedContainerRequirements.get(type); + RequirementDefinition toDelete = null; + if (reqList != null) { + for (RequirementDefinition reqDef : reqList) { + if (reqDef.getOwnerId().equals(fromId)) { + toDelete = reqDef; + } + } + if (toDelete != null) { + reqList.remove(toDelete); + if (reqList.isEmpty()) { + expectedContainerRequirements.remove(type); + } + removedRequirements.put(toDelete.getCapability() + " " + toDelete.getOwnerId(), toDelete); + } + } + } + + public static void dissociateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, + ComponentReqDetails containerDetails, User user) throws IOException { + + RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user, + containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE); + ResourceRestUtils.checkSuccess(dissociateInstances); + addDissociatedToExpected(requirementDef); + } + + private static void addDissociatedToExpected(RequirementCapabilityRelDef requirementDef) { + // adding to requirements + RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0); + String type = relationship.getRelationship().getType(); + String fromId = requirementDef.getFromNode(); + String key = type + " " + fromId; + RequirementDefinition requirementDefinition = removedRequirements.get(key); + if (requirementDefinition != null) { + List reqList = expectedContainerRequirements.get(type); + if (reqList == null) { + reqList = new ArrayList<>(); + expectedContainerRequirements.put(type, reqList); + } + reqList.add(requirementDefinition); + } + } + +} 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 new file mode 100644 index 0000000000..26fac7fd6e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java @@ -0,0 +1,361 @@ +/*- + * ============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.ci.tests.utils; + +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Map; +import java.util.Set; + +import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum; +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.ToscaSubstitutionMappingsDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition; +import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.introspector.PropertyUtils; + +public class ToscaParserUtils { + + private static Logger log = LoggerFactory.getLogger(ToscaParserUtils.class.getName()); + + public static ToscaDefinition parseToscaYamlToJavaObject(String csarUUID) throws Exception { + + ToscaDefinition toscaDefinition = null; + String TOSCAMetaLocation = "TOSCA-Metadata/TOSCA.meta"; + Map map = getToscaYamlMap(csarUUID, TOSCAMetaLocation); + assertNotNull("Tosca Entry-Definitions is null", map); + if (map != null) { + File definitionYamlLocation = (File) map.get("Entry-Definitions"); + toscaDefinition = parseToscaYamlToJavaObject(definitionYamlLocation); + } + return toscaDefinition; + + } + + public static ToscaDefinition parseToscaYamlToJavaObject(File path) throws Exception { + + ToscaDefinition toscaDefinition = null; + +// File path = new File("C:/Data/D2.0/TOSCA_Ex/Definitions/tosca_definition_version.yaml"); + FileInputStream fis = null; + try { + fis = new FileInputStream(path); + + } catch (Exception e) { + System.out.println("Exception: " + e); + } + + Constructor constructor = getConstructor(); + + Yaml yaml = new Yaml(constructor); + try { + toscaDefinition = (ToscaDefinition) yaml.load(fis); + } catch (Exception e) { + log.debug("Failed to parse tosca yaml file"); + System.out.println("Exception: " + e); + } finally { + fis.close(); + } + return toscaDefinition; + + } + + public static ToscaDefinition parseToscaYamlPayloadToJavaObject(String payload){ + + ToscaDefinition toscaDefinition = null; + Constructor constructor = getConstructor(); + + Yaml yaml = new Yaml(constructor); + try { + toscaDefinition = (ToscaDefinition) yaml.load(payload); + } catch (Exception e) { + log.debug("Failed to parse tosca yaml file"); + System.out.println("Exception: " + e); + } + return toscaDefinition; + + } + + + 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()); + +// Skip properties which are found in YAML, but not found in POJO + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setSkipMissingProperties(true); + constructor.setPropertyUtils(propertyUtils); + return constructor; + } + + public static Map getToscaYamlMap(String csarUUID, String fileLocation) throws Exception { + String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation); + if (csarPayload != null) { + Yaml yaml = new Yaml(); + Map map = (Map) yaml.load(csarPayload); + return map; + } + return null; + } + +/* public static Map getToscaYamlMap(String csarUUID, String fileLocation) throws Exception { + String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation); + if (csarPayload != null) { + Yaml yaml = new Yaml(); + Map map = (Map) yaml.load(csarPayload); + return map; + } + return null; + } + + public static ToscaDefinition getToscaDefinitionObjectByCsarUuid(String csarUUID) throws Exception { + + String TOSCAMetaLocation = "TOSCA-Metadata/TOSCA.meta"; + Map map = getToscaYamlMap(csarUUID, TOSCAMetaLocation); + assertNotNull("Tosca Entry-Definitions is null", map); + if (map != null) { + String definitionYamlLocation = (String) map.get("Entry-Definitions"); + Map toscaMap = getToscaYamlMap(csarUUID, definitionYamlLocation); + assertNotNull("Tosca definition is null", toscaMap); + if (toscaMap != null) { + ToscaDefinition toscaDefinition = new ToscaDefinition(); + Set keySet = toscaMap.keySet(); + for (Object key : keySet) { + ToscaKeysEnum toscaKey = ToscaKeysEnum.findToscaKey((String) key); + switch (toscaKey) { + case TOSCA_DEFINITION_VERSION: + getToscaDefinitionVersion(toscaMap, toscaDefinition); + break; + case NODE_TYPES: + getToscaNodeTypes(toscaMap, toscaDefinition); + break; + case TOPOLOGY_TEMPLATE: + getToscaTopologyTemplate(toscaMap, toscaDefinition); + break; + case IMPORTS: + // toscaMap.get("imports"); + break; + default: + break; + } + } + return toscaDefinition; + } + } + return null; + + } + + public static void getToscaDefinitionVersion(Map toscaMap, ToscaDefinition toscaDefinition) { + if (toscaMap.get("tosca_definitions_version") != null) { + toscaDefinition.setTosca_definitions_version((String) toscaMap.get("tosca_definitions_version")); + } + } + + // spec 90 page + public static void getToscaNodeTypes(Map toscaMap, ToscaDefinition toscaDefinition) { + @SuppressWarnings("unchecked") + Map> nodeTypes = (Map>) toscaMap.get("node_types"); + Map listToscaNodeTypes = new HashMap(); + if (nodeTypes != null) { + for (Map.Entry> entry : nodeTypes.entrySet()) { + ToscaNodeTypesDefinition toscaNodeTypes = new ToscaNodeTypesDefinition(); + String toscaNodeName = entry.getKey(); + toscaNodeTypes.setName(toscaNodeName); + + Map toscaNodeType = entry.getValue(); + if (toscaNodeType != null) { + Set> entrySet = toscaNodeType.entrySet(); + if (entrySet != null) { + // boolean found = false; + for (Entry toscaNodeTypeMap : entrySet) { + String key = toscaNodeTypeMap.getKey(); + if (key.equals("derived_from")) { + String derivedFrom = toscaNodeTypeMap.getValue(); + toscaNodeTypes.setDerived_from(derivedFrom); + // found = true; + break; + } else { + continue; + } + + } + // if (found == false) { + // System.out.println("Tosca file not valid, + // derived_from not found"); + // } + } + + } +// listToscaNodeTypes.add(toscaNodeTypes); + listToscaNodeTypes.put(toscaNodeName, toscaNodeTypes); + } + toscaDefinition.setNode_types(listToscaNodeTypes); + } + } + + public static void getToscaTopologyTemplate(Map toscaMap, ToscaDefinition toscaDefinition) { + ToscaTopologyTemplateDefinition toscaTopologyTemplate = new ToscaTopologyTemplateDefinition(); + @SuppressWarnings("unchecked") + Map> topologyTemplateMap = (Map>) toscaMap.get("topology_template"); +// List listToscaNodeTemplates = new ArrayList<>(); + Map mapToscaNodeTemplates = new HashMap(); + + if (topologyTemplateMap != null) { + getToscaNodeTemplates(topologyTemplateMap, mapToscaNodeTemplates); + } +// toscaTopologyTemplate.setToscaNodeTemplatesTopologyTemplateDefinition(listToscaNodeTemplates); + toscaTopologyTemplate.setNode_templates(mapToscaNodeTemplates); + toscaDefinition.setTopology_template(toscaTopologyTemplate); + } + + public static void getToscaNodeTemplates(Map> topologyTemplateMap, Map mapToscaNodeTemplates) { + Map nodeTemplatesMap = topologyTemplateMap.get("node_templates"); + if (nodeTemplatesMap != null) { + + for (Entry nodeTemplates : nodeTemplatesMap.entrySet()) { + ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates = new ToscaNodeTemplatesTopologyTemplateDefinition(); + getToscaNodeTemplatesName(nodeTemplates, toscaNodeTemplates); + + @SuppressWarnings("unchecked") + Map node = (Map) nodeTemplates.getValue(); + getNodeTemplatesType(toscaNodeTemplates, node); + getToscaNodeTemplateProperties(toscaNodeTemplates, node); + getToscaNodeTemplateRequirements(toscaNodeTemplates, node); + mapToscaNodeTemplates.putAll(mapToscaNodeTemplates); + } + } + } + + public static void getToscaNodeTemplateRequirements(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates, Map node) { +//// List toscaRequirements = new ArrayList<>(); +// List> toscaRequirements = new ArrayList<>(); +// if (node.get("requirements") != null) { +// @SuppressWarnings("unchecked") +// List> requirementList = (List>) node.get("requirements"); +// for (int i = 0; i < requirementList.size(); i++) { +// for (Map.Entry requirement : requirementList.get(i).entrySet()) { +// ToscaRequirementsNodeTemplatesDefinition toscaRequirement = new ToscaRequirementsNodeTemplatesDefinition(); +// if (requirement.getKey() != null) { +// String requirementName = requirement.getKey(); +// toscaRequirement.setName(requirementName); +// } else { +// log.debug("Tosca file not valid, requirements should contain name"); +// } +// +// @SuppressWarnings("unchecked") +// Map requirementMap = (Map) requirement.getValue(); +// Set> entrySet = requirementMap.entrySet(); +// if (entrySet != null) { +// for (Entry requirementField : entrySet) { +// String key = requirementField.getKey(); +// switch (key) { +// case "capability": +// if (requirementMap.get(key) != null) { +// String capability = (String) requirementMap.get(key); +// toscaRequirement.setCapability(capability); +// break; +// } else { +// continue; +// } +// case "node": +// if (requirementMap.get(key) != null) { +// String requirementNode = (String) requirementMap.get(key); +// toscaRequirement.setNode(requirementNode); +// break; +// } else { +// continue; +// } +// case "relationship": +// if (requirementMap.get(key) != null) { +// String relationship = (String) requirementMap.get(key); +// toscaRequirement.setRelationship(relationship); +// break; +// } else { +// continue; +// } +// default: +// break; +// } +// } +// } +//// toscaRequirements.add(toscaRequirement); +// toscaRequirements.add(requirementMap); +// } +// } +// } +//// toscaNodeTemplates.setRequirements(toscaRequirements); +// toscaNodeTemplates.setRequirements(requirements); + + } + + public static void getToscaNodeTemplateProperties(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates, + Map node) { +// List listToscaProperties = new ArrayList<>(); + Map mapToscaProperties = new HashMap<>(); + if (node.get("properties") != null) { + @SuppressWarnings("unchecked") + Map properties = (Map) node.get("properties"); + for (Map.Entry property : properties.entrySet()) { + ToscaPropertiesNodeTemplatesDefinition toscaProperty = new ToscaPropertiesNodeTemplatesDefinition(); + String propertyName = property.getKey(); + Object propertyValue = property.getValue(); + toscaProperty.setName(propertyName); + toscaProperty.setValue(propertyValue); +// mapToscaProperties.add(toscaProperty); + mapToscaProperties.put(propertyName, propertyValue); + } + } + toscaNodeTemplates.setProperties(mapToscaProperties); + } + + protected static void getNodeTemplatesType(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates, + Map node) { + if (node.get("type") != null) { + String type = (String) node.get("type"); + toscaNodeTemplates.setType(type); + } else { + log.debug("Tosca file not valid, nodeTemplate should contain type"); + } + } + + protected static void getToscaNodeTemplatesName(Entry nodeTemplates, + ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates) { + String name = nodeTemplates.getKey(); + toscaNodeTemplates.setName(name); + }*/ + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java new file mode 100644 index 0000000000..3515191433 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java @@ -0,0 +1,689 @@ +/*- + * ============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.ci.tests.utils; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.ToscaNodeTypeInfo; +import org.openecomp.sdc.common.api.YamlConstants; +import org.yaml.snakeyaml.Yaml; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public final class Utils { + + Gson gson = new Gson(); + + static Logger logger = Logger.getLogger(Utils.class.getName()); + + String contentTypeHeaderData = "application/json"; + String acceptHeaderDate = "application/json"; + + public Utils() { + /* + * super(); + * + * StartTest.enableLogger(); logger = + * Logger.getLogger(Utils.class.getName()); + */ + + } + + // public String serviceTopologyPattern = "/topology/topology/%s"; + // public String serviceTopologyTemplatePattern = + // "/topologytemplate/topologytemplate/%s"; + // + // public String serviceTopologySearchPattern = + // "topology/topology/_search?q=%s"; + // public String serviceTopologyTemplateSearchPattern = + // "topologytemplate/topologytemplate/_search?q=%s"; + // + // public ArtifactTypeEnum getFileTypeByExtension(String fileName) { + // + // String fileExtension = null; + // if (fileName.matches("(.*)\\.(.*)")) { + // System.out.println(fileName.substring(fileName.lastIndexOf(".") + 1)); + // fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); + // } + // + // switch (fileExtension) { + // case "sh": + // return ArtifactTypeEnum.SHELL_SCRIPT; + // case "png": + // return ArtifactTypeEnum.ICON; + // case "ppp": + // return ArtifactTypeEnum.PUPPET; + // case "yang": + // return ArtifactTypeEnum.YANG; + // default: + // return ArtifactTypeEnum.UNKNOWN; + // } + // + // } + // + // public ArrayList getScriptList (List + // artifactsList){ + // + // ArrayList scriptNameArray = new ArrayList<>(); + // if (artifactsList != null){ + // for (UploadArtifactInfo fileInArtifactsList : artifactsList){ + // String artifactFileName = fileInArtifactsList.getArtifactName(); + // ArtifactTypeEnum artifactFileType = + // fileInArtifactsList.getArtifactType(); + // if (! artifactFileType.equals(ArtifactTypeEnum.ICON)){ + // scriptNameArray.add(artifactFileName); + // } + // continue; + // } + // return scriptNameArray; + // } + // return null; + // } + // + // + // public String getYamlFileLocation(File testResourcesPath) { + // File[] files = testResourcesPath.listFiles(); + // if (files.length == 0){ + // return null; + // }else{ + // for (int i = 0; i < files.length; i++){ + // if (files[i].isFile()){ + // return files[i].getAbsoluteFile().toString(); + // } + // } + // } + // return null; + // } + // + // public String readFileContentToString (String fileName) throws + // IOException { + // + // Path path = Paths.get(fileName); + // String stringFromFile = new String(Files.readAllBytes(path)); + // return stringFromFile; + // + // + // } + // + @SuppressWarnings("unchecked") + public ToscaNodeTypeInfo parseToscaNodeYaml(String fileContent) { + + ToscaNodeTypeInfo result = new ToscaNodeTypeInfo(); + Object templateVersion = null; + Object templateName = null; + + if (fileContent != null) { + Yaml yaml = new Yaml(); + + Map yamlObject = (Map) yaml.load(fileContent); + + templateVersion = yamlObject.get(YamlConstants.TEMPLATE_VERSION); + if (templateVersion != null) { + result.setTemplateVersion(templateVersion.toString()); + } + templateName = yamlObject.get(YamlConstants.TEMPLATE_NAME); + if (templateName != null) { + result.setTemplateName(templateName.toString()); + } + Object nodeTypes = yamlObject.get(YamlConstants.NODE_TYPES); + + if (nodeTypes != null) { + Map nodeTypesMap = (Map) nodeTypes; + for (Entry entry : nodeTypesMap.entrySet()) { + + String nodeName = entry.getKey(); + if (nodeName != null) { + result.setNodeName(nodeName); + } + + break; + + } + } + + } + + return result; + } + + // + // + // public ArtifactsMetadata getArtifactsMetadata(String response){ + // ArtifactsMetadata artifactsMetadata = new ArtifactsMetadata(); + // + // artifactsMetadata.setId(getJsonObjectValueByKey(response, "id")); + // artifactsMetadata.setName(getJsonObjectValueByKey(response, "name")); + // artifactsMetadata.setType(getJsonObjectValueByKey(response, "type")); + // + // artifactsMetadata.setCreator(getJsonObjectValueByKey(response, + // "creator")); + // artifactsMetadata.setCreationTime(getJsonObjectValueByKey(response, + // "creationTime")); + // artifactsMetadata.setLastUpdateTime(getJsonObjectValueByKey(response, + // "lastUpdateTime")); + // artifactsMetadata.setChecksum(getJsonObjectValueByKey(response, + // "checksum")); + // artifactsMetadata.setDescription(getJsonObjectValueByKey(response, + // "description")); + // artifactsMetadata.setLastUpdater(getJsonObjectValueByKey(response, + // "lastUpdater")); + // + // return artifactsMetadata; + // } + // + public static String getJsonObjectValueByKey(String metadata, String key) { + JsonElement jelement = new JsonParser().parse(metadata); + + JsonObject jobject = jelement.getAsJsonObject(); + Object obj = jobject.get(key); + if (obj == null) { + return null; + } else { + String value; + value = (String) jobject.get(key).getAsString(); + return value; + } + } + + public static Config getConfig() throws FileNotFoundException { + Config config = Config.instance(); + return config; + } + + // public void uploadNormativeTypes() throws IOException{ + // Config config = getConfig(); + // String[] normativeTypes = {"root", "compute", "blockStorage", + // "softwareComponent", "DBMS", "database", "network", "objectStorage", + // "webServer", "webApplication"}; + // for( String normativeType : normativeTypes ){ + // uploadComponent(config.getComponentsConfigDir()+File.separator+"normativeTypes"+File.separator+normativeType); + // } + // + // } + // + // public void uploadApacheComponent() throws IOException{ + // Config config = getConfig(); + // uploadComponent(config.getComponentsConfigDir()+File.separator+"apache"); + // } + // + // public void uploadComponent(String componentDir) throws IOException{ + // + // //*********************************************upload************************************************************* + // Config config = getConfig(); + // ZipDirectory zipDirectory = new ZipDirectory(); + // System.out.println(config.getEsHost()); + // + // List artifactsList = new + // ArrayList(); + // + //// read test resources and zip it as byte array + // byte[] zippedAsByteArray = zipDirectory.zip(componentDir, artifactsList); + // + //// encode zipped directory using base64 + // String payload = Decoder.encode(zippedAsByteArray); + // + //// zip name build as testName with ".zip" extension + // String payloadZipName = getPayloadZipName(componentDir); + // + //// build json + // UploadResourceInfo resourceInfo = new UploadResourceInfo(payload, + // payloadZipName, "description", "category/mycategory", null, + // artifactsList); + // String json = new Gson().toJson(resourceInfo); + // + //// calculate md5 on the content of json + // String jsonMd5 = + // org.apache.commons.codec.digest.DigestUtils.md5Hex(json); + // + //// encode the md5 to base64, sent as header in post http request + // String encodedMd5 = Decoder.encode(jsonMd5.getBytes()); + // + //// upload component to Elastic Search DB + // String url = null; + // HttpRequest http = new HttpRequest(); + // + // url = String.format(Urls.UPLOAD_ZIP_URL, config.getCatalogFeHost(), + // config.getCatalogFePort()); + // + //// Prepare headers to post upload component request + // HeaderData headerData = new HeaderData(encodedMd5, "application/json", + // "att", "test", "testIvanovich", "RoyalSeal", "Far_Far_Away", + // "getResourceArtifactListTest"); + // + // MustHeaders headers = new MustHeaders(headerData); + // System.out.println("headers:"+headers.getMap()); + // + // RestResponse response = http.httpSendPost(url, json, headers.getMap()); + // + // assertEquals("upload component failed with code " + + // response.getErrorCode().intValue(),response.getErrorCode().intValue(), + // 204); + // } + // + // private String getPayloadZipName(String componentDir) { + // String payloadName; + // if( componentDir.contains( File.separator) ){ + // String delimiter = null; + // if( File.separator.equals("\\")){ + // delimiter ="\\\\"; + // } + // else{ + // delimiter = File.separator; + // } + // String[] split = componentDir.split(delimiter); + // payloadName = split[split.length-1]; + // } + // else{ + // payloadName = componentDir; + // } + // return payloadName+".zip"; + // } + // + // + // + // public List createArtifactsList(String srcDir) { + // + // List artifactsList = new + // ArrayList(); + // File srcFile = new File(srcDir); + // addFileToList(srcFile, artifactsList); + // + // return artifactsList; + // } + // + // public void addFileToList(File srcFile, List + // artifactsList) { + // + // File[] files = srcFile.listFiles(); + // + // for (int i = 0; i < files.length; i++) { + // // if the file is directory, use recursion + // if (files[i].isDirectory()) { + // addFileToList(files[i], artifactsList); + // continue; + // } + // + // String fileName = files[i].getName(); + // String artifactPath = fileName; + // + // if ( ! files[i].getName().matches("(.*)\\.y(?)ml($)")) { + // UploadArtifactInfo uploadArtifactInfo = new UploadArtifactInfo(); + // uploadArtifactInfo.setArtifactName(files[i].getName()); + // String parent = files[i].getParent(); + // + // if (parent != null) { + // System.out.println(parent); + // int lastSepartor = parent.lastIndexOf(File.separator); + // if (lastSepartor > -1) { + // String actualParent = parent.substring(lastSepartor + 1); + // artifactPath = actualParent + "/" + artifactPath; + // } + // } + // + // uploadArtifactInfo.setArtifactPath(artifactPath); + // uploadArtifactInfo.setArtifactType(getFileTypeByExtension(fileName)); + // uploadArtifactInfo.setArtifactDescription("description"); + // artifactsList.add(uploadArtifactInfo); + // + // System.out.println("artifact list: " + artifactsList); + // + // } + // + // } + // } + // + // + // public String buildArtifactListUrl (String nodesType, String + // templateVersion, String artifactName) throws FileNotFoundException{ + // //"http://172.20.43.132/sdc2/v1/catalog/resources/tosca.nodes.Root/1.0.0.wd03-SNAPSHOT/artifacts/wxs_baseline_compare.sh" + // Config config = getConfig(); + // return "\"http://" + config.getCatalogBeHost() + ":" + + // config.getCatalogBePort() + "/sdc2/v1/catalog/resources/" +nodesType + + // "/" + templateVersion + "/artifacts/" + artifactName +"\""; + // } + // + // + // public void addTopologyToES(String testFolder, String + // serviceTopologyPattern) throws IOException{ + // Config config = getConfig(); + // String url = String.format(Urls.ES_URL, config.getEsHost(), + // config.getEsPort()) + serviceTopologyPattern; + // String sourceDir = + // config.getResourceConfigDir()+File.separator+testFolder; + // Path filePath = FileSystems.getDefault().getPath(sourceDir, + // "topology.txt"); + // postFileContentsToUrl(url, filePath); + // } + // + // public void addTopologyTemplateToES(String testFolder, String + // serviceTopologyTemplatePattern) throws IOException{ + // Config config = getConfig(); + // String url = String.format(Urls.ES_URL, config.getEsHost(), + // config.getEsPort()) + serviceTopologyTemplatePattern; + // String sourceDir = + // config.getResourceConfigDir()+File.separator+testFolder; + // Path filePath = FileSystems.getDefault().getPath(sourceDir, + // "topologyTemplate.txt"); + // postFileContentsToUrl(url, filePath); + // } + // + // + // public void postFileContentsToUrl(String url, Path filePath) throws + // IOException { + // HttpClientContext localContext = HttpClientContext.create(); + // CloseableHttpResponse response = null; + // + // byte[] fileContent = Files.readAllBytes(filePath); + // + // try(CloseableHttpClient httpClient = HttpClients.createDefault()){ + // HttpPost httpPost = new HttpPost(url); + // StringEntity entity = new StringEntity(new String(fileContent) , + // ContentType.APPLICATION_JSON); + // httpPost.setEntity(entity); + // response = httpClient.execute(httpPost, localContext); + // + // } + // finally{ + // response.close(); + // } + // + // + // } + // + // + //// public boolean isPatternInEsDb(String patternToSearch)throws + // IOException{ + //// Config config = getConfig(); + //// String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, + // config.getEsHost(), config.getEsPort(),patternToSearch); + //// HttpRequest httpRequest = new HttpRequest(); + //// RestResponse restResponse = httpRequest.httpSendGet(url); + //// if (restResponse.getErrorCode() == 200){ + //// return true; + //// } + //// if (restResponse.getErrorCode() == 404){ + //// return false; + //// } + //// + //// return false; + //// } + // + // public static RestResponse deleteAllDataFromEs() throws IOException{ + // return deleteFromEsDbByPattern("_all"); + // } + // + + // + // public List buildIdArrayListByTypesIndex (String index, String + // types) throws IOException{ + // + // Config config = getConfig(); + // HttpRequest http = new HttpRequest(); + // RestResponse getResponce = + // http.httpSendGet(String.format(Urls.GET_ID_LIST_BY_INDEX_FROM_ES, + // config.getEsHost(), config.getEsPort(), index, types), null); + // + // List idArray = new ArrayList(); + // + // JsonElement jelement = new JsonParser().parse(getResponce.getResponse()); + // JsonObject jobject = jelement.getAsJsonObject(); + // JsonObject hitsObject = (JsonObject) jobject.get("hits"); + // JsonArray hitsArray = (JsonArray) hitsObject.get("hits"); + // for (int i = 0; i < hitsArray.size(); i ++){ + // JsonObject idObject = (JsonObject) hitsArray.get(i); + // String id = idObject.get("_id").toString(); + // id = id.replace("\"", ""); + // idArray.add(id); + // } + // + // return idArray; + // } + // + // public List buildCategoriesTagsListFromJson(String + // categoriesTagsJson){ + // + // ArrayList categoriesTagsArray = new ArrayList<>(); + // JsonElement jelement = new JsonParser().parse(categoriesTagsJson); + // JsonArray jArray = jelement.getAsJsonArray(); + // for (int i = 0; i < jArray.size(); i ++){ + // JsonObject categoriesTagsObject = (JsonObject) jArray.get(i); + // String categories = categoriesTagsObject.get("name").toString(); + // categoriesTagsArray.add(categories); + // } + // + // return categoriesTagsArray; + // } + // + // public ArrayList getCategoriesFromDb() throws Exception{ + // + // ArrayList categoriesFromDbArrayList = new ArrayList<>(); + // RestResponse restResponse = new RestResponse(); + // String contentTypeHeaderData = "application/json"; + // String acceptHeaderDate = "application/json"; + // + // Map headersMap = new HashMap(); + // headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(),contentTypeHeaderData); + // headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + // + // HttpRequest httpRequest = new HttpRequest(); + // String url = String.format(Urls.QUERY_NEO4J, + // Config.instance().getNeoHost(), Config.instance().getNeoPort()); + // String body = "{\"statements\" : [ { \"statement\" : \"MATCH + // (category:category) return (category)\"} ]}"; + // restResponse = httpRequest.httpSendPostWithAuth(url, body, headersMap, + // Config.instance().getNeoDBusername(), + // Config.instance().getNeoDBpassword()); + // + // if (restResponse.getResponse()==null){ + // return categoriesFromDbArrayList; + // }else{ + // JsonElement jelement = new + // JsonParser().parse(restResponse.getResponse()); + // JsonObject jobject = jelement.getAsJsonObject(); + // JsonArray resultsArray = (JsonArray) jobject.get("results"); + // JsonObject resObject = (JsonObject) resultsArray.get(0); + // JsonArray dataArray = (JsonArray) resObject.get("data"); + // for (int i = 0; i < dataArray.size(); i ++){ + // JsonObject rowObject = (JsonObject) dataArray.get(i); + // JsonArray rowArray = (JsonArray) rowObject.get("row"); + // JsonObject nameObject = (JsonObject) rowArray.get(0); + // String name = nameObject.get("name").toString(); + //// name = name.replace("\"", ""); + // categoriesFromDbArrayList.add(name); + // } + // + // + // } + // + // return categoriesFromDbArrayList; + // } + // + public static void compareArrayLists(List actualArraylList, List expectedArrayList, + String message) { + + ArrayList actual = new ArrayList(actualArraylList); + ArrayList expected = new ArrayList(expectedArrayList); + // assertEquals(message + " count got by rest API not match to " + + // message + " expected count", expected.size(),actual.size()); + expected.removeAll(actual); + assertEquals(message + " content got by rest API not match to " + message + " actual content", 0, + expected.size()); + } + + public static Object parseYamlConfig(String pattern) throws FileNotFoundException { + + Yaml yaml = new Yaml(); + Config config = getConfig(); + String configurationFile = config.getConfigurationFile(); + File file = new File(configurationFile); + // File file = new + // File("../catalog-be/src/main/resources/config/configuration.yaml"); + InputStream inputStream = new FileInputStream(file); + Map map = (Map) yaml.load(inputStream); + Object patternMap = (Object) map.get(pattern); + + return patternMap; + } + + public static String getDepArtLabelFromConfig(ArtifactTypeEnum artifactTypeEnum) throws FileNotFoundException { + + @SuppressWarnings("unchecked") + Map mapOfDepResArtTypesObjects = (Map) parseYamlConfig( + "deploymentResourceArtifacts"); + for (Map.Entry iter : mapOfDepResArtTypesObjects.entrySet()) { + if (iter.getValue().toString().contains(artifactTypeEnum.getType())) { + return iter.getKey().toLowerCase(); + } + } + + return "defaultLabelName"; + } + + + public static String multipleChar(String ch, int repeat) { + return StringUtils.repeat(ch, repeat); + } + + public static List getListOfDepResArtLabels(Boolean isLowerCase) throws FileNotFoundException { + + List listOfResDepArtTypesFromConfig = new ArrayList(); + @SuppressWarnings("unchecked") + Map resourceDeploymentArtifacts = (Map) parseYamlConfig( + "deploymentResourceArtifacts"); + if (resourceDeploymentArtifacts != null) { + + if (isLowerCase) { + for (Map.Entry iter : resourceDeploymentArtifacts.entrySet()) { + listOfResDepArtTypesFromConfig.add(iter.getKey().toLowerCase()); + } + } else { + + for (Map.Entry iter : resourceDeploymentArtifacts.entrySet()) { + listOfResDepArtTypesFromConfig.add(iter.getKey()); + } + } + } + return listOfResDepArtTypesFromConfig; + } + + public static List getListOfToscaArtLabels(Boolean isLowerCase) throws FileNotFoundException { + + List listOfToscaArtTypesFromConfig = new ArrayList(); + @SuppressWarnings("unchecked") + Map toscaArtifacts = (Map) parseYamlConfig("toscaArtifacts"); + if (toscaArtifacts != null) { + + if (isLowerCase) { + for (Map.Entry iter : toscaArtifacts.entrySet()) { + listOfToscaArtTypesFromConfig.add(iter.getKey().toLowerCase()); + } + } else { + for (Map.Entry iter : toscaArtifacts.entrySet()) { + listOfToscaArtTypesFromConfig.add(iter.getKey()); + } + } + } + return listOfToscaArtTypesFromConfig; + } + + // + // public static List getListOfResDepArtTypes() throws + // FileNotFoundException { + // + // List listOfResDepArtTypesFromConfig = new ArrayList(); + // @SuppressWarnings("unchecked") + // Map resourceDeploymentArtifacts = (Map) + // parseYamlConfig("resourceDeploymentArtifacts"); + // for (Map.Entry iter : + // resourceDeploymentArtifacts.entrySet()) { + // listOfResDepArtTypesFromConfig.add(iter.getKey()); + // } + // + // return listOfResDepArtTypesFromConfig; + // } + // + // public static List getListOfDepResInstArtTypes() throws + // FileNotFoundException { + // + // List listOfResInstDepArtTypesFromConfig = new + // ArrayList(); + // @SuppressWarnings("unchecked") + // Map resourceDeploymentArtifacts = (Map) + // parseYamlConfig("deploymentResourceInstanceArtifacts"); + // for (Map.Entry iter : + // resourceDeploymentArtifacts.entrySet()) { + // listOfResInstDepArtTypesFromConfig.add(iter.getKey().toLowerCase()); + // } + // + // return listOfResInstDepArtTypesFromConfig; + // } + // + public static List getListOfResPlaceHoldersDepArtTypes() throws FileNotFoundException { + List listResDepArtTypesFromConfig = new ArrayList(); + List listOfResDepArtLabelsFromConfig = getListOfDepResArtLabels(false); + assertNotNull("deployment artifact types list is null", listOfResDepArtLabelsFromConfig); + Object parseYamlConfig = Utils.parseYamlConfig("deploymentResourceArtifacts"); + Map mapOfDepResArtTypesObjects = (Map) Utils + .parseYamlConfig("deploymentResourceArtifacts"); + + // assertNotNull("deployment artifact types list is null", + // mapOfDepResArtTypesObjects); + if (listOfResDepArtLabelsFromConfig != null) { + for (String resDepArtType : listOfResDepArtLabelsFromConfig) { + Object object = mapOfDepResArtTypesObjects.get(resDepArtType); + if (object instanceof Map) { + Map map = (Map) object; + listResDepArtTypesFromConfig.add((String) map.get("type")); + } else { + assertTrue("return object does not instance of map", false); + } + } + } + return listResDepArtTypesFromConfig; + } + + public static Long getEpochTimeFromUTC(String time) throws ParseException { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz"); + java.util.Date date = df.parse(time); + long epoch = date.getTime(); + return epoch; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java new file mode 100644 index 0000000000..e89c6be5df --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java @@ -0,0 +1,220 @@ +/*- + * ============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.ci.tests.utils.cassandra; + +import com.datastax.driver.core.*; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.querybuilder.Select.Where; + +import org.javatuples.Pair; +import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public final class CassandraUtils { + private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName()); + + protected static Cluster cluster = null; + protected static Session session; + + protected static void initConnection(String keyspace) throws FileNotFoundException { + + String cassandraHost = Utils.getConfig().getCassandraHost(); + Boolean cassandraAuthenticate = Utils.getConfig().getCassandraAuthenticate(); + String cassandraUsername = Utils.getConfig().getCassandraUsername(); + String cassandraPassword = Utils.getConfig().getCassandraPassword(); + Boolean cassandraSsl = Utils.getConfig().getCassandraSsl(); + String cassandraTruststorePath = Utils.getConfig().getCassandraTruststorePath(); + String cassandraTruststorePassword = Utils.getConfig().getCassandraTruststorePassword(); + /* + * String cassandraAuditKeySpace= + * Utils.getConfig().getCassandraAuditKeySpace(); String + * cassandraArtifactKeySpace= + * Utils.getConfig().getCassandraArtifactKeySpace(); + */ + + Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost); + if (cassandraAuthenticate) { + // authantication + clusterBuilder.withCredentials(cassandraUsername, cassandraPassword); + } + + if (cassandraSsl) { + // ssl + System.setProperty("javax.net.ssl.trustStore", cassandraTruststorePath); + System.setProperty("javax.net.ssl.trustStorePassword", cassandraTruststorePassword); + clusterBuilder.withSSL(); + } + + cluster = clusterBuilder.build(); + session = cluster.connect(keyspace); + + } + + public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException { + + if (session == null || session.isClosed()) { + initConnection(keyspace); + } + + try { + + if (session != null) { + session.execute(QueryBuilder.truncate(keyspace, tableName)); + logger.debug("The table {}.{} was cleaned",keyspace,tableName); + } else { + throw new RuntimeException("Keyspace " + keyspace + " not connected"); + } + } finally { + // if (cluster != null) { + // cluster.close(); + // } + } + } + + public static void close() { + if (cluster != null) { + cluster.close(); + } + } + + public static void truncateAllKeyspaces() throws FileNotFoundException { + // truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE); + truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE); + } + + public static void truncateAllTables(String keyspace) throws FileNotFoundException { + + if (session == null || session.isClosed()) { + initConnection(keyspace); + } + try { + + if (session != null) { + Metadata metadata = cluster.getMetadata(); + KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace); + if (keyspaceMetadata != null) { + Collection tables = keyspaceMetadata.getTables(); + tables.forEach(table -> { + session.execute(QueryBuilder.truncate(table)); + logger.debug("Table trunceted - {}", table.getName()); + }); + } + } else { + throw new RuntimeException("Keyspace " + keyspace + " not connected"); + } + + } finally { + // if (cluster != null) { + // cluster.close(); + // } + } + } + + public static List fetchFromTable(String keyspace, String tableName, + List> fields) throws FileNotFoundException { + + List> fieldsConverted = new ArrayList<>(); + +// fields.forEach(pair -> { +// Pair newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1()); +// fieldsConverted.add(newPair); +// }); + + fields.forEach(pair ->{ + Pair newPair; + if(pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL ){ + newPair = new Pair("RESOURE_URL", pair.getValue1()); + + }else{ + newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1()); + } + fieldsConverted.add(newPair); + + }); + + return fetchFromTableQuery(keyspace, tableName, fieldsConverted); + } + + public static List fetchFromTableQuery(String keyspace, String tableName, List> fields) + throws FileNotFoundException { + + if (session == null || session.isClosed()) { + initConnection(keyspace); + } + try { + + if (session != null) { + Select select = QueryBuilder.select().all().from(keyspace, tableName); + if (fields != null) { + // Set> entrySet = + // fields.entrySet(); + // fields. + boolean multiple = (fields.size() > 1) ? true : false; + Where where = null; + int size = 0; + + for (Pair pair : fields) { + ++size; + if (size == 1) { + where = select.where(QueryBuilder.eq(pair.getValue0(), pair.getValue1())); + } else { + where.and(QueryBuilder.eq(pair.getValue0(), pair.getValue1())); + } + } + if (multiple) { + select.allowFiltering(); + } + + } + + List rows = session.execute(select).all(); + for (Row row : rows) { + logger.debug("{}", row); + } + return rows; + } + } finally { + // if (cluster != null) { + // cluster.close(); + // } + } + return null; + } + // + // public static void main(String[] args) throws FileNotFoundException { + // Map map = new HashMap<>(); + // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access"); + // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200"); + // // CassandraUtils.truncateTable("sdcartifact", "resources"); + //// CassandraUtils.truncateAllTables("sdcaudit"); + // CassandraUtils.fetchFromTable("sdcaudit", "useraccessevent", map ); + // } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java new file mode 100644 index 0000000000..024389609d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java @@ -0,0 +1,166 @@ +/*- + * ============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.ci.tests.utils.cassandra; + +import com.datastax.driver.core.*; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.querybuilder.Select.Where; +import org.javatuples.Pair; +import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileNotFoundException; +import java.util.Collection; +import java.util.List; + +public final class CassandraUtils2 { + private static Logger logger = LoggerFactory.getLogger(CassandraUtils2.class.getName()); + + public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException { + + String cassandraHost = Utils.getConfig().getCassandraHost(); + + Cluster cluster = null; + Session session; + + try { + Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost); + // authantication + // clusterBuilder.withCredentials(username,password); + // ssl + // System.setProperty("javax.net.ssl.trustStore",truststorePath); + // System.setProperty("javax.net.ssl.trustStorePassword",truststorePassword); + // clusterBuilder.withSSL(); + cluster = clusterBuilder.build(); + session = cluster.connect(keyspace); + if (session != null) { + session.execute(QueryBuilder.truncate(keyspace, tableName)); + logger.debug("The table {}.{} was cleaned",keyspace,tableName); + } else { + throw new RuntimeException("Keyspace " + keyspace + " not connected"); + } + } finally { + if (cluster != null) { + cluster.close(); + } + } + } + + public static void truncateAllKeyspaces() throws FileNotFoundException { + truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE); + truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE); + } + + public static void truncateAllTables(String keyspace) throws FileNotFoundException { + String cassandraHost = Utils.getConfig().getCassandraHost(); + + Cluster cluster = null; + Session session; + + try { + cluster = Cluster.builder().addContactPoint(cassandraHost).build(); + session = cluster.connect(keyspace); + if (session != null) { + Metadata metadata = cluster.getMetadata(); + KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace); + if (keyspaceMetadata != null) { + Collection tables = keyspaceMetadata.getTables(); + tables.forEach(table -> { + session.execute(QueryBuilder.truncate(table)); + logger.debug("Table trunceted - {}", table.getName()); + }); + } + } else { + throw new RuntimeException("Keyspace " + keyspace + " not connected"); + } + + } finally { + if (cluster != null) { + cluster.close(); + } + } + } + + public static List fetchFromTable(String keyspace, String tableName, + List> fields) throws FileNotFoundException { + + // List> + // Map + + Cluster cluster = null; + Session session; + String cassandraHost = Utils.getConfig().getCassandraHost(); + + try { + cluster = Cluster.builder().addContactPoint(cassandraHost).build(); + session = cluster.connect(keyspace); + if (session != null) { + Select select = QueryBuilder.select().all().from(keyspace, tableName); + if (fields != null) { + // Set> entrySet = + // fields.entrySet(); + // fields. + boolean multiple = (fields.size() > 1) ? true : false; + Where where = null; + int size = 0; + + for (Pair pair : fields) { + ++size; + if (size == 1) { + where = select.where(QueryBuilder.eq(pair.getValue0().getDisplayName(), pair.getValue1())); + } else { + where.and(QueryBuilder.eq(pair.getValue0().getDisplayName(), pair.getValue1())); + } + } + if (multiple) { + select.allowFiltering(); + } + + } + + List rows = session.execute(select).all(); + for (Row row : rows) { + logger.debug("{}", row); + } + return rows; + } + } finally { + if (cluster != null) { + cluster.close(); + } + } + return null; + } + // + // public static void main(String[] args) throws FileNotFoundException { + // Map map = new HashMap<>(); + // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access"); + // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200"); + // // CassandraUtils.truncateTable("sdcartifact", "resources"); + //// CassandraUtils.truncateAllTables("sdcaudit"); + // CassandraUtils.fetchFromTable("sdcaudit", "useraccessevent", map ); + // } + +} 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 new file mode 100644 index 0000000000..207c4bbe02 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java @@ -0,0 +1,732 @@ +/*- + * ============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.ci.tests.utils.general; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.helpers.AbstractUnmarshallerImpl; +import javax.xml.ws.Response; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.tuple.Pair; +import org.aspectj.apache.bcel.classfile.Code; +import org.json.JSONException; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails; +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.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +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.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +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.ComponentInstanceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils; +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.api.ArtifactGroupTypeEnum; +import org.testng.SkipException; + +import com.google.gson.Gson; + +import fj.data.Either; + +public final class AtomicOperationUtils { + + static final String basicAuthentication = "Basic Y2k6MTIzNDU2"; + + private AtomicOperationUtils() { + throw new UnsupportedOperationException(); + } + + // *********** RESOURCE **************** + /** + * Import a vfc From tosca file + * + * @param filePath + * @param fileName + * @return + * @throws IOException + * @throws JSONException + */ + public static Either importResource(String filePath, String fileName) { + try { + User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource("ciTmpVFC"); + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null); + return buildResourceFromResponse(importResourceResponse); + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } + + public static Either createResourceByType(ResourceTypeEnum resourceType, UserRoleEnum userRole, Boolean validateState) { + try { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByType(resourceType, defaultUser); + RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser); + + if (validateState) { + assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + + if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse()); + return Either.left(resourceResponseObject); + } + return Either.right(resourceResp); + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } + + public static Either createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState) + throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, normativeTypes, resourceCategory, defaultUser); + RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser); + + if (validateState) { + assertTrue("Actual Response Code is: " + resourceResp.getErrorCode(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + + if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + // Resource resourceResponseObject = ResponseParser + // .convertResourceResponseToJavaObject(resourceResp.getResponse()); + Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class); + return Either.left(resourceResponseObject); + } + return Either.right(resourceResp); + } + + public static Either createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum resourceType, Resource resourceNormativeType, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState) + throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, resourceNormativeType, resourceCategory, defaultUser); + RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser); + + if (validateState) { + assertTrue("actual result: " + resourceResp.getResponseMessage(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + + if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + // Resource resourceResponseObject = ResponseParser + // .convertResourceResponseToJavaObject(resourceResp.getResponse()); + Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class); + return Either.left(resourceResponseObject); + } + return Either.right(resourceResp); + } + + // *********** SERVICE **************** + + public static Either createDefaultService(UserRoleEnum userRole, Boolean validateState) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(defaultUser); + RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser); + + if (validateState) { + assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + } + + if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse()); + return Either.left(serviceResponseObject); + } + return Either.right(createServiceResp); + } + + public static Either createServiceByCategory(ServiceCategoriesEnum category, UserRoleEnum userRole, Boolean validateState) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(category, defaultUser); + RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser); + + if (validateState) { + assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + } + + if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse()); + return Either.left(serviceResponseObject); + } + return Either.right(createServiceResp); + } + + // *********** PRODUCT **************** + + public static Either createDefaultProduct(UserRoleEnum userRole, Boolean validateState) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(); + RestResponse createProductResp = ProductRestUtils.createProduct(defaultProduct, defaultUser); + + if (validateState) { + assertTrue(createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED); + } + + if (createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED) { + Product productResponseJavaObject = ResponseParser.convertProductResponseToJavaObject(createProductResp.getResponse()); + return Either.left(productResponseJavaObject); + } + return Either.right(createProductResp); + } + + // public static ComponentReqDetails + // convertCompoentToComponentReqDetails(Component component){ + // + // ComponentReqDetails componentReqDetails = + // ElementFactory.getDefaultService(); + // componentReqDetails.setName(component.getName()); + // componentReqDetails.setDescription(component.getDescription()); + // componentReqDetails.setTags(component.getTags()); + // componentReqDetails.setContactId(component.getContactId()); + // componentReqDetails.setIcon(component.getIcon()); + // componentReqDetails.setUniqueId(component.getUniqueId()); + // componentReqDetails.setCreatorUserId(component.getCreatorUserId()); + // componentReqDetails.setCreatorFullName(component.getCreatorFullName()); + // componentReqDetails.setLastUpdaterUserId(component.getLastUpdaterUserId()); + // componentReqDetails.setLastUpdaterFullName(component.getLastUpdaterFullName()); + // componentReqDetails.setCreationDate(component.getCreationDate()); + // componentReqDetails.setLastUpdateDate(component.getLastUpdateDate()); + // componentReqDetails.setLifecycleState(component.getLifecycleState()); + // componentReqDetails.setVersion(component.getVersion()); + // componentReqDetails.setUuid(component.getUUID()); + // componentReqDetails.setCategories(component.getCategories()); + // componentReqDetails.setProjectCode(component.getProjectCode()); + // + // return componentReqDetails; + // } + + // *********** LIFECYCLE *************** + + public static Pair changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception { + + Boolean isValidationFailed = false; + RestResponse lifeCycleStatesResponse = null; + User defaultUser = ElementFactory.getDefaultUser(userRole); + + LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString()); + + if (curentCompState == targetState) { + component = getCompoenntObject(component, userRole); + return Pair.of(component, null); + } + // List lifeCycleStatesEnumOrigList = new + // ArrayList(EnumSet.allOf(LifeCycleStatesEnum.class)); + + ArrayList lifeCycleStatesEnumList = new ArrayList(); + if (curentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) { + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); + } else { + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFICATIONREQUEST.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.STARTCERTIFICATION.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString()); + } + for (int i = 0; i < lifeCycleStatesEnumList.size(); i++) { + if (lifeCycleStatesEnumList.get(i).equals(curentCompState.name())) { + int a; + a = (i == lifeCycleStatesEnumList.size() - 1) ? 0 : i + 1; + + for (int n = a; n < lifeCycleStatesEnumList.size(); n++) { + if (lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.STARTCERTIFICATION.name()) || lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.CERTIFY.name())) { + defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + } else + defaultUser = ElementFactory.getDefaultUser(userRole); + + lifeCycleStatesResponse = LifecycleRestUtils.changeComponentState(component, defaultUser, LifeCycleStatesEnum.findByState(lifeCycleStatesEnumList.get(n))); + if (lifeCycleStatesResponse.getErrorCode() != LifecycleRestUtils.STATUS_CODE_SUCCESS) + isValidationFailed = true; + if (lifeCycleStatesEnumList.get(n).equals(targetState.toString()) || isValidationFailed == true) { + break; + } + } + } + + } + Component componentJavaObject = getCompoenntObject(component, userRole); + + if (validateState == true && isValidationFailed == true) { + assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false); + + return Pair.of(componentJavaObject, lifeCycleStatesResponse); + } + + if (isValidationFailed == true) { + return Pair.of(componentJavaObject, lifeCycleStatesResponse); + } + + return Pair.of(componentJavaObject, lifeCycleStatesResponse); + } + + public static RestResponse distributeService(Component component, Boolean validateState) throws Exception { + + Service service = (Service) component; + + User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS); + User governotUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); + + ServiceReqDetails serviceDetails = new ServiceReqDetails(service); + RestResponse distributionService = null; + + RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTION_APPROVED); + if (approveDistribution.getErrorCode() == 200) { + distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "approveService", DistributionStatusEnum.DISTRIBUTED); + } + + if (validateState) { + assertTrue(approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); + assertTrue(distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); + return distributionService; + } + + return distributionService; + + } + + // *********** ARTIFACTS ***************** + + public static Either uploadArtifactByType(ArtifactTypeEnum artifactType, Component component, UserRoleEnum userRole, Boolean deploymentTrue, Boolean validateState) throws Exception { + + User defaultUser = ElementFactory.getDefaultUser(userRole); + ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(null, artifactType, deploymentTrue); + if (deploymentTrue == false) + artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType()); + RestResponse uploadArtifactResp = ArtifactRestUtils.uploadArtifact(artifactDetails, component, defaultUser); + + if (validateState) { + assertTrue("artifact upload failed: " + artifactDetails.getArtifactName(), uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + if (uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) { + ArtifactDefinition artifactJavaObject = ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactResp.getResponse()); + return Either.left(artifactJavaObject); + } + return Either.right(uploadArtifactResp); + } + + // *********** CONTAINERS ***************** + /** + * Adds Component instance to Component + * + * @param compInstParent + * @param compContainer + * @return + */ + public static Either addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer) { + return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false); + } + + public static Either addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState) { + try { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent); + RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer); + + if (validateState) { + if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND) + { + throw new SkipException("Open bug DE262001"); + } + else{ + assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " + ServiceRestUtils.STATUS_CODE_CREATED, createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + } + } + + if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + ComponentInstance componentInstance = ResponseParser.convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse()); + return Either.left(componentInstance); + } + return Either.right(createComponentInstance); + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } + + public static Resource getResourceObject(Component containerDetails, UserRoleEnum userRole) throws Exception { + // User defaultUser = ElementFactory.getDefaultUser(userRole); + RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId()); + Resource container = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + return container; + } + + public static Resource getResourceObject(String uniqueId) throws Exception { + RestResponse restResponse = ResourceRestUtils.getResource(uniqueId); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + return resource; + } + + public static Resource getResourceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String resourceName, String resourceVersion) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails); + RestResponse resourceResponse = ResourceRestUtils.getResourceByNameAndVersion(defaultUser.getUserId(), resourceName, resourceVersion); + Resource container = ResponseParser.convertResourceResponseToJavaObject(resourceResponse.getResponse()); + return container; + } + + public static Service getServiceObject(Component containerDetails, UserRoleEnum userRole) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser); + Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse()); + return container; + } + + public static Service getServiceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String serviceName, String serviceVersion) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails); + RestResponse serviceResponse = ServiceRestUtils.getServiceByNameAndVersion(defaultUser, serviceName, serviceVersion); + Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse()); + return container; + } + + public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId()); + Product container = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse()); + return container; + } + + public static Component getCompoenntObject(Component containerDetails, UserRoleEnum userRole) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + + switch (containerDetails.getComponentType()) { + case RESOURCE: + RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId()); + containerDetails = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse()); + break; + case SERVICE: + RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser); + containerDetails = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse()); + break; + case PRODUCT: + RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId()); + containerDetails = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse()); + break; + default: + break; + } + return containerDetails; + } + + public static Component convertReposnseToComponentObject(Component containerDetails, RestResponse restresponse) throws Exception { + + switch (containerDetails.getComponentType()) { + case RESOURCE: + containerDetails = ResponseParser.convertResourceResponseToJavaObject(restresponse.getResponse()); + break; + case SERVICE: + containerDetails = ResponseParser.convertServiceResponseToJavaObject(restresponse.getResponse()); + break; + case PRODUCT: + containerDetails = ResponseParser.convertProductResponseToJavaObject(restresponse.getResponse()); + break; + default: + break; + } + return containerDetails; + } + + public static Either associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws Exception { + + User defaultUser = ElementFactory.getDefaultUser(userRole); + RestResponse associate2ResourceInstancesResponse = ResourceRestUtils.associate2ResourceInstances(containerDetails, fromNode, toNode, assocType, defaultUser); + + if (validateState) { + assertTrue(associate2ResourceInstancesResponse.getErrorCode() == ServiceRestUtils.STATUS_CODE_SUCCESS); + } + + if (associate2ResourceInstancesResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS) { + + switch (containerDetails.getComponentType()) { + case RESOURCE: + containerDetails = ResponseParser.convertResourceResponseToJavaObject(associate2ResourceInstancesResponse.getResponse()); + break; + case SERVICE: + containerDetails = ResponseParser.convertServiceResponseToJavaObject(associate2ResourceInstancesResponse.getResponse()); + break; + case PRODUCT: + containerDetails = ResponseParser.convertProductResponseToJavaObject(associate2ResourceInstancesResponse.getResponse()); + break; + default: + break; + } + + return Either.left(containerDetails); + } + return Either.right(associate2ResourceInstancesResponse); + + } + + public static Either, RestResponse> changeComponentInstanceVersion(Component containerDetails, ComponentInstance componentInstanceToReplace, Component newInstance, UserRoleEnum userRole, Boolean validateState) + throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + + RestResponse changeComponentInstanceVersionResp = ComponentInstanceRestUtils.changeComponentInstanceVersion(containerDetails, componentInstanceToReplace, newInstance, defaultUser); + if (validateState) { + assertTrue("change ComponentInstance version failed: " + changeComponentInstanceVersionResp.getResponseMessage(), changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) { + + Component compoenntObject = AtomicOperationUtils.getCompoenntObject(containerDetails, userRole); + ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse()); + + return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject)); + } + + return Either.right(changeComponentInstanceVersionResp); + } + + // *********** PROPERTIES ***************** + + public static Either addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception { + + User defaultUser = ElementFactory.getDefaultUser(userRole); + Map propertyToSend = new HashMap(); + propertyToSend.put(propDetails.getName(), propDetails); + Gson gson = new Gson(); + RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser); + + if (validateState) { + assertTrue("add property to resource failed: " + addPropertyResponse.getErrorCode(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED); + } + + if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) { + ComponentInstanceProperty compInstProp = null; + String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName()); + compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property)); + return Either.left(compInstProp); + } + return Either.right(addPropertyResponse); + } + + // Benny + public static Either updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception { + + User defaultUser = ElementFactory.getDefaultUser(userRole); + Map propertyToSend = new HashMap(); + propertyToSend.put(propDetails.getName(), propDetails); + Gson gson = new Gson(); + RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser); + + if (validateState) { + assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) { + ComponentInstanceProperty compInstProp = null; + String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName()); + compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property)); + return Either.left(compInstProp); + } + return Either.right(addPropertyResponse); + } + + public static RestResponse deletePropertyOfResource(String resourceId, String propertyId, UserRoleEnum userRole) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + return PropertyRestUtils.deleteProperty(resourceId, propertyId, defaultUser); + } + + public static Either addDefaultPropertyToResource(PropertyTypeEnum propertyType, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception { + + User defaultUser = ElementFactory.getDefaultUser(userRole); + PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType); + Map propertyToSend = new HashMap(); + propertyToSend.put(propDetails.getName(), propDetails); + Gson gson = new Gson(); + RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser); + + if (validateState) { + assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED); + } + + if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) { + ComponentInstanceProperty compInstProp = null; + String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName()); + compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property)); + + return Either.left(compInstProp); + } + return Either.right(addPropertyResponse); + } + + public static RestResponse createDefaultConsumer(Boolean validateState) { + try { + ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails(); + RestResponse createResponse = ConsumerRestUtils.createConsumer(defaultConsumerDefinition, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)); + BaseRestUtils.checkCreateResponse(createResponse); + + if (validateState) { + assertTrue(createResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + return createResponse; + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } + + /** + * Builds Resource From rest response + * + * @param resourceResp + * @return + */ + public static Either buildResourceFromResponse(RestResponse resourceResp) { + Either result; + if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse()); + result = Either.left(resourceResponseObject); + } else { + result = Either.right(resourceResp); + } + return result; + } + + private static class AtomicOperationException extends RuntimeException { + private AtomicOperationException(Exception e) { + super(e); + } + + private static final long serialVersionUID = 1L; + }; + + /** + * Import resource from CSAR + * + * @param resourceType + * @param userRole + * @param fileName + * @param filePath + * @return Resource + * @throws Exception + */ + public static Resource importResourceFromCSAR(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, String... filePath) throws Exception { + // Get the CSARs path + String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ; + if (filePath != null && filePath.length > 0) { + realFilePath = filePath.toString(); + } + + // Create default import resource & user + ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource(); + User sdncModifierDetails = ElementFactory.getDefaultUser(userRole); + + byte[] data = null; + Path path = Paths.get(realFilePath + File.separator + fileName); + data = Files.readAllBytes(path); + String payloadName = fileName; + String payloadData = Base64.encodeBase64String(data); + resourceDetails.setPayloadData(payloadData); + resourceDetails.setCsarUUID(payloadName); + resourceDetails.setPayloadName(payloadName); + resourceDetails.setResourceType(resourceType.name()); + + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); + BaseRestUtils.checkCreateResponse(createResource); + return ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + }; + + public static Either importResourceByFileName(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, Boolean validateState, String... filePath) throws IOException { + + String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ; + if (filePath != null && filePath.length > 0) { + realFilePath = filePath.toString(); + } + + try { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(defaultUser); + ImportReqDetails defaultImportResource = ElementFactory.getDefaultImportResource(defaultResource); + ImportUtils.getImportResourceDetailsByPathAndName(defaultImportResource, realFilePath, fileName); + RestResponse resourceResp = ResourceRestUtils.createResource(defaultImportResource, defaultUser); + + if (validateState) { + assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + + if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse()); + return Either.left(resourceResponseObject); + } + return Either.right(resourceResp); + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } + + public static Either getServiceToscaArtifactPayload(Service service, String artifactType) throws Exception { + + String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, "localhost", "8080", service.getUniqueId(), service.getToscaArtifacts().get(artifactType).getUniqueId()); + String userId = service.getLastUpdaterUserId(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); +// headersMap.put("X-ECOMP-InstanceID", "test"); + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) { + return Either.right(response); + } + return Either.left(response.getResponse()); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java new file mode 100644 index 0000000000..619d279b62 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java @@ -0,0 +1,344 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.general; + +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED; +import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS; + +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +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.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +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.ExpectedProductAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.Constants; + +public class Convertor { + // ***** resource ***** + public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails, + String resourceVersion) { + return convertToRespObject(resourceDetails, resourceVersion, UserRoleEnum.ADMIN.getUserId(), + UserRoleEnum.ADMIN.getUserName()); + + } + + public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails) { + return convertToRespObject(resourceDetails, resourceDetails.getVersion(), UserRoleEnum.ADMIN.getUserId(), + UserRoleEnum.ADMIN.getUserName()); + + } + + public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails, + String resourceVersion, User user) { + return convertToRespObject(resourceDetails, resourceVersion, user.getUserId(), user.getFullName()); + + } + + private static ResourceRespJavaObject convertToRespObject(ResourceReqDetails resourceDetails, + String resourceVersion, String userId, String userName) { + ResourceRespJavaObject resourceRespJavaObject = new ResourceRespJavaObject(); + + resourceRespJavaObject.setUniqueId(resourceDetails.getUniqueId()); + resourceRespJavaObject.setName(resourceDetails.getName()); + resourceRespJavaObject.setCreatorUserId(resourceDetails.getCreatorUserId()); + resourceRespJavaObject.setCreatorFullName(resourceDetails.getCreatorFullName()); + resourceRespJavaObject.setLastUpdaterUserId(userId); + resourceRespJavaObject.setLastUpdaterFullName(userName); + resourceRespJavaObject.setDescription(resourceDetails.getDescription()); + resourceRespJavaObject.setIcon(resourceDetails.getIcon()); + resourceRespJavaObject.setTags(resourceDetails.getTags()); + resourceRespJavaObject.setIsHighestVersion("true"); + resourceRespJavaObject.setCategories(resourceDetails.getCategories()); + resourceRespJavaObject.setLifecycleState( + resourceDetails.getLifecycleState() != null ? resourceDetails.getLifecycleState().toString() + : LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceRespJavaObject.setDerivedFrom(resourceDetails.getDerivedFrom()); + resourceRespJavaObject.setVendorName(resourceDetails.getVendorName()); + resourceRespJavaObject.setVendorRelease(resourceDetails.getVendorRelease()); + resourceRespJavaObject.setContactId(resourceDetails.getContactId()); + resourceRespJavaObject.setAbstractt("false"); + resourceRespJavaObject.setVersion(resourceVersion); + resourceRespJavaObject.setCost(resourceDetails.getCost()); + resourceRespJavaObject.setLicenseType(resourceDetails.getLicenseType()); + resourceRespJavaObject.setResourceType(resourceDetails.getResourceType()); + + return resourceRespJavaObject; + + } + + // ********** service ************** + + // public static ServiceRespJavaObject + // constructFieldsForRespValidation(ServiceReqDetails serviceDetails, String + // serviceVersion, User user) { + // return convertToRespObject(serviceDetails, serviceVersion, + // user.getUserId(), user.getFullName()); + // + // } + // + // private static ServiceRespJavaObject + // convertToRespObject(ServiceReqDetails serviceDetails, String + // serviceVersion, String userId, String userName) { + // ServiceRespJavaObject serviceRespJavaObject = new + // ServiceRespJavaObject(); + // + // serviceRespJavaObject.setUniqueId(serviceDetails.getUniqueId()); + // serviceRespJavaObject.setName(serviceDetails.getName()); + // serviceRespJavaObject.setCreatorUserId(userId); + // serviceRespJavaObject.setCreatorFullName(userName); + // serviceRespJavaObject.setLastUpdaterUserId(userId); + // serviceRespJavaObject.setLastUpdaterFullName(userName); + // serviceRespJavaObject.setDescription(serviceDetails.getDescription()); + // serviceRespJavaObject.setIcon(serviceDetails.getIcon()); + // serviceRespJavaObject.setCategory(serviceDetails.getCategory()); + // serviceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + // serviceRespJavaObject.setContactId(serviceDetails.getContactId()); + // serviceRespJavaObject.setVersion(serviceVersion); + // + // return serviceRespJavaObject; + // } + + // ********** product ************** + + public static Product constructFieldsForRespValidation(ProductReqDetails productDetails, String productVersion, + User user) { + return convertToRespObject(productDetails, productVersion, user.getUserId(), user.getFullName()); + } + + private static Product convertToRespObject(ProductReqDetails productDetails, String productVersion, String userId, + String userName) { + Product expectedProduct = new Product(); + + expectedProduct.setUniqueId(productDetails.getUniqueId()); + expectedProduct.setName(productDetails.getName()); + expectedProduct.setFullName(productDetails.getFullName()); + expectedProduct.setCreatorUserId(productDetails.getCreatorUserId()); + expectedProduct.setCreatorFullName(productDetails.getCreatorFullName()); + expectedProduct.setLastUpdaterUserId(userId); + expectedProduct.setLastUpdaterFullName(userName); + expectedProduct.setDescription(productDetails.getDescription()); + // expectedProduct.setIcon(resourceDetails.getIcon()); + expectedProduct.setTags(productDetails.getTags()); + expectedProduct.setHighestVersion(true); + List categories = productDetails.getCategories(); + if (categories == null) { + categories = new ArrayList<>(); + } + expectedProduct.setCategories(categories); + expectedProduct.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + expectedProduct.setVersion(productVersion); + expectedProduct.setContacts(productDetails.getContacts()); + return expectedProduct; + } + + // ***** audit ***** + + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails, + String resourceVersion) { + return convertToAuditObject(resourceDetails, resourceVersion, UserRoleEnum.ADMIN.getUserId(), + UserRoleEnum.ADMIN.getUserName()); + } + + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation( + ResourceReqDetails resourceDetails) { + return convertToAuditObject(resourceDetails, resourceDetails.getVersion(), UserRoleEnum.ADMIN.getUserId(), + UserRoleEnum.ADMIN.getUserName()); + } + + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails, + String resourceVersion, User user) { + return convertToAuditObject(resourceDetails, resourceVersion, user.getUserId(), user.getFullName()); + } + + private static ExpectedResourceAuditJavaObject convertToAuditObject(ResourceReqDetails resourceDetails, + String resourceVersion, String userId, String userName) { + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + + expectedResourceAuditJavaObject.setAction("Checkout"); + expectedResourceAuditJavaObject.setModifierName(userName); + expectedResourceAuditJavaObject.setModifierUid(userId); + expectedResourceAuditJavaObject.setStatus("200.0"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName()); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(resourceVersion) - 0.1f)); + expectedResourceAuditJavaObject.setCurrVersion(resourceVersion); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setComment(null); + + return expectedResourceAuditJavaObject; + } + + public static ExpectedProductAudit constructFieldsForAuditValidation(Product productDetails, String action, + User user, ActionStatus actionStatus, String prevVersion, String currVersion, LifecycleStateEnum prevState, + LifecycleStateEnum currState, String uuid, String... errorMessageParams) throws FileNotFoundException { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + return convertToAuditObject(productDetails, action, user, errorInfo, prevVersion, currVersion, prevState, + currState, uuid, errorMessageParams); + } + + private static ExpectedProductAudit convertToAuditObject(Product productDetails, String action, User user, + ErrorInfo errorInfo, String prevVersion, String currVersion, LifecycleStateEnum prevState, + LifecycleStateEnum currState, String uuid, String... errorMessageParams) { + ExpectedProductAudit expectedProductAudit = new ExpectedProductAudit(); + + expectedProductAudit.setACTION(action); + String userUserId = user.getUserId(); + String userFullName; + if (StringUtils.isEmpty(user.getFirstName()) && StringUtils.isEmpty(user.getLastName())) { + userFullName = ""; + } else { + userFullName = user.getFullName(); + } + if (StringUtils.isEmpty(userUserId)) { + userUserId = "UNKNOWN"; + } + expectedProductAudit.setMODIFIER( + !StringUtils.isEmpty(userFullName) ? userFullName + "(" + userUserId + ")" : "(" + userUserId + ")"); + expectedProductAudit.setSTATUS(Integer.toString(errorInfo.getCode())); + expectedProductAudit.setDESC(errorInfo.getAuditDesc((Object[]) (errorMessageParams))); + expectedProductAudit + .setRESOURCE_NAME(productDetails != null ? productDetails.getName() : Constants.EMPTY_STRING); + expectedProductAudit.setRESOURCE_TYPE("Product"); + expectedProductAudit.setPREV_VERSION(prevVersion); + expectedProductAudit.setCURR_VERSION(currVersion); + expectedProductAudit.setPREV_STATE(prevState != null ? prevState.name() : Constants.EMPTY_STRING); + expectedProductAudit.setCURR_STATE(currState != null ? currState.name() : Constants.EMPTY_STRING); + expectedProductAudit.setSERVICE_INSTANCE_ID(uuid); + return expectedProductAudit; + } + + //////////////// + // Convertor.constructFieldsForAuditValidationSuccess(addUser, + //////////////// sdncAdminUser, mechIdUser, null, STATUS_CODE_CREATED); + public static ExpectedUserCRUDAudit constructFieldsForAuditValidation(String action, User userModifier, + ActionStatus actionStatus, User userAfter, User userBefore, Object... variables) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + ExpectedUserCRUDAudit expectedAddUserAuditJavaObject = new ExpectedUserCRUDAudit(); + expectedAddUserAuditJavaObject.setAction(action); + expectedAddUserAuditJavaObject.setModifier( + userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")" + : "(" + userModifier.getUserId() + ")"); + String status = Integer.toString(errorInfo.getCode()); + expectedAddUserAuditJavaObject.setStatus(status); + if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) { + expectedAddUserAuditJavaObject.setDesc("OK"); + } else { + expectedAddUserAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + } + expectedAddUserAuditJavaObject.setUserBefore(userBefore != null + ? userBefore.getUserId() + ", " + userBefore.getFirstName() + " " + userBefore.getLastName() + ", " + + userBefore.getEmail() + ", " + userBefore.getRole() + : Constants.EMPTY_STRING); + expectedAddUserAuditJavaObject.setUserAfter(userAfter != null + ? userAfter.getUserId() + ", " + userAfter.getFirstName() + " " + userAfter.getLastName() + ", " + + userAfter.getEmail() + ", " + userAfter.getRole() + : Constants.EMPTY_STRING); + return expectedAddUserAuditJavaObject; + } + + // For RESOURCE and SERVICE same Audit + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation( + ComponentReqDetails componentDetails, String action, User userModifier, ActionStatus actionStatus, + String currVersion, String prevVersion, String curState, String prevState, String uuid, String comment, + Object... variables) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(action); + expectedResourceAuditJavaObject.setMODIFIER( + userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")" + : "(" + userModifier.getUserId() + ")"); + String status = Integer.toString(errorInfo.getCode()); + expectedResourceAuditJavaObject.setStatus(status); + if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) { + expectedResourceAuditJavaObject.setDesc("OK"); + } else { + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + } + expectedResourceAuditJavaObject.setCurrState(curState); + expectedResourceAuditJavaObject.setPrevState(prevState); + expectedResourceAuditJavaObject.setCurrVersion(currVersion); + expectedResourceAuditJavaObject.setPrevVersion(prevVersion); + expectedResourceAuditJavaObject.setComment(comment); + expectedResourceAuditJavaObject.setSERVICE_INSTANCE_ID(uuid); + if (componentDetails instanceof ServiceReqDetails) { + expectedResourceAuditJavaObject.setResourceName(((ServiceReqDetails) componentDetails).getName()); + expectedResourceAuditJavaObject.setResourceType("Service"); + } + if (componentDetails instanceof ResourceReqDetails) { + expectedResourceAuditJavaObject.setResourceName(((ResourceReqDetails) componentDetails).getName()); + expectedResourceAuditJavaObject.setResourceType("Resource"); + } + return expectedResourceAuditJavaObject; + } + + // Distribution Service Audit + public static ExpectedResourceAuditJavaObject constructFieldsForDistributionAuditValidation( + ComponentReqDetails componentDetails, String action, User userModifier, ActionStatus actionStatus, + String currVersion, String distCurrStatus, String distProvStatus, String curState, String uuid, + String comment, Object... variables) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(action); + expectedResourceAuditJavaObject.setMODIFIER( + userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")" + : "(" + userModifier.getUserId() + ")"); + String status = Integer.toString(errorInfo.getCode()); + expectedResourceAuditJavaObject.setStatus(status); + if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) { + expectedResourceAuditJavaObject.setDesc("OK"); + } else { + expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + } + expectedResourceAuditJavaObject.setCurrState(curState); + expectedResourceAuditJavaObject.setCurrVersion(currVersion); + expectedResourceAuditJavaObject.setDcurrStatus(distCurrStatus); + expectedResourceAuditJavaObject.setDprevStatus(distProvStatus); + expectedResourceAuditJavaObject.setComment(comment); + expectedResourceAuditJavaObject.setSERVICE_INSTANCE_ID(uuid); + if (componentDetails instanceof ServiceReqDetails) { + expectedResourceAuditJavaObject.setResourceName(((ServiceReqDetails) componentDetails).getName()); + expectedResourceAuditJavaObject.setResourceType("Service"); + } + return expectedResourceAuditJavaObject; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java new file mode 100644 index 0000000000..5c23b5f3fe --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java @@ -0,0 +1,997 @@ +/*- + * ============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.ci.tests.utils.general; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +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.LifecycleStateEnum; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +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.expected.ExpectedExternalAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.util.ValidationUtils; + +public class ElementFactory { + + private static final String CI_SERVICE = "ciService"; + private static final String CI_RES = "ciRes"; + private static final String CI_PRODUCT = "CiProduct"; + private static String DEFAULT_ARTIFACT_LABEL = "artifact1"; + private static final String RESOURCE_INSTANCE_POS_X = "20"; + private static final String RESOURCE_INSTANCE_POS_Y = "20"; + private static final String RESOURCE_INSTANCE_DESCRIPTION = "description"; + + // *** RESOURCE *** + + public static ResourceReqDetails getDefaultResource() { + return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003"); + } + + public static ResourceReqDetails getDefaultResource(ResourceCategoryEnum category) { + return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, category, "jh0003"); + } + + public static ResourceReqDetails getDefaultResource(String contactId) { + return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId); + } + + public static ResourceReqDetails getDefaultResource(User modifier) { + return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, modifier.getUserId()); + } + + public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, ResourceCategoryEnum category) { + return getDefaultResource(CI_RES, derivedFrom, category, "jh0003"); + } + + public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom) { + return getDefaultResource(CI_RES, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003"); + } + + public static ResourceReqDetails getDefaultResource(String resourceName, NormativeTypesEnum derivedFrom) { + return getDefaultResource(resourceName, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003"); + } + + public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, String contactId) { + return getDefaultResource(CI_RES, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId); + } + + // New + public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName) { + return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003", ResourceType.toString()); + } + + public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, User user) { + return getDefaultResourceByType(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_LOAD_BALANCER, user.getUserId(), ResourceType.toString()); + } + + public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, User user) { + return getDefaultResourceByType(CI_RES, normativeTypes, resourceCategory, user.getUserId(), resourceType.toString()); + } + + public static PropertyReqDetails getDefaultMapProperty(PropertyTypeEnum innerType) { + return getPropertyDetails(innerType); + } + + public static PropertyReqDetails getDefaultMapProperty() { + return getPropertyDetails(PropertyTypeEnum.STRING_MAP); + } + + public static ResourceReqDetails getDefaultResource(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId) { + resourceName = (resourceName + generateUUIDforSufix()); + String description = "Represents a generic software component that can be managed and run by a Compute Node Type."; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(derived.normativeName); + String vendorName = "ATT Tosca"; + String vendorRelease = "1.0.0.wd03"; + String icon = "defaulticon"; + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory()); + + return resourceDetails; + + } + + public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, Resource normativeTypes, ResourceCategoryEnum resourceCategory, User user) { + return getDefaultResource(CI_RES + resourceType, normativeTypes, resourceCategory, user.getUserId()); + } + + public static ResourceReqDetails getDefaultResource(String resourceName, Resource derived, ResourceCategoryEnum category, String contactId) { + resourceName = (resourceName + generateUUIDforSufix()); + String description = "Represents a generic software component that can be managed and run by a Compute Node Type."; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add(derived.getToscaResourceName()); + String vendorName = "ATT Tosca"; + String vendorRelease = "1.0.0.wd03"; + String icon = "defaulticon"; + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory()); + + return resourceDetails; + + } + + public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, ResourceTypeEnum resourceType) { + return getDefaultResourceByType(resourceName, derived, category, contactId, resourceType.toString()); + } + + // New + public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType) { + resourceName = (resourceName + resourceType + generateUUIDforSufix()); + String description = "Represents a generic software component that can be managed and run by a Compute Node Type."; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + ArrayList derivedFrom = null; + if (derived != null) { + derivedFrom = new ArrayList(); + derivedFrom.add(derived.normativeName); + } + String vendorName = "ATT Tosca"; + String vendorRelease = "1.0.0.wd03"; + String icon = "defaulticon"; + ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon, resourceType.toString()); + resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory()); + return resourceDetails; + } + + public static ResourceExternalReqDetails getDefaultResourceByType(String resourceName, ResourceCategoryEnum category, String contactId, String resourceType) { + resourceName = (resourceName + resourceType + generateUUIDforSufix()); + String description = "Represents a generic software component that can be managed and run by a Compute Node Type."; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + String vendorName = "ATT Tosca"; + String vendorRelease = "1.0.0.wd03"; + String icon = "defaulticon"; + ResourceExternalReqDetails resourceDetails = new ResourceExternalReqDetails(resourceName, description, resourceTags, + vendorName, vendorRelease, contactId, icon, + resourceType.toString(), category.getCategory(), category.getSubCategory()); + return resourceDetails; + } + + // New + public static ImportReqDetails getDefaultImportResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType) { + resourceName = (resourceName + resourceType + generateUUIDforSufix()); + String description = "Represents a generic software component that can be managed and run by a Compute Node Type."; + ArrayList resourceTags = new ArrayList(); + resourceTags.add(resourceName); + ArrayList derivedFrom = null; + if (derived != null) { + derivedFrom = new ArrayList(); + derivedFrom.add(derived.normativeName); + } + String vendorName = "ATT Tosca"; + String vendorRelease = "1.0.0.wd03"; + String icon = "defaulticon"; + ImportReqDetails resourceDetails = new ImportReqDetails(resourceName, description, resourceTags, derivedFrom, vendorName, vendorRelease, contactId, icon); + resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory()); + return resourceDetails; + } + //// + + public static ImportReqDetails getDefaultImportResource(ResourceReqDetails resourceReqDetails) { + ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(), + resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon()); + importReqDetails.setPayloadName("myCompute.yaml"); + importReqDetails.setCategories(resourceReqDetails.getCategories()); + importReqDetails.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBjb20uYXR0LmQyLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo="); + return importReqDetails; + } + + public static ImportReqDetails getDefaultImportResource() { + ResourceReqDetails resourceReqDetails = getDefaultResource(); + ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(), + resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon()); + importReqDetails.setPayloadName("myCompute.yaml"); + importReqDetails.setCategories(resourceReqDetails.getCategories()); + importReqDetails.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBjb20uYXR0LmQyLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo="); + return importReqDetails; + } + + public static ImportReqDetails getDefaultImportResource(String name) { + ResourceReqDetails resourceReqDetails = getDefaultResourceByType(ResourceTypeEnum.VFC, name); + ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(), + resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon()); + importReqDetails.setPayloadName("myCompute.yaml"); + importReqDetails.setCategories(resourceReqDetails.getCategories()); + importReqDetails.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBjb20uYXR0LmQyLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo="); + return importReqDetails; + } + + // *** SERVICE *** + public static ServiceReqDetails getDefaultService() { + return getDefaultService(CI_SERVICE, ServiceCategoriesEnum.MOBILITY, "al1976"); + } + + public static ServiceReqDetails getDefaultService(String contactId) { + return getDefaultService(CI_SERVICE, ServiceCategoriesEnum.MOBILITY, contactId); + } + + public static ServiceReqDetails getDefaultService(User user) { + return getDefaultService(CI_SERVICE, ServiceCategoriesEnum.MOBILITY, user.getUserId()); + } + + public static ServiceReqDetails getService(ServiceCategoriesEnum category) { + return getDefaultService(CI_SERVICE, category, "al1976"); + } + + public static ServiceReqDetails getDefaultService(ServiceCategoriesEnum category, User user) { + return getDefaultService(CI_SERVICE, category, user.getUserId()); + } + + public static ServiceReqDetails getDefaultService(String serviceName, ServiceCategoriesEnum category, String contactId) { + serviceName = (serviceName + generateUUIDforSufix()); + ArrayList tags = new ArrayList(); + tags.add("serviceTag"); + tags.add("serviceTag1"); + tags.add(serviceName); + String description = "service Description"; + String icon = "myIcon"; + + ServiceReqDetails serviceDetails = new ServiceReqDetails(serviceName, category.getValue(), tags, description, contactId, icon); + + return serviceDetails; + } + + // ***** PROPERTY *** + + public static PropertyReqDetails getDefaultProperty() { + return getDefaultProperty("disk_size"); + } + + public static PropertyReqDetails getDefaultProperty(String propertyName) { + PropertyReqDetails property = new PropertyReqDetails(); + property.setName(propertyName); + property.setPropertyType("integer"); + property.setPropertyRequired(false); + property.setPropertyDefaultValue("12345"); + property.setPropertyDescription("test property"); + property.setPropertyRangeMax("500"); + property.setPropertyRangeMin("100"); + property.setPropertyPassword(false); + return property; + } + + public static PropertyReqDetails getDefaultIntegerProperty() { + return getPropertyDetails(PropertyTypeEnum.INTEGER); + } + + public static PropertyReqDetails getDefaultStringProperty() { + return getPropertyDetails(PropertyTypeEnum.STRING); + } + + public static PropertyReqDetails getDefaultBooleanProperty() { + return getPropertyDetails(PropertyTypeEnum.BOOLEAN); + } + + public static PropertyReqDetails getDefaultListProperty() { + return getPropertyDetails(PropertyTypeEnum.STRING_LIST); + } + + public static PropertyReqDetails getDefaultListProperty(PropertyTypeEnum innerType) { + return getPropertyDetails(innerType); + } + + public static PropertyReqDetails getPropertyDetails(PropertyTypeEnum propType) { + return new PropertyReqDetails(propType.getName(), propType.getType(), propType.getValue(), propType.getDescription(), propType.getSchemaDefinition()); + } + + // ***** RESOURCE INSTANCE *** + public static ComponentInstanceReqDetails getDefaultComponentInstance() { + return getDefaultComponentInstance("resourceInstanceName"); + } + + public static ComponentInstanceReqDetails getDefaultComponentInstance(String name) { + String resourceUid = "resourceId"; + ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, name); + + return resourceInstanceDetails; + + } + + public static ComponentInstanceReqDetails getDefaultComponentInstance(String name, ComponentReqDetails componentReqDetails) { + String resourceUid = componentReqDetails.getUniqueId(); + ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, name); + + return resourceInstanceDetails; + + } + + public static ComponentInstanceReqDetails getComponentResourceInstance(ComponentReqDetails compInstOriginDetails) { + String compInstName = (compInstOriginDetails.getName() != null ? compInstOriginDetails.getName() : "resourceInstanceName"); + String resourceUid = compInstOriginDetails.getUniqueId(); + ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, compInstName); + return resourceInstanceDetails; + + } + + public static ComponentInstanceReqDetails getComponentInstance(Component compInstOriginDetails) { + String compInstName = (compInstOriginDetails.getName() != null ? compInstOriginDetails.getName() : "componentInstanceName"); + String compInsUid = compInstOriginDetails.getUniqueId(); + ComponentInstanceReqDetails componentInstanceDetails = new ComponentInstanceReqDetails(compInsUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, compInstName); + return componentInstanceDetails; + + } + + // ******* USER ********************** + public static User getDefaultUser(UserRoleEnum userRole) { + User sdncModifierDetails = new User(); + sdncModifierDetails.setUserId(userRole.getUserId()); + sdncModifierDetails.setFirstName(userRole.getFirstName()); + sdncModifierDetails.setLastName(userRole.getLastName()); + return sdncModifierDetails; + } + + public static User getDefaultMechUser() { + User sdncMechUserDetails = new User(); + sdncMechUserDetails.setUserId("m12345"); + sdncMechUserDetails.setFirstName("Fishi"); + sdncMechUserDetails.setLastName("Shifi"); + sdncMechUserDetails.setEmail("mechId@intl.sdc.com"); + sdncMechUserDetails.setRole("DESIGNER"); + return sdncMechUserDetails; + } + + // ******* CONSUMER ********************** + + public static ConsumerDataDefinition getDefaultConsumerDetails() { + ConsumerDataDefinition consumer = new ConsumerDataDefinition(); + consumer.setConsumerName("ci"); + consumer.setConsumerSalt("2a1f887d607d4515d4066fe0f5452a50"); + consumer.setConsumerPassword("0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"); + return consumer; + } + + // *** ARTIFACT *** + public static ArtifactReqDetails getDefaultArtifact() throws IOException, Exception { + return getDefaultArtifact(DEFAULT_ARTIFACT_LABEL); + } + + public static ArtifactReqDetails getDefaultArtifact(String artifactLabel) throws IOException, Exception { + List artifactTypes = ResponseParser.getValuesFromJsonArray(ArtifactRestUtils.getArtifactTypesList()); + String artifactType = artifactTypes.get(0); + + return getDefaultArtifact(artifactLabel, artifactType); + } + + public static ArtifactReqDetails getDefaultArtifact(String artifactLabel, String artifactType) throws IOException, Exception { + + String artifactName = "testArtifact.sh"; + String artifactDescription = "descriptionTest"; + String payloadData = "dGVzdA=="; // content of file + + ArtifactReqDetails artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel); + artifactDetails.setUrl(""); + artifactDetails.setArtifactDisplayName(artifactLabel); + return artifactDetails; + } + + public static ArtifactReqDetails getServiceApiArtifactDetails(String artifactLabel) throws IOException, Exception { + ArtifactReqDetails defaultArtifact = getDefaultArtifact(artifactLabel, "OTHER"); + defaultArtifact.setUrl("http://www.apple.com"); + defaultArtifact.setServiceApi(true); + defaultArtifact.setArtifactDisplayName(StringUtils.capitalize(defaultArtifact.getArtifactLabel())); + return defaultArtifact; + } + + public static ArtifactReqDetails getDefaultDeploymentArtifactForType(String artifactType) throws IOException, Exception { + return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType, true, false); + } + + public static ArtifactReqDetails getArtifactByType(ArtifactTypeEnum artifactLabel, ArtifactTypeEnum artifactType, Boolean deploymentTrue) throws IOException, Exception { + return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType.toString(), deploymentTrue, false); + + } + + public static ArtifactReqDetails getArtifactByType(String artifactLabel, String artifactType, Boolean deploymentTrue, Boolean updatedPayload) throws IOException, Exception { + String artifactName; + String updatedPayloadData =null; + String payloadData = null; + Integer timeout = null; + String url = ""; + String artifactDescription = "descriptionTest"; + + // PLEASE NOTE!!! + // The non-default payloads here are real ones according to various + // types validations, + // Please don't change them unless you know what you are doing! + + ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType); + + /* + * Missing file type: DCAE_JSON + */ + switch (artifactTypeEnum) { + case DCAE_INVENTORY_TOSCA: + case DCAE_EVENT: + case APPC_CONFIG: + case DCAE_DOC: + case DCAE_TOSCA: + case HEAT: + case HEAT_NET: + case HEAT_VOL: { + artifactName = generateUUIDforSufix() + artifactType + "_install_apache2.yaml"; + payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9"; + updatedPayloadData = "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCg0Kbm9kZV90eXBlczoNCiAgY29tLmF0dC5kMi5yZXNvdXJjZS5jcC5DUDoNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLm5ldHdvcmsuUG9ydA0KICAgIHByb3BlcnRpZXM6DQogICAgICBpc190YWdnZWQ6DQogICAgICAgIHR5cGU6IGJvb2xlYW4NCiAgICAgICAgcmVxdWlyZWQ6IGZhbHNlDQogICAgICAgIGRlZmF1bHQ6IGZhbHNlDQogICAgICAgIGRlc2NyaXB0aW9uOiANCg0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gdmlydHVhbExpbms6DQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLm5ldHdvcmsuTGlua2FibGUNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMubmV0d29yay5MaW5rc1RvDQogICAgICAtIHZpcnR1YWxCaW5kaW5nOg0KICAgICAgICAgIGNhcGFiaWxpdHk6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQogICAgICAgICAgcmVsYXRpb25zaGlwOiB0b3NjYS5yZWxhdGlvbnNoaXBzLm5ldHdvcmsuQmluZHNUbw0KICAgIGNhcGFiaWxpdGllczoNCiAgICAgIGF0dGFjaG1lbnQ6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5BdHRhY2htZW50DQogICAgICAgIG9jY3VycmVuY2VzOg0KICAgICAgICAtIDENCiAgICAgICAgLSBVTkJPVU5ERUQNCiAgICAgICAgdHlwZTogdG9zY2EuY2FwYWJpbGl0aWVzLm5ldHdvcmsuQmluZGFibGUNCiAgICAgICAgb2NjdXJyZW5jZXM6DQogICAgICAgIC0gMQ0KICAgICAgICAtIFVOQk9VTkRFRA0KICAgICAgdmlydHVhbF9saW5rYWJsZToNCiAgICAgICAgdHlwZTogY29tLmF0dC5kMi5jYXBhYmlsaXRpZXMuTWV0cmljDQogICAgICBlbmRfcG9pbnQ6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5FbmRwb2ludCAgICAgICA="; + timeout = 60; + artifactLabel = normalizeArtifactLabel(artifactName); + break; + } + case DCAE_INVENTORY_POLICY: + case DCAE_INVENTORY_BLUEPRINT: + case DCAE_INVENTORY_EVENT: { + artifactName = getDcaeArtifactName(artifactTypeEnum, artifactType); + payloadData = "will be override later"; + updatedPayloadData = "override"; + timeout = 60; + artifactLabel = normalizeArtifactLabel(artifactName); + break; + } + case MURANO_PKG: { + artifactName = artifactType + "org.openstack.Rally.zip"; + payloadData = "ODM4MTRjNzkxZjcwYTlkMjk4ZGQ2ODE4MThmNjg0N2Y="; + updatedPayloadData = "ODM4MTRjNzkxZjcwYTlkMjk4ZGQ2ODE4MThmMTAwN2Y="; + break; + } + case DCAE_POLICY: { + artifactName = artifactType + "dcae_policy.emf"; + payloadData = "will be override later"; + updatedPayloadData = "override"; + break; + } + case DCAE_INVENTORY_JSON: + case DCAE_JSON: { + artifactName = artifactType + "dcae_policy.json"; + payloadData = "ew0KICAiYXJ0aWZhY3RzIjogImRmc2FmIiwNCiAgIm5vcm1hbGl6ZWROYW1lIjogImNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJzeXN0ZW1OYW1lIjogIkNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJpbnZhcmlhbnRVVUlEIjogIjEzZmJkNzI3LWRjNzUtNDU1OS1iNzEyLWUwMjc5YmY4YTg2MSIsDQogICJhdHRDb250YWN0IjogImNzMDAwOCIsDQogICJuYW1lIjogImNpU2VydmljZTBiYzY5ODk2OTQ4ZiINCn0="; + updatedPayloadData = "ew0KICAiYXJ0aWZhY3RzIjogIjEyMzQzIiwNCiAgIm5vcm1hbGl6ZWROYW1lIjogIjU0MzUzNCIsDQogICJzeXN0ZW1OYW1lIjogIkNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJpbnZhcmlhbnRVVUlEIjogIjEzZmJkNzI3LWRjNzUtNDU1OS1iNzEyLWUwMjc5YmY4YTg2MSIsDQogICJhdHRDb250YWN0IjogImNzMDAwOCIsDQogICJuYW1lIjogImNpU2VydmljZTBiYzY5ODk2OTQ4ZiINCn0="; + break; + } + case PUPPET: + case CHEF: + case DG_XML: + case YANG: { + artifactName = generateUUIDforSufix() + artifactType + "yangXml.xml"; + payloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTg3LTA2LTI0VDAwOjAwOjAwLTAwOjAwPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg=="; + updatedPayloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTkwLTA2LTI0VDAwOjAwOjAwLTAwOjExPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg=="; + timeout = 15; + artifactLabel = normalizeArtifactLabel(artifactName); + break; + } + case VF_LICENSE: + case VENDOR_LICENSE: + case MODEL_INVENTORY_PROFILE: + case MODEL_QUERY_SPEC: + case VNF_CATALOG: + case YANG_XML: { + artifactName = generateUUIDforSufix() + artifactType + "yangXml.xml"; + payloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTg3LTA2LTI0VDAwOjAwOjAwLTAwOjAwPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg=="; + updatedPayloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTkwLTA2LTI0VDAwOjAwOjAwLTAwOjExPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg=="; + timeout = 0; + artifactLabel = normalizeArtifactLabel(artifactName); + break; + } + case SNMP_POLL: + case SNMP_TRAP: + case DCAE_INVENTORY_DOC: + case GUIDE: + case OTHER: { + artifactName = generateUUIDforSufix() + artifactType + "other.pdf"; + payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9"; + updatedPayloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDE2LTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGRzYWRzYWRzYWUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFkc2FkYXN3Z2UgbmFtZSBmb3IgaW5zdGFuY2UxDQogICAgZGVmYXVsdDogY2lycm9zLTAuMy4xLXg4Nl82NA0KICBpbWFnZV9uYW1lXzI6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTINCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIG5ldHdvcmtfaWQ6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IE5ldHdvcmsgSUQNCiAgICBkZXNjcmlwdGlvbjogU0NPTkVUV09SSyBOZXR3b3JrIHRvIGJlIHVzZWQgZm9yIHRoZSBjb21wdXRlIGluc3RhbmNlDQogICAgaGlkZGVuOiB0cnVlDQogICAgY29uc3RyYWludHM6DQogICAgICAtIGxlbmd0aDogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBsZW5ndGggbXVzdCBiZSBiZXR3ZWVuIDYgYW5kIDggY2hhcmFjdGVycy4NCiAgICAgIC0gcmFuZ2U6IHsgbWluOiA2LCBtYXg6IDggfQ0KICAgICAgICBkZXNjcmlwdGlvbjogUmFuZ2UgZGVzY3JpcHRpb24NCiAgICAgIC0gYWxsb3dlZF92YWx1ZXM6DQogICAgICAgIC0gbTEuc21hbGwNCiAgICAgICAgLSBtMS5tZWRpdW0NCiAgICAgICAgLSBtMS5sYXJnZQ0KICAgICAgICBkZXNjcmlwdGlvbjogQWxsb3dlZCB2YWx1ZXMgZGVzY3JpcHRpb24NCiAgICAgIC0gYWxsb3dlZF9wYXR0ZXJuOiAiW2EtekEtWjAtOV0rIg0KICAgICAgICBkZXNjcmlwdGlvbjogUGFzc3dvcmQgbXVzdCBjb25zaXN0IG9mIGNoYXJhY3RlcnMgYW5kIG51bWJlcnMgb25seS4NCiAgICAgIC0gYWxsb3dlZF9wYXR0ZXJuOiAiW0EtWl0rW2EtekEtWjAtOV0qIg0KICAgICAgICBkZXNjcmlwdGlvbjogUGFzc3dvcmQgbXVzdCBzdGFydCB3aXRoIGFuIHVwcGVyY2FzZSBjaGFyYWN0ZXIuDQogICAgICAtIGN1c3RvbV9jb25zdHJhaW50OiBub3ZhLmtleXBhaXINCiAgICAgICAgZGVzY3JpcHRpb246IEN1c3RvbSBkZXNjcmlwdGlvbg0KDQpyZXNvdXJjZXM6DQogIG15X2luc3RhbmNlMToNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8xIH0NCiAgICAgIGZsYXZvcjogbTEuc21hbGwNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICAtIG5ldHdvcmsgOiB7IGdldF9wYXJhbSA6IG5ldHdvcmtfaWQgfQ0KICBteV9pbnN0YW5jZTI6DQogICAgdHlwZTogT1M6Ok5vdmE6OlNlcnZlcg0KICAgIHByb3BlcnRpZXM6DQogICAgICBpbWFnZTogeyBnZXRfcGFyYW06IGltYWdlX25hbWVfMiB9DQogICAgICBmbGF2b3I6IG0xLnRpbnkNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICAtIG5ldHdvcmsgOiB7IGdldF9wYXJhbSA6IG5ldHdvcmtfaWQgfQ"; + timeout = 0; + artifactLabel = normalizeArtifactLabel(artifactName); + break; + } + case SHELL_SCRIPT: + default: {// dummy + artifactName = generateUUIDforSufix() + "testArtifact.sh"; + payloadData = "dGVzdA=="; + updatedPayloadData = "YmVzYg=="; + artifactLabel = normalizeArtifactLabel(artifactName); + break; + } + } + artifactLabel = normalizeArtifactLabel("ci" + artifactName); + + ArtifactReqDetails artifactDetails = null; + + if (!updatedPayload){ + artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel); + } + else artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, + updatedPayloadData, artifactLabel); + + artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + artifactDetails.setUrl(url); + artifactDetails.setTimeout(timeout); + artifactDetails.setArtifactDisplayName(artifactLabel); + return artifactDetails; + } + + private static String getDcaeArtifactName(ArtifactTypeEnum artifactTypeEnum, String artifactType) { + String artifactName = null; + switch (artifactTypeEnum) { + case DCAE_INVENTORY_TOSCA: { + artifactName = generateUUIDforSufix() + artifactType + "_toscaSampleArtifact.yml"; + break; + } + case DCAE_INVENTORY_JSON: { + artifactName = generateUUIDforSufix() + artifactType + "_jsonSampleArtifact.json"; + break; + } + case DCAE_INVENTORY_POLICY: { + artifactName = generateUUIDforSufix() + artifactType + "_emfSampleArtifact.emf"; + break; + } + case DCAE_INVENTORY_DOC: { + artifactName = generateUUIDforSufix() + artifactType + "_docSampleArtifact.doc"; + break; + } + case DCAE_INVENTORY_BLUEPRINT: { + artifactName = generateUUIDforSufix() + artifactType + "_bluePrintSampleArtifact.xml"; + break; + } + case DCAE_INVENTORY_EVENT: { + artifactName = generateUUIDforSufix() + artifactType + "_eventSampleArtifact.xml"; + break; + } + } + return artifactName; + } + + // ---------------------Audit message------------------ + public static ExpectedResourceAuditJavaObject getDefaultImportResourceAuditMsgSuccess() { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.IMPORT_RESOURCE.getName()); + expectedResourceAuditJavaObject.setResourceName("defaultImportResourceName.yaml"); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion("0.1"); + expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName()); + expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setToscaNodeType(""); + return expectedResourceAuditJavaObject; + + } + + public static ExpectedResourceAuditJavaObject getDefaultImportResourceAuditMsgFailure(ErrorInfo errorInfo, List variables) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.IMPORT_RESOURCE.getName()); + expectedResourceAuditJavaObject.setResourceName(""); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName()); + expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + expectedResourceAuditJavaObject.setToscaNodeType(""); + return expectedResourceAuditJavaObject; + + } + + public static ExpectedResourceAuditJavaObject getDefaultCertificationRequestAuditMsgSuccess() { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName()); + expectedResourceAuditJavaObject.setResourceName("defaultResourceName"); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion("0.1"); + expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName()); + expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setComment(""); + return expectedResourceAuditJavaObject; + + } + + public static ExpectedResourceAuditJavaObject getDefaultCertificationRequestAuditMsgFailure(ErrorInfo errorInfo, List variables) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName()); + expectedResourceAuditJavaObject.setResourceName(""); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setPrevVersion("0.1"); + expectedResourceAuditJavaObject.setCurrVersion("0.1"); + expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName()); + expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + expectedResourceAuditJavaObject.setComment(""); + return expectedResourceAuditJavaObject; + + } + + public static ExpectedExternalAudit getDefaultExternalAuditObject(AssetTypeEnum assetType, AuditingActionEnum action, String query) { + + ExpectedExternalAudit expectedExternalAudit = new ExpectedExternalAudit(); + expectedExternalAudit.setACTION(action.getName()); + expectedExternalAudit.setCONSUMER_ID("ci"); + expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query)); + expectedExternalAudit.setSTATUS("200"); + expectedExternalAudit.setDESC("OK"); + return expectedExternalAudit; + + } + + public static ExpectedExternalAudit getDefaultAssetListAudit(AssetTypeEnum assetType, AuditingActionEnum auditAction) { + + // ExpectedExternalAudit expectedAssetListAuditJavaObject = new + // ExpectedExternalAudit(); + ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, auditAction, null); + return expectedAssetListAuditJavaObject; + + } + + public static ExpectedExternalAudit getDefaultFilteredAssetListAudit(AssetTypeEnum assetType, String query) { + + // ExpectedExternalAudit expectedAssetListAuditJavaObject = new + // ExpectedExternalAudit(); + ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST, query); + return expectedAssetListAuditJavaObject; + + } + + public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID) { + + // ExpectedExternalAudit expectedExternalArtifactAudit = new + // ExpectedExternalAudit(); + + ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null); + expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater())); + expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID(""); + expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID()); + expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition)); + expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + componentUUID + "/artifacts"); + return expectedExternalArtifactAudit; + + } + + public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, Component component) { + + //ExpectedExternalAudit expectedExternalArtifactAudit = new ExpectedExternalAudit(); + + ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null); + expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater())); + expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID(""); + expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID()); + expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition)); + expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + component.getUUID() + "/artifacts"); + expectedExternalArtifactAudit.setRESOURCE_NAME(component.getName()); + expectedExternalArtifactAudit.setRESOURCE_TYPE(component.getComponentType().getValue()); + return expectedExternalArtifactAudit; + + } + + public static ExpectedResourceAuditJavaObject getDefaultCreateResourceExternalAPI(String resourceName) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CREATE_RESOURCE_BY_API.getName()); + expectedResourceAuditJavaObject.setResourceName(resourceName); + expectedResourceAuditJavaObject.setResourceType("Resource"); + expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); + expectedResourceAuditJavaObject.setRESOURCE_URL("/sdc/v1/catalog/resources"); + expectedResourceAuditJavaObject.setMODIFIER(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion("0.1"); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + + return expectedResourceAuditJavaObject; + + + } + + public static ExpectedResourceAuditJavaObject getDefaultChangeAssetLifeCycleExternalAPI(Component resourceAssetStructure, User defaultUser, LifeCycleStatesEnum lifecycleStateEnum, AssetTypeEnum assetTypeEnum) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName()); + expectedResourceAuditJavaObject.setResourceName(resourceAssetStructure.getName()); + expectedResourceAuditJavaObject.setResourceType(assetTypeEnum.getCorrespondingComponent()); + expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); + expectedResourceAuditJavaObject.setRESOURCE_URL(String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", assetTypeEnum.getValue().toLowerCase(), resourceAssetStructure.getUUID(), lifecycleStateEnum.getState())); + expectedResourceAuditJavaObject.setMODIFIER(defaultUser.getFullName() + "(" + defaultUser.getUserId() + ")"); + expectedResourceAuditJavaObject.setPrevVersion("0.1"); + expectedResourceAuditJavaObject.setCurrVersion("0.1"); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + // TODO: Remove comment +// expectedResourceAuditJavaObject.setINVARIANT_UUID(resourceAssetStructure.getInvariantUUID()); + // TODO: SERVICE_INSTANCE_ID + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + + return expectedResourceAuditJavaObject; + + } + + public static ExpectedResourceAuditJavaObject getDefaultInvalidChangeAssetLifeCycleExternalAPI(String assetUUID, User defaultUser, LifeCycleStatesEnum lifecycleStateEnum, AssetTypeEnum assetTypeEnum) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName()); + expectedResourceAuditJavaObject.setResourceName(""); + expectedResourceAuditJavaObject.setResourceType(assetTypeEnum.getCorrespondingComponent()); + expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); + expectedResourceAuditJavaObject.setRESOURCE_URL(String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", assetTypeEnum.getValue().toLowerCase(), assetUUID, lifecycleStateEnum.getState())); + expectedResourceAuditJavaObject.setMODIFIER(""); + expectedResourceAuditJavaObject.setMODIFIER(defaultUser.getFullName() + "(" + defaultUser.getUserId() + ")"); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setCurrState(""); + expectedResourceAuditJavaObject.setStatus("404"); + expectedResourceAuditJavaObject.setDesc("OK"); + + return expectedResourceAuditJavaObject; + + } + + public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, String resourceInstanceName) { + + ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditSuccess(assetType, action, artifactDefinition, componentUUID); + expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts"); + return expectedExternalArtifactAudit; + } + + public static ExpectedExternalAudit getDefaultExternalArtifactAuditFailure(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, ErrorInfo errorInfo, List variables) { + + // ExpectedExternalAudit expectedExternalArtifactAudit = new + // ExpectedExternalAudit(); + + ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null); + expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater())); + expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID(""); + expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID()); + expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition)); + expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + componentUUID + "/artifacts"); + expectedExternalArtifactAudit.setSTATUS(errorInfo.getCode().toString()); + expectedExternalArtifactAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + return expectedExternalArtifactAudit; + + } + + public static ExpectedExternalAudit getDefaultExternalArtifactAuditFailure(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, ErrorInfo errorInfo, List variables, + String resourceInstanceName) { + + ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditFailure(assetType, action, artifactDefinition, componentUUID, errorInfo, variables); + expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts"); + return expectedExternalArtifactAudit; + } + + public static ExpectedExternalAudit getFilteredAssetListAuditCategoryNotFound(AssetTypeEnum assetType, String query, String category) { + + // ExpectedExternalAudit expectedAssetListAuditJavaObject = new + // ExpectedExternalAudit(); + ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST, query); + expectedAssetListAuditJavaObject.setSTATUS("404"); + ErrorInfo errorInfo = null; + try { + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String desc = (errorInfo.getMessageId() + ": " + errorInfo.getMessage()).replace("%2", "category").replace("%3", category).replace("%1", "resource"); + expectedAssetListAuditJavaObject.setDESC(desc); + + return expectedAssetListAuditJavaObject; + + } + + public static ExpectedExternalAudit getDefaultAssetMetadataAudit(AssetTypeEnum assetType, Component component) { + + ExpectedExternalAudit expectedAssetListAuditJavaObject = new ExpectedExternalAudit(); + expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_ASSET_METADATA, null); + expectedAssetListAuditJavaObject.setRESOURCE_URL(expectedAssetListAuditJavaObject.getRESOURCE_URL() + "/" + component.getUUID() + "/metadata"); + expectedAssetListAuditJavaObject.setRESOURCE_NAME(component.getName()); + expectedAssetListAuditJavaObject.setRESOURCE_TYPE(component.getComponentType().getValue()); + expectedAssetListAuditJavaObject.setSERVICE_INSTANCE_ID(component.getUUID()); + return expectedAssetListAuditJavaObject; + + } + + public static ExpectedExternalAudit getDefaultAssetMetadataAuditFailure(AssetTypeEnum assetType, String serviceUuid, String resourceType) { + + ExpectedExternalAudit expectedAssetListAuditJavaObject = new ExpectedExternalAudit(); + expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_ASSET_METADATA, null); + expectedAssetListAuditJavaObject.setSTATUS("404"); + expectedAssetListAuditJavaObject.setDESC("OK"); + expectedAssetListAuditJavaObject.setRESOURCE_URL(expectedAssetListAuditJavaObject.getRESOURCE_URL() + "/" + serviceUuid + "/metadata"); + expectedAssetListAuditJavaObject.setRESOURCE_TYPE(resourceType); + expectedAssetListAuditJavaObject.setSERVICE_INSTANCE_ID(serviceUuid); + return expectedAssetListAuditJavaObject; + + } + + // Category/Subcategory/Group + public static CategoryDefinition getDefaultCategory() { + CategoryDefinition productCategoryDefinition = new CategoryDefinition(); + productCategoryDefinition.setName("CiCateg" + generateUUIDforSufix()); + return productCategoryDefinition; + } + + public static SubCategoryDefinition getDefaultSubCategory() { + SubCategoryDefinition productSubCategoryDefinition = new SubCategoryDefinition(); + productSubCategoryDefinition.setName("CiSubCateg" + generateUUIDforSufix()); + return productSubCategoryDefinition; + } + + public static GroupingDefinition getDefaultGroup() { + GroupingDefinition productGroupDefinition = new GroupingDefinition(); + productGroupDefinition.setName("CiGrouping1" + generateUUIDforSufix()); + return productGroupDefinition; + } + + // Product + + public static ProductReqDetails getDefaultProduct() { + return createDefaultProductReqDetails(CI_PRODUCT, null); + } + + public static ProductReqDetails getDefaultProduct(String name) { + return createDefaultProductReqDetails(name, null); + } + + public static ProductReqDetails getDefaultProduct(CategoryDefinition category) { + List categories = new ArrayList<>(); + categories.add(category); + return createDefaultProductReqDetails(CI_PRODUCT, categories); + } + + public static ProductReqDetails getDefaultProduct(String name, CategoryDefinition category) { + List categories = new ArrayList<>(); + categories.add(category); + return createDefaultProductReqDetails(name, categories); + } + + public static ProductReqDetails getDefaultProduct(List categories) { + return createDefaultProductReqDetails(CI_PRODUCT, categories); + } + + public static ProductReqDetails getDefaultProduct(String name, List categories) { + return createDefaultProductReqDetails(name, categories); + } + + private static ProductReqDetails createDefaultProductReqDetails(String productName, List categories) { + ProductReqDetails product = new ProductReqDetails(productName); + productName = (productName + generateUUIDforSufix()); + product.setName(productName); + ArrayList tags = new ArrayList(); + tags.add(productName); + product.setTags(tags); + product.setProjectCode("12345"); + product.setIcon("myIcon"); + ArrayList contacts = new ArrayList(); + // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1).getUserId()); + // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2).getUserId()); + contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1).getUserId()); + // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2).getUserId()); + product.setContacts(contacts); + product.setContactId(UserRoleEnum.PRODUCT_MANAGER1.getUserId()); + product.setCategories(categories); + String fullName = "This is my full name: " + productName; + product.setFullName(fullName); + String description = "This is product description"; + product.setDescription(description); + return product; + } + + public static RequirementCapabilityRelDef getReqCapRelation(String fromCompInstId, String toCompInstId, String reqOwnerId, String capOwnerId, String capType, String reqCapName, List capList, + List reqList) { + RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef(); + requirementDef.setFromNode(fromCompInstId); + requirementDef.setToNode(toCompInstId); + RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(); + pair.setRequirementOwnerId(reqOwnerId); + pair.setCapabilityOwnerId(capOwnerId); + pair.setRequirement(reqCapName); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(capType); + pair.setRelationships(relationship); + pair.setCapabilityUid(capList.get(0).getUniqueId()); + pair.setRequirementUid(reqList.get(0).getUniqueId()); + List relationships = new ArrayList<>(); + relationships.add(pair); + requirementDef.setRelationships(relationships); + return requirementDef; + } + + private static String generateUUIDforSufix() { + + String uniqueSufix = UUID.randomUUID().toString(); + String[] split = uniqueSufix.split("-"); + return uniqueSufix = split[4]; + } + + private static String normalizeArtifactLabel(String label) { + + label = label.substring(0, label.indexOf(".")); + String normalizedLabel = ValidationUtils.normalizeArtifactLabel(label); + return normalizedLabel.substring(0, Math.min(25, normalizedLabel.length())); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java new file mode 100644 index 0000000000..28964e2f7e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java @@ -0,0 +1,137 @@ +/*- + * ============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.ci.tests.utils.general; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.sdc.ci.tests.utils.Decoder; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +public class FileUtils { + static Logger logger = LoggerFactory.getLogger(Utils.class.getName()); + + public static void writeToFile(String filePath, String content) { + try { + Files.write(Paths.get(filePath), content.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static String getFileName(String fullyQualified) { + String fileName = fullyQualified; + + int i = fullyQualified.lastIndexOf('.'); + if (i > 0) { + fileName = fullyQualified.substring(i + 1); + } + return fileName; + + } + + public static Either getFileContentUTF8(String filePath) { + Either eitherResult; + try { + String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8); + eitherResult = Either.left(content); + } catch (Exception e) { + eitherResult = Either.right(e); + } + return eitherResult; + } + + public static List getFileListFromBaseDirectoryByTestName(String testResourcesPath) { + + File file = new File(testResourcesPath); + File[] listFiles = file.listFiles(); + if (listFiles != null) { + List listFileName = new ArrayList(); + for (File newFile : listFiles) { + if (newFile.isFile()) { + listFileName.add(newFile.getPath()); + } + } + return listFileName; + } + assertTrue("directory " + testResourcesPath + " is empty", false); + return null; + } + + public static String getFilePathFromListByPattern(List fileList, String pattern) { + + for (String filePath : fileList) { + if (filePath.contains(pattern)) { + return filePath; + } + } + return null; + } + + public static String loadPayloadFileFromListUsingPosition(List listFileName, String pattern, + Boolean isBase64, int positionInList) throws IOException { + List newList = new ArrayList(Arrays.asList(listFileName.get(positionInList))); + return loadPayloadFile(newList, pattern, isBase64); + } + + public static String loadPayloadFile(List listFileName, String pattern, Boolean isBase64) + throws IOException { + String fileName; + String payload = null; + fileName = FileUtils.getFilePathFromListByPattern(listFileName, pattern); + logger.debug("fileName: {}", fileName); + + if (fileName != null) { + payload = Decoder.readFileToString(fileName); + if (isBase64) { + payload = Decoder.encode(payload.getBytes()); + } + } else { + assertTrue("file to upload not found", false); + } + return payload; + } + + public static String getFileNameFromPath(String testResourcesPath) { + + File file = new File(testResourcesPath); + String fileName = null; + if (file.exists()) { + return file.getName(); + } else { + assertTrue("file to upload not found", false); + } + return fileName; + + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java new file mode 100644 index 0000000000..c1f311a91e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java @@ -0,0 +1,63 @@ +/*- + * ============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.ci.tests.utils.general; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.utils.Utils; + +public class ImportUtils { + + public static ImportReqDetails getImportResourceDetailsByPathAndName(ImportReqDetails importReqDetails, + String filePath, String fileName) throws IOException { + + // ImportReqDetails importReqDetails; + // User sdncUserDetails; + // String testResourcesPath; + // ResourceReqDetails resourceDetails; + // Config config; + // config = Utils.getConfig(); + // + // importReqDetails = ElementFactory.getDefaultImportResource(); + // User sdncUserDetails = + // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // ResourceReqDetails resourceDetails = + // ElementFactory.getDefaultResource(); + // String sourceDir = config.getResourceConfigDir(); + // String testResourcesPath = sourceDir + File.separator + workDir; + // final String workDir = "importToscaResourceByCreateUrl"; + + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filePath); + importReqDetails.setPayloadName(fileName); + String payloadData = FileUtils.loadPayloadFile(listFileName, fileName, true); + importReqDetails.setPayloadData(payloadData); + + return importReqDetails; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java new file mode 100644 index 0000000000..a7ab544725 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java @@ -0,0 +1,934 @@ +/*- + * ============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.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +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.UserRoleEnum; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +public class ArtifactRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(ArtifactRestUtils.class.getName()); + + + // External API + // Delete Artifact on rI of the asset + public static RestResponse externalAPIDeleteArtifactOfComponentInstanceOnAsset(Component component, User user, ComponentInstance resourceInstance, String artifactUUID) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + String resourceInstanceName = resourceInstance.getNormalizedName(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName, artifactUUID); + + return deleteInformationalArtifact(user, url); + } + + // Delete Artifact of the asset + public static RestResponse externalAPIDeleteArtifactOfTheAsset(Component component, User user, String artifactUUID) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, artifactUUID); + + RestResponse restResponse = deleteInformationalArtifact(user, url); + + return restResponse; + } + + + // Update Artifact on rI of the asset + public static RestResponse externalAPIUpdateArtifactOfComponentInstanceOnAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, ComponentInstance resourceInstance, String artifactUUID) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + String resourceInstanceName = resourceInstance.getNormalizedName(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName, artifactUUID); + + return updateInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url); + } + + // Update Artifact of the asset + public static RestResponse externalAPIUpdateArtifactOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, String artifactUUID) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, artifactUUID); + + return updateInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url); + } + + + // Upload Artifact on rI of the asset + public static RestResponse externalAPIUploadArtifactOfComponentInstanceOnAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, ComponentInstance resourceInstance) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + String resourceInstanceName = resourceInstance.getNormalizedName(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName); + + return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url); + } + + // Upload Artifact of the asset + public static RestResponse externalAPIUploadArtifactOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID); + + return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url); + } + + + // Upload Artifact of the asset with invalid checksum + public static RestResponse externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, ComponentInstance resourceInstance) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + String resourceInstanceName = resourceInstance.getNormalizedName(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName); + + return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails) + "123", url); + } + + // Upload Artifact of the asset with invalid checksum + public static RestResponse externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + + System.out.println(component.getComponentType()); + + if(component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID); + + return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails) + "123", url); + } + + + // + // Testing + // + public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException { + Config config = Utils.getConfig(); + String url = null; + + if (resourceType.toUpperCase().equals("SERVICE")) { + url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID); + + } else { + url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID); + } + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + logger.debug("Send GET request to get Resource Assets: {}", url); + System.out.println("Send GET request to get Resource Assets: " + url); + + logger.debug("Request headers: {}", headersMap); + System.out.println("Request headers: " + headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + + } + + + + public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentNormalizedName, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException { + Config config = Utils.getConfig(); + String url = null; + + if (resourceType.toLowerCase().equals("service")) { + url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID); + + } else { + url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID); + } + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + logger.debug("Send GET request to get Resource Assets: {}", url); + System.out.println("Send GET request to get Resource Assets: " + url); + + logger.debug("Request headers: {}", headersMap); + System.out.println("Request headers: " + headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + + } + + + //*********** SERVICE **************** + public static RestResponse getArtifactTypesList() throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort()); + + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid) throws IOException { + return addInformationalArtifactToService(artifactDetails, sdncModifierDetails, serviceUid, calculateChecksum(artifactDetails)); + } + + public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String checksum) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url); + } + + public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map addionalHeaders) throws Exception + { + + return downloadServiceArtifact( service, artifact, user,addionalHeaders,true); + } + + public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map addionalHeaders,boolean addEcompHeader) throws Exception + { + Config config = Utils.getConfig(); + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()), service.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName()))); + String fullUrl = String.format(Urls.DOWNLOAD_SERVICE_ARTIFACT_FULL_URL, config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl); + + return downloadArtifact(fullUrl, user, addionalHeaders,addEcompHeader); + } + + public static RestResponse downloadResourceArtifact(ServiceReqDetails service, ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map addionalHeaders) throws Exception + { + return downloadResourceArtifact(service, resource, artifact, user,addionalHeaders, true); + } + + public static RestResponse downloadResourceArtifact(ServiceReqDetails service,ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map addionalHeaders,boolean addEcompHeader) throws Exception + { + Config config = Utils.getConfig(); + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()),service.getVersion(),ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName()))); + String fullUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL, config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl); + + return downloadArtifact(fullUrl, user, addionalHeaders,addEcompHeader); + } + + + + public static RestResponse downloadResourceInstanceArtifact(String serviceUniqueId,String resourceInstanceId, User user, String artifactUniqeId) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format(Urls.DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUniqueId, resourceInstanceId, artifactUniqeId); + RestResponse res = sendGet(url, user.getUserId(), null); + return res; + } + + //// + + //update + + public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod) throws IOException { + return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactUid, sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails)); + } + + public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, User sdncModifierDetails, String httpMethod) throws IOException { + return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactReqDetails.getUniqueId(), sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails)); + } + + public static RestResponse downloadResourceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception + { + return downloadComponentArtifactInternalApi(resourceId, user, artifactUniqeId, Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT); + } + + public static RestResponse downloadServiceArtifactInternalApi(String componentId, User user, String artifactUniqeId) throws Exception + { + return downloadComponentArtifactInternalApi(componentId, user, artifactUniqeId, Urls.UI_DOWNLOAD_SERVICE_ARTIFACT); + } + public static RestResponse downloadComponentArtifactInternalApi(String componentId, User user, String artifactUniqeId, String urlTemplate) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format(urlTemplate, config.getCatalogBeHost(),config.getCatalogBePort(), componentId, artifactUniqeId); + RestResponse res = sendGet(url, user.getUserId(), null); + return res; + } + +// public static RestResponse downloadServiceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception +// { +// Config config = Utils.getConfig(); +// String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), resourceId, artifactUniqeId); +// RestResponse res = sendGet(url, user.getUserId(), null); +// return res; +// } + + /* + public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException + { + return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true); + } + + public static RestResponse updateInformationalArtifactMetadataOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException + { + return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateChecksum(artifactDetails), false); + } + + public static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException + { + Config config = Utils.getConfig(); + Map headersMap = getHeadersMap(sdncModifierDetails); + + if (isPayloadUpdate){ + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid); + RestResponse res = http.httpSendPost(url, jsonBody, headersMap); + System.out.println("update artifact was finished with response: "+ res.getErrorCode()); + return res; + }*/ + + + + public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod, String checksum) throws IOException + { + Config config = Utils.getConfig(); + + Map headersMap = getHeadersMap(sdncModifierDetails); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(artifactReqDetails); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid); + RestResponse updateResourceResponse = http.httpSendByMethod(url, httpMethod, userBodyJson, headersMap); +// System.out.println("update artifact was finished with response: "+ updateResourceResponse.getErrorCode()); + + return updateResourceResponse; + } + + + public static Map getHeadersMap(User sdncModifierDetails) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader); + + try{ + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + } + catch(Exception e) + { + + } + + return headersMap; + } + + //*********** RESOURCE **************** + //add + public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException{ + return addInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails)); + } + + public static RestResponse explicitAddInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException{ + Config config = Utils.getConfig(); + + + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),config.getCatalogBePort(), resourceUid); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + + public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException{ + Config config = Utils.getConfig(); + + if (artifactDetails.getArtifactGroupType()!=null && artifactDetails.getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT.getType())){ + //YANG_XML and OTHER deployment artifact should be added through this API, not updated + String artifactType = artifactDetails.getArtifactType(); + if (!(ArtifactTypeEnum.YANG_XML.getType().equals(artifactType) || + ArtifactTypeEnum.OTHER.getType().equals(artifactType) || + ArtifactTypeEnum.VNF_CATALOG.getType().equals(artifactType) || + ArtifactTypeEnum.VF_LICENSE.getType().equals(artifactType) || + ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(artifactType) || + ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equals(artifactType) || + ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equals(artifactType) || + ArtifactTypeEnum.APPC_CONFIG.getType().equals(artifactType))){ + //return updateInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid); + } + } + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),config.getCatalogBePort(), resourceUid); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url); + } + //update + public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException{ + return updateInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails)); + } + + public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException { + Config config = Utils.getConfig(); + if (artifactDetails.getArtifactGroupType()!=null && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")){ + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid ); + Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel()); + artifactDetails.setUniqueId(artifactDefinition.getUniqueId()); + artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); + + } + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId()); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + public static RestResponse uploadArtifactToPlaceholderOnResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String placeHolderLabel) throws IOException { + Config config = Utils.getConfig(); + if (artifactDetails.getArtifactLabel() != null && !artifactDetails.getArtifactLabel().isEmpty()){ + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid ); + Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel()); + AssertJUnit.assertNotNull(artifactDefinition); + artifactDetails.setUniqueId(artifactDefinition.getUniqueId()); + artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); + + } + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId()); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + public static RestResponse updateArtifactToResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDefinition.getUniqueId()); + return updateDeploymentArtifact(artifactDefinition, sdncModifierDetails, url); + } + + public static RestResponse updateDeploymentArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId()); + + return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url); + } + + + public static RestResponse updateDeploymentArtifactToRI(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId()); + return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url); + } + + //delete + public static RestResponse deleteArtifactFromResourceInstance (ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceUid, String serviceId) throws IOException{ + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceUid, artifactDefinition.getUniqueId()); + return sendDelete(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, ArtifactReqDetails artifactDetails, User sdncModifierDetails) throws IOException{ + return deleteInformationalArtifactFromResource( resourceUid, artifactDetails.getUniqueId(), sdncModifierDetails); + } + + public static RestResponse deleteInformationalArtifactFromResource( String resourceUid, String artifactId, User sdncModifierDetails) throws IOException{ + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactId); + return sendDelete(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse deleteServiceApiArtifact(ArtifactReqDetails artifactDetails, String serviceUniqueId, User user) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_DELETE_SERVICE_API_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUniqueId, artifactDetails.getUniqueId()); + RestResponse res = sendDelete(url, user.getUserId()); + logger.debug("Deleting api artifact was finished with response: {}", res.getErrorCode()); + logger.debug("Response body: {}", res.getResponseMessage()); + return res; + } + + //*************** RESOURCE INSTANCE ************** + /** + * Add DCAE artifacts to resource instance. + * @param artifactDetails + * @param sdncModifierDetails + * @param resourceInstanceId + * @param serviceId + * @return + * @throws IOException + */ + public static RestResponse addArtifactToResourceInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId,resourceInstanceId, artifactDetails.getUniqueId()); + return addArtifactToInstance(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + //*************** COMPONENT ************** + + public static RestResponse uploadDeploymentArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + Map additionalHeaders = null; + String checksum = ResponseParser.calculateMD5Header(artifactDetails); + additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + + ComponentTypeEnum componentType = component.getComponentType(); + + String url = null; + + switch (componentType){ + + case RESOURCE: + { + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), component.getUniqueId(), artifactDetails.getUniqueId()); + + break; + } + case SERVICE: { + + break; + } + + case PRODUCT: { + + break; + } + + default: {//dummy + assertTrue("failed on enum selection", false); + + break; + } + } + + + + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); +// System.out.println("ArtifactDetails: "+ jsonBody); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } +// System.out.println("Add artifact was finished with response: "+ res.getErrorCode()); + return res; + } + + public static RestResponse uploadArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + List placeHolderlst = Utils.getListOfResPlaceHoldersDepArtTypes(); + Map additionalHeaders = null; + String checksum = null; + String url= null; +// +// +// if (artifactDetails.getArtifactGroupType() != null +// && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT") +// && placeHolderlst.contains(artifactDetails.getArtifactType())) { +// Map deploymentArtifacts = component.getDeploymentArtifacts(); +// ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel()); +// artifactDetails.setUniqueId(artifactDefinition.getUniqueId()); +// artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); +// checksum = ResponseParser.calculateMD5Header(artifactDetails); +// additionalHeaders = new HashMap(); +// additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); +// url = String.format(Urls.UPDATE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(), +// config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), +// component.getUniqueId(), artifactDetails.getUniqueId()); +// } +// +// else { + checksum = ResponseParser.calculateMD5Header(artifactDetails); + additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + url = String.format(Urls.UPLOAD_DELETE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), + component.getUniqueId(), artifactDetails.getUniqueId()); +// } + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); +// System.out.println("ArtifactDetails: "+ jsonBody); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } +// System.out.println("Add artifact was finished with response: "+ res.getErrorCode()); + return res; + } + + + + + //*************** PRIVATE ************** + private static RestResponse deleteInformationalArtifact(User sdncModifierDetails, String url) throws IOException { + Map additionalHeaders = null; + + additionalHeaders = new HashMap(); + + + additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + return sendDelete(url, sdncModifierDetails.getUserId(), additionalHeaders); + +// Gson gson = new Gson(); +//// System.out.println("ArtifactDetails: "+ jsonBody); +// String jsonBody = gson.toJson(artifactDetails); +// +// RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); +// if ((res.getErrorCode() == STATUS_CODE_SUCCESS) || (res.getErrorCode() == STATUS_CODE_CREATED)) { +// artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); +// } +//// System.out.println("Add artifact was finished with response: "+ res.getErrorCode()); +// return res; + } + + private static RestResponse updateInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException { + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url); + } + + private static RestResponse uploadInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException { + Map additionalHeaders = null; + if (checksum != null && !checksum.isEmpty()) { + additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + + additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + Gson gson = new Gson(); +// System.out.println("ArtifactDetails: "+ jsonBody); + String jsonBody = gson.toJson(artifactDetails); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + if ((res.getErrorCode() == STATUS_CODE_SUCCESS) || (res.getErrorCode() == STATUS_CODE_CREATED)) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } +// System.out.println("Add artifact was finished with response: "+ res.getErrorCode()); + return res; + } + + private static RestResponse addArtifactToInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException { + Map additionalHeaders = null; + additionalHeaders = new HashMap(); + if (checksum != null && !checksum.isEmpty()) { + additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); + additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } + return res; + } + + private static RestResponse updateDeploymentArtifact(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String url) throws IOException { + Map additionalHeaders = null; + additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); + additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDefinition); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders); + return res; + } + + private static RestResponse updateDeploymentArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String url) throws IOException { + Map additionalHeaders = null; + + additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); + additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); +// additionalHeaders.put(HttpHeaderEnum..getValue(), "application/json;charset=UTF-8"); + + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); +// System.out.println("ArtifactDetails: "+ jsonBody); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } +// System.out.println("Add artifact was finished with response: "+ res.getErrorCode()); + return res; + } + + private static RestResponse downloadArtifact(String url, User user, Map addionalHeaders,boolean addEcompHeader) throws IOException + { + if(addEcompHeader){ + addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), ecomp); + } + return downloadArtifact(url, user, addionalHeaders, acceptOctetStream); + } + + private static RestResponse downloadArtifact(String url, User user, Map addionalHeaders, String accept) throws IOException + { + addionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), accept); + + RestResponse res = sendGet(url, user.getUserId(), addionalHeaders); +// System.out.println("download artifact was finished with response: "+ res.getErrorCode()); +// System.out.println("response is: " + res.getResponse()); + return res; + } + + private static Map> getArtifactsListFromResponse(String jsonResponse, String fieldOfArtifactList){ + JSONObject object = (JSONObject)JSONValue.parse(jsonResponse); + Map> map = (Map>)object.get(fieldOfArtifactList); + return map; + } + + public static String calculateChecksum(ArtifactReqDetails artifactDetails) { + String checksum = null; + if (artifactDetails.getPayload() != null) { + checksum = ResponseParser.calculateMD5Header(artifactDetails); + } + return checksum; + } + + public static String encodeUrlForDownload(String url){ + + return url.replaceAll(" ", "%20"); + } + + public static String getPartialUrlByArtifactName(ServiceReqDetails serviceDetails,String serviceVersion ,String artifactName){ + return encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceVersion, artifactName)); + } + + public static String getUniqueIdOfArtifact(RestResponse createResponse, String artifactField, String requieredArtifactLabel) throws Exception + { + Map artifact = getArtifactFromRestResponse(createResponse, artifactField, requieredArtifactLabel); + assertNotNull(artifact); + return artifact.get("uniqueId").toString(); + } + + public static Map getArtifactFromRestResponse(RestResponse response, String artifactField, String requieredArtifactLabel) + { + Map> map = getArtifactsListFromResponse(response.getResponse(), artifactField); + return map.get(requieredArtifactLabel); + } + + + + public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException + { + return updateInformationalArtifactPayloadOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateMD5Header(artifactDetails)); + } + + private static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException + { + return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true); + } + + private static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException + { + Config config = Utils.getConfig(); + Map headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + + if (isPayloadUpdate){ + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid); + RestResponse res = http.httpSendPost(url, jsonBody, headersMap); +// System.out.println("update artifact was finished with response: "+ res.getErrorCode()); + return res; + } + + public static String calculateMD5Header(ArtifactReqDetails artifactDetails) + { + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // calculate MD5 for json body + return calculateMD5(jsonBody); + + } + + public static String calculateMD5 (String data){ + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + String encodeBase64Str = new String(encodeBase64); + return encodeBase64Str; + + } + + + public static ArtifactDefinition getArtifactDataFromJson(String json) { + Gson gson = new Gson(); + JsonObject jsonElement = new JsonObject(); + jsonElement = gson.fromJson(json, jsonElement.getClass()); + ArtifactDefinition artifact = new ArtifactDefinition(); + String payload = null; + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + artifact = gson.fromJson(jsonElement, ArtifactDefinition.class); + artifact.setPayloadData(payload); + + /*atifact.setArtifactName(UPLOAD_ARTIFACT_NAME); +artifact.setArtifactDisplayName("configure"); +artifact.setArtifactType("SHELL"); +artifact.setMandatory(false); +artifact.setDescription("ff"); +artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD); +artifact.setArtifactLabel("configure");*/ + return artifact; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java new file mode 100644 index 0000000000..13a56417e8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java @@ -0,0 +1,626 @@ +/*- + * ============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.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +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.HttpClients; +import org.codehaus.jackson.map.ObjectMapper; +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.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.AssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceInstanceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class AssetRestUtils extends BaseRestUtils { + static Gson gson = new Gson(); + static ObjectMapper objectMapper = new ObjectMapper(); + + static Logger logger = LoggerFactory.getLogger(AssetRestUtils.class.getName()); + static final String contentTypeHeaderData = "application/json"; + static final String acceptHeaderDate = "application/json"; + static final String basicAuthentication = "Basic Y2k6MTIzNDU2"; + // /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(); + CloseableHttpClient httpclient = HttpClients.createDefault(); + String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), uuid); + HttpGet httpGet = new HttpGet(url); + + httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + + logger.debug("Send GET request to get Tosca model: {}", url); + + return httpclient.execute(httpGet); + } + + public static File getToscaModelCsarFile(AssetTypeEnum assetType, String uuid) throws IOException { + Config config = Utils.getConfig(); + CloseableHttpClient httpclient = HttpClients.createDefault(); + String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), uuid); + HttpGet httpGet = new HttpGet(url); + File myFile = new File("tmpCSAR"); + + + httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + + logger.debug("Send GET request to get Tosca model: {}", url); + CloseableHttpResponse execute = httpclient.execute(httpGet); + + HttpEntity entity = execute.getEntity(); + if (entity != null) { + try (FileOutputStream outstream = new FileOutputStream(myFile)) { + entity.writeTo(outstream); + outstream.close(); + } + } + return myFile; + } + + public static RestResponse getRestResponseComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException { + Config config = Utils.getConfig(); + + String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), uuid); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + logger.debug("Send GET request to get Resource Assets: {}", url); + System.out.println("Send GET request to get Resource Assets: " + url); + + logger.debug("Request headers: {}", headersMap); + System.out.println("Request headers: " + headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + + } + + public static RestResponse getComponentListByAssetType(boolean isBasicAuthentication, AssetTypeEnum assetType, + String... filterArrayString) throws IOException { + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + if (isBasicAuthentication) { + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + } + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue()); + if (filterArrayString != null && filterArrayString.length > 0) { + url = buildUrlWithFilter(url, filterArrayString); + } + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + } + + public static RestResponse getFilteredComponentList(AssetTypeEnum assetType, String query) throws IOException { + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), query); + + logger.debug("Send GET request to get Resource Assets: {}", url); + logger.debug("Request headers: {}", headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + } + + public static String buildUrlWithFilter(String url, String[] filterArrayString) { + StringBuilder sb = new StringBuilder(); + int length = filterArrayString.length; + int count = 0; + for (String filterString : filterArrayString) { + sb.append(filterString); + count++; + if (length != count) { + sb.append("&"); + } + } + return url + "?" + sb; + } + + public static RestResponse getAssetMetadataByAssetTypeAndUuid(boolean isBasicAuthentication, + AssetTypeEnum assetType, String uuid) throws IOException { + + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + if (isBasicAuthentication) { + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + } + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ASSET_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), uuid); + + logger.debug("Send GET request to get Resource Assets: {}", url); + logger.debug("Request headers: {}", headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + } + + public static List getResourceAssetList(RestResponse assetResponse) { + List resourceAssetList = new ArrayList<>(); + + JsonElement jelement = new JsonParser().parse(assetResponse.getResponse()); + JsonArray componenetArray = (JsonArray) jelement; + for (JsonElement jElement : componenetArray) { + ResourceAssetStructure resource = gson.fromJson(jElement, ResourceAssetStructure.class); + resourceAssetList.add(resource); + } + return resourceAssetList; + } + + public static ResourceDetailedAssetStructure getResourceAssetMetadata(RestResponse assetResponse) { + + List resourcesList = new ArrayList<>(); + List artifactsList = new ArrayList<>(); + ResourceDetailedAssetStructure resourceAssetMetadata = new ResourceDetailedAssetStructure(); + String response = assetResponse.getResponse(); + + JsonObject jObject = (JsonObject) new JsonParser().parse(response); + resourceAssetMetadata = gson.fromJson(jObject, ResourceDetailedAssetStructure.class); + + setResourceInstanceAssetList(resourcesList, jObject); + resourceAssetMetadata.setResources(resourcesList); + + setArtifactAssetList(artifactsList, jObject); + resourceAssetMetadata.setArtifacts(artifactsList); + + return resourceAssetMetadata; + } + + public static void generalMetadataFieldsValidatior(AssetStructure assetMetadata, Component component) { + + assertTrue("Expected resourceUuid is " + component.getUUID() + " actual: " + assetMetadata.getUuid(), + assetMetadata.getUuid().equals(component.getUUID())); + assertTrue( + "Expected resourceInvariantUuid is " + component.getInvariantUUID() + " actual: " + + assetMetadata.getInvariantUUID(), + assetMetadata.getInvariantUUID().equals(component.getInvariantUUID())); + assertTrue("Expected asset name is " + component.getName() + " actual: " + assetMetadata.getName(), + assetMetadata.getName().equals(component.getName())); + assertTrue("Expected asset version is " + component.getVersion() + " actual: " + assetMetadata.getVersion(), + assetMetadata.getVersion().equals(component.getVersion())); + assertTrue( + "Expected asset lastUpdaterUserId is " + component.getLastUpdaterUserId() + " actual: " + + assetMetadata.getLastUpdaterUserId(), + assetMetadata.getLastUpdaterUserId().equals(component.getLastUpdaterUserId())); + assertNotNull("Expected asset toscaModel is null", assetMetadata.getToscaModelURL()); + assertTrue( + "Expected asset category is " + component.getCategories().get(0).getName() + " actual: " + + assetMetadata.getCategory(), + assetMetadata.getCategory().equals(component.getCategories().get(0).getName())); + assertTrue( + "Expected asset lifeCycleState is " + component.getLifecycleState() + " actual: " + + assetMetadata.getLifecycleState(), + assetMetadata.getLifecycleState().equals(component.getLifecycleState().toString())); + + } + + public static void resourceMetadataValidatior(ResourceDetailedAssetStructure resourceAssetMetadata, + Resource resource, AssetTypeEnum assetType) throws Exception { + + generalMetadataFieldsValidatior(resourceAssetMetadata, resource); + assertTrue( + "Expected asset lastUpdaterFullName is " + resource.getLastUpdaterFullName() + " actual: " + + resourceAssetMetadata.getLastUpdaterFullName(), + resourceAssetMetadata.getLastUpdaterFullName().equals(resource.getLastUpdaterFullName())); + assertTrue( + "Expected asset subCategory is " + resource.getCategories().get(0).getSubcategories().get(0).getName() + + " actual: " + resourceAssetMetadata.getSubCategory(), + resourceAssetMetadata.getSubCategory() + .equals(resource.getCategories().get(0).getSubcategories().get(0).getName())); + assertTrue( + "Expected asset toscaResourceName is " + resource.getToscaResourceName() + " actual: " + + resourceAssetMetadata.getToscaResourceName(), + resourceAssetMetadata.getToscaResourceName().equals(resource.getToscaResourceName())); + assertTrue( + "Expected asset resourceType is " + resource.getResourceType() + " actual: " + + resourceAssetMetadata.getResourceType(), + resourceAssetMetadata.getResourceType().equals(resource.getResourceType().toString())); + resourceInstanceAssetValidator(resourceAssetMetadata.getResources(), resource, assetType); + // resourceInstanceAssetValidator(resourceAssetMetadata.getResources(), + // resource); + artifactAssetValidator(resourceAssetMetadata.getArtifacts(), resource, assetType); + + } + + public static void serviceMetadataValidatior(ServiceDetailedAssetStructure serviceAssetMetadata, Service service, + AssetTypeEnum assetType) throws Exception { + + generalMetadataFieldsValidatior(serviceAssetMetadata, service); + assertTrue( + "Expected asset lastUpdaterFullName is " + service.getLastUpdaterFullName() + " actual: " + + serviceAssetMetadata.getLastUpdaterFullName(), + serviceAssetMetadata.getLastUpdaterFullName().equals(service.getLastUpdaterFullName())); + assertTrue("Expected asset distributionStatus is " + service.getDistributionStatus() + " actual: " + + serviceAssetMetadata.getDistributionStatus(), + serviceAssetMetadata.getDistributionStatus().equals(service.getDistributionStatus().toString())); + resourceInstanceAssetValidator(serviceAssetMetadata.getResources(), service, assetType); + // resourceInstanceAssetValidator(serviceAssetMetadata.getResources(), + // service); + artifactAssetValidator(serviceAssetMetadata.getArtifacts(), service, assetType); + + } + + private static void artifactAssetValidator(List artifactAssetStructureList, + Component component, AssetTypeEnum assetType) { + Map componentDeploymentArtifacts = component.getDeploymentArtifacts(); + validateArtifactMetadata(componentDeploymentArtifacts, artifactAssetStructureList, component.getUUID(), + assetType, null); + } + + private static void validateArtifactMetadata(Map componentDeploymentArtifacts, + List artifactAssetStructureList, String componentUuid, AssetTypeEnum assetType, + String resourceInstanceName) { + if(componentDeploymentArtifacts != null){ + for (Entry componentDeploymentArtifact : componentDeploymentArtifacts.entrySet()) { + ArtifactAssetStructure artifactAssetStructure = getArtifactMetadata(artifactAssetStructureList, + componentDeploymentArtifact.getValue().getArtifactUUID()); + ArtifactDefinition componentDeploymentArtifactValue = componentDeploymentArtifact.getValue(); + if (artifactAssetStructure != null) { + assertTrue( + "Expected artifact asset artifactName is " + componentDeploymentArtifactValue.getArtifactName() + + " actual: " + artifactAssetStructure.getArtifactName(), + componentDeploymentArtifactValue.getArtifactName() + .equals(artifactAssetStructure.getArtifactName())); + assertTrue( + "Expected artifact asset Type is " + componentDeploymentArtifactValue.getArtifactType() + + " actual: " + artifactAssetStructure.getArtifactType(), + componentDeploymentArtifactValue.getArtifactType() + .equals(artifactAssetStructure.getArtifactType())); + // assertNotNull("Expected artifact asset resourceInvariantUUID + // is null", + // resourceInstanceAssetStructure.getResourceInvariantUUID()); + // String expectedArtifactUrl = "/sdc/v1/catalog/" + + // assetType.getValue() + "/" + componentUuid + "/artifacts/" + + // componentDeploymentArtifactValue.getArtifactUUID(); + String expectedArtifactUrl = ""; + if (resourceInstanceName == null) { + expectedArtifactUrl = String.format(COMPONENT_ARTIFACT_URL, assetType.getValue(), componentUuid, + componentDeploymentArtifactValue.getArtifactUUID()); + } else { + expectedArtifactUrl = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, assetType.getValue(), + componentUuid, resourceInstanceName, componentDeploymentArtifactValue.getArtifactUUID()); + } + + assertTrue( + "Expected artifact asset URL is " + expectedArtifactUrl + " actual: " + + artifactAssetStructure.getArtifactURL(), + artifactAssetStructure.getArtifactURL().equals(expectedArtifactUrl)); + assertTrue( + "Expected artifact asset description is " + componentDeploymentArtifactValue.getDescription() + + " actual: " + artifactAssetStructure.getArtifactDescription(), + componentDeploymentArtifactValue.getDescription().toString() + .equals(artifactAssetStructure.getArtifactDescription())); + assertTrue( + "Expected artifact asset checkSum is " + componentDeploymentArtifactValue.getArtifactChecksum() + + " actual: " + artifactAssetStructure.getArtifactChecksum(), + componentDeploymentArtifactValue.getArtifactChecksum() + .equals(artifactAssetStructure.getArtifactChecksum())); + assertTrue( + "Expected artifact asset version is " + componentDeploymentArtifactValue.getArtifactVersion() + + " actual: " + artifactAssetStructure.getArtifactVersion(), + componentDeploymentArtifactValue.getArtifactVersion() + .equals(artifactAssetStructure.getArtifactVersion())); + if (componentDeploymentArtifactValue.getTimeout() > 0) { + assertTrue( + "Expected artifact asset timeout is " + componentDeploymentArtifactValue.getTimeout() + + " actual: " + artifactAssetStructure.getArtifactTimeout(), + componentDeploymentArtifactValue.getTimeout() + .equals(artifactAssetStructure.getArtifactTimeout())); + } + + } else { + assertTrue("artifact asset with UUID" + componentDeploymentArtifact.getValue().getArtifactUUID() + + " not found in get Metadata response", false); + } + } + }else{ + System.out.println("componentDeploymentArtifacts is null"); + logger.debug("componentDeploymentArtifacts is null"); + } + + } + + private static ArtifactAssetStructure getArtifactMetadata(List artifactAssetStructureList, + String artifactUUID) { + for (ArtifactAssetStructure artifactAssetStructure : artifactAssetStructureList) { + if (artifactAssetStructure.getArtifactUUID().equals(artifactUUID)) { + return artifactAssetStructure; + } + } + return null; + } + + private static void resourceInstanceAssetValidator( + List resourceInstanceAssetStructures, Component component, + AssetTypeEnum assetType) throws Exception { + + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + for (ComponentInstance componentInstance : componentInstances) { + ResourceInstanceAssetStructure resourceInstanceAssetStructure = getResourceInstanceMetadata( + resourceInstanceAssetStructures, componentInstance.getName()); + if (resourceInstanceAssetStructure != null) { + assertTrue( + "Expected RI asset resourceName is " + componentInstance.getComponentName() + " actual: " + + resourceInstanceAssetStructure.getResourceName(), + componentInstance.getComponentName() + .equals(resourceInstanceAssetStructure.getResourceName())); + assertTrue( + "Expected RI asset Name is " + componentInstance.getName() + " actual: " + + resourceInstanceAssetStructure.getResourceInstanceName(), + componentInstance.getName() + .equals(resourceInstanceAssetStructure.getResourceInstanceName())); + assertNotNull("Expected RI asset resourceInvariantUUID is null", + resourceInstanceAssetStructure.getResourceInvariantUUID()); + assertTrue( + "Expected RI asset resourceVersion is " + componentInstance.getComponentVersion() + + " actual: " + resourceInstanceAssetStructure.getResourceVersion(), + componentInstance.getComponentVersion() + .equals(resourceInstanceAssetStructure.getResourceVersion())); + assertTrue( + "Expected RI asset resourceType is " + componentInstance.getOriginType() + " actual: " + + resourceInstanceAssetStructure.getResoucreType(), + componentInstance.getOriginType().toString() + .equals(resourceInstanceAssetStructure.getResoucreType())); + Resource resource = AtomicOperationUtils.getResourceObject(componentInstance.getComponentUid()); + assertTrue("Expected RI asset resourceUUID is " + resource.getUUID() + " actual: " + resourceInstanceAssetStructure.getResourceUUID(), + resource.getUUID().equals(resourceInstanceAssetStructure.getResourceUUID())); + validateArtifactMetadata(componentInstance.getDeploymentArtifacts(), + resourceInstanceAssetStructure.getArtifacts(), component.getUUID(), assetType, + componentInstance.getNormalizedName()); + // validateArtifactMetadata(componentInstance.getDeploymentArtifacts(), + // resourceInstanceAssetStructure.getArtifacts(), + // component.getUUID(), AssetTypeEnum.RESOURCES); + } else { + assertTrue("resourceInstance asset with UUID" + componentInstance.getComponentUid() + + " not found in get Metadata response", false); + } + } + } + + } + + // private static ResourceInstanceAssetStructure + // getResourceInstanceMetadata(List + // resourceInstanceAssetStructures, String componentUid) { + private static ResourceInstanceAssetStructure getResourceInstanceMetadata( + List resourceInstanceAssetStructures, String name) { + for (ResourceInstanceAssetStructure resourceInstanceAssetStructure : resourceInstanceAssetStructures) { + if (resourceInstanceAssetStructure.getResourceInstanceName().equals(name)) { + return resourceInstanceAssetStructure; + } + } + return null; + } + + public static ServiceDetailedAssetStructure getServiceAssetMetadata(RestResponse assetResponse) { + + List resourcesList = new ArrayList<>(); + List artifactsList = new ArrayList<>(); + ServiceDetailedAssetStructure serviceAssetMetadata; + + JsonObject jObject = (JsonObject) new JsonParser().parse(assetResponse.getResponse()); + serviceAssetMetadata = gson.fromJson(jObject, ServiceDetailedAssetStructure.class); + + setResourceInstanceAssetList(resourcesList, jObject); + serviceAssetMetadata.setResources(resourcesList); + + setArtifactAssetList(artifactsList, jObject); + serviceAssetMetadata.setArtifacts(artifactsList); + + return serviceAssetMetadata; + } + + public static void setArtifactAssetList(List artifactsList, JsonObject jObject) { + JsonArray artifactsArray = jObject.getAsJsonArray("artifacts"); + if (artifactsArray != null) { + for (JsonElement jElement : artifactsArray) { + ArtifactAssetStructure artifact = gson.fromJson(jElement, ArtifactAssetStructure.class); + artifactsList.add(artifact); + } + } + } + + public static void setResourceInstanceAssetList(List resourcesList, + JsonObject jObject) { + JsonArray resourcesArray = jObject.getAsJsonArray("resources"); + if (resourcesArray != null) { + for (JsonElement jElement : resourcesArray) { + ResourceInstanceAssetStructure resource = gson.fromJson(jElement, ResourceInstanceAssetStructure.class); + resourcesList.add(resource); + } + } + } + + public static List getServiceAssetList(RestResponse assetResponse) { + List serviceAssetList = new ArrayList<>(); + + JsonElement jelement = new JsonParser().parse(assetResponse.getResponse()); + JsonArray componenetArray = (JsonArray) jelement; + for (JsonElement jElement : componenetArray) { + ServiceAssetStructure service = gson.fromJson(jElement, ServiceAssetStructure.class); + serviceAssetList.add(service); + } + return serviceAssetList; + } + + public static List getResourceNamesList(List resourceAssetList) { + List assetNamesList = new ArrayList<>(); + for (ResourceAssetStructure resourceAsset : resourceAssetList) { + assetNamesList.add(resourceAsset.getName()); + } + return assetNamesList; + } + + public static Map getResourceAssetMap(RestResponse assetResponse) { + Map resourceAssetMap = new HashMap<>(); + + JsonElement jelement = new JsonParser().parse(assetResponse.getResponse()); + JsonArray componenetArray = (JsonArray) jelement; + for (JsonElement jElement : componenetArray) { + ResourceAssetStructure resource = gson.fromJson(jElement, ResourceAssetStructure.class); + resourceAssetMap.put(resource.getName(), resource.getVersion()); + } + return resourceAssetMap; + } + + public static Map getResourceListFiltteredByWholeVersion(Map resourceAssetList) { + Map assetNamesMap = new HashMap<>(); + for (Entry entry : resourceAssetList.entrySet()) { + String key = entry.getKey(); + String[] parts = entry.getValue().split("\\."); + String lastOne = parts[parts.length-1]; + + if (key.contains("CinderVolume") ){ + assetNamesMap.put(key,entry.getValue()); + } + + if (lastOne.equals("0") && !key.contains("Ci") ){ + assetNamesMap.put(key,entry.getValue()); + } + } + + return assetNamesMap; + } + + public static List getResourceObjectByNameAndVersionToscaNamesList(Map resourceAssetList) throws Exception { + List assetNamesList = new ArrayList<>(); + for (Entry entry : resourceAssetList.entrySet()) { + System.out.println("fetch data---->"+entry.getKey()+entry.getValue()); + Resource resourceObjectByNameAndVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, entry.getKey(), entry.getValue()); + assetNamesList.add(resourceObjectByNameAndVersion.getToscaResourceName()); + + } + + return assetNamesList; + } + + + public static List getServiceNamesList(List serviceAssetList) { + List assetNamesList = new ArrayList<>(); + for (ServiceAssetStructure serviceAsset : serviceAssetList) { + assetNamesList.add(serviceAsset.getName()); + } + return assetNamesList; + } + + public static void checkResourceTypeInObjectList(List resourceAssetList, ResourceTypeEnum resourceType) { + for (ResourceAssetStructure resourceAsset : resourceAssetList) { + assertTrue("Expected resourceType is " + resourceType.toString() + " actual: " + resourceAsset.getResourceType(), + resourceAsset.getResourceType().equals(resourceType.toString())); + } + } + + public static void checkComponentTypeInObjectList(List resourceAssetList, ComponentTypeEnum componentType) { + ComponentTypeEnum actualComponentType; + for (ResourceAssetStructure resourceAsset : resourceAssetList) { + actualComponentType = detectComponentType(resourceAsset); + assertTrue("Expected componentType is " + componentType.getValue() + " actual: " + actualComponentType.getValue(), actualComponentType.equals(componentType)); + } + } + + private static ComponentTypeEnum detectComponentType(ResourceAssetStructure resourceAsset) { + String resourceType = resourceAsset.getResourceType(); + if(ResourceTypeEnum.getType(resourceType) !=null){ + return ComponentTypeEnum.RESOURCE; + } + return null; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java new file mode 100644 index 0000000000..2e27907fb5 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java @@ -0,0 +1,110 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +public class AutomationUtils extends BaseRestUtils { + + + public static String getOnboardVersion() { + String onboardVersionStr = null; + try { + + RestResponse onboardVersion = CatalogRestUtils.getOnboardVersion(); + onboardVersionStr = ResponseParser.getValueFromJsonResponse(onboardVersion.getResponse() , "Version"); + + } catch (Exception e) { + System.out.println("UnknownOnboardVersion"); + } + return onboardVersionStr != null ? onboardVersionStr : "UnknownOnboardVersion"; + + } + + public static String getOSVersion() { + String osVersionStr = null; + try { + RestResponse osVersion = CatalogRestUtils.getOsVersion(); + osVersionStr = ResponseParser.getVersionFromResponse(osVersion); + + } catch (Exception e) { + System.out.println("UnknownOSversion"); + } + + return osVersionStr != null ? osVersionStr : "UnknownOSversion" ; + } + + + + public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData, String suiteName) + throws FileNotFoundException, IOException { + File myFoo = new File(filepath); + FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append + String versions = ("onboardVesrion=\""+ onboardVersion+ "\"\n" + "osVersion=\"" + osVersion + "\"\n" + "env=\""+ envData + "\"\n" + "suiteName=\""+ suiteName+ "\"\n"); + byte[] myBytes = versions.getBytes(); + fooStream.write(myBytes); + fooStream.close(); + } + + public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData) + throws FileNotFoundException, IOException { + createVersionsInfoFile(filepath, onboardVersion, osVersion, envData, null); + } + + public static void addEnvDetailsToReport() throws FileNotFoundException{ + + Config config = Utils.getConfig(); + config.getUrl(); + } + + public static File getConfigFile(String configFileName) throws Exception { + File configFile = new File(getBasePath() + File.separator + "conf" + File.separator + configFileName); + if (!configFile.exists()) { + configFile = new File(getConfFilesPath() + configFileName); + } + return configFile; + } + + public static String getCiFilesPath() { + return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci"; + } + + public static String getConfFilesPath() { + return getCiFilesPath() + File.separator + "conf" + File.separator; + } + + public static String getTestSuitesFilesPath() { + return getCiFilesPath() + File.separator + "testSuites" + File.separator; + } + public static String getBasePath() { + return System.getProperty("user.dir"); + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java new file mode 100644 index 0000000000..4ea404784a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java @@ -0,0 +1,265 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +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; +import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BaseRestUtils extends BaseValidationUtils { + public static final String contentTypeHeaderData = "application/json"; + public static final String acceptHeaderData = "application/json"; + public static final String acceptJsonHeader = "application/json"; + public static final String acceptOctetHeader = "application/octet-stream"; + public static final String authorizationHeader = "Basic " + Base64.encodeBase64String("ci:123456".getBytes()); + public static final String acceptOctetStream = "application/octet-stream"; + public static final String ecomp = "ecomp"; + public static final String authorizationPrefixString = "Basic "; + + public static final String RESOURCE_COMPONENT_TYPE = "resources"; + public static final String PRODUCT_COMPONENT_TYPE = "products"; + public static final String SERVICE_COMPONENT_TYPE = "services"; + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_CREATED = 201; + public static final int STATUS_CODE_DELETE = 204; + public static final int STATUS_CODE_NOT_FOUND = 404; + public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204; + public static final int STATUS_CODE_SUCCESS_DELETE = 204; + public static final int STATUS_CODE_INVALID_CONTENT = 400; + public static final int STATUS_CODE_MISSING_DATA = 400; + public static final int STATUS_CODE_MISSING_INFORMATION = 403; + public static final int STATUS_CODE_RESTRICTED_ACCESS = 403; + public static final int STATUS_CODE_ALREADY_EXISTS = 409; + public static final int STATUS_CODE_RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT = 400; + public static final int STATUS_CODE_MISSING_COMPONENT_NAME = 400; + public static final int STATUS_CODE_UNSUPPORTED_ERROR = 400; + public static final int STATUS_CODE_IMPORT_SUCCESS = 201; + public static final int STATUS_CODE_UPDATE_SUCCESS = 200; + public static final int RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_GET_SUCCESS = 200; + + public static final String SUCCESS_MESSAGE = "OK"; + private static Logger logger = LoggerFactory.getLogger(BaseRestUtils.class.getName()); + + private static byte[] encodeBase64; + + // ************* PRIVATE METHODS ************************ + + protected static Map prepareHeadersMap(String userId) { + return prepareHeadersMap(userId, acceptHeaderData); + } + + protected static Map prepareHeadersMap(String userId, String accept) { + Map headersMap = new HashMap(); + if (contentTypeHeaderData != null) { + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + } + if (accept != null) { + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), accept); + } + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + + return headersMap; + } + + // send request + // GET + protected static RestResponse sendGet(String url, String userId) throws IOException { + return sendGet(url, userId, null); + } + + protected static RestResponse sendGet(String url, String userId, Map additionalHeaders) + throws IOException { + Map headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + HttpRequest http = new HttpRequest(); + RestResponse getResourceResponse = http.httpSendGet(url, headersMap); + return getResourceResponse; + } + + public static RestResponse sendGetAndRemoveHeaders(String url, String userId, List headersToRemove) + throws IOException { + Map headersMap = prepareHeadersMap(userId); + if (headersToRemove != null) { + for (String header : headersToRemove) { + headersMap.remove(header); + } + } + + HttpRequest http = new HttpRequest(); + RestResponse getResourceResponse = http.httpSendGet(url, headersMap); + return getResourceResponse; + } + + // PUT + protected static RestResponse sendPut(String url, String userBodyJson, String userId, String cont) + throws IOException { + Map headersMap = prepareHeadersMap(userId, cont); + + HttpRequest http = new HttpRequest(); + RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap); + return updateResourceResponse; + } + + // POST + public static RestResponse sendPost(String url, String userBodyJson, String userId, String accept) + throws IOException { + return sendPost(url, userBodyJson, userId, accept, null); + } + + protected static RestResponse sendPost(String url, String userBodyJson, String userId, String accept, + Map additionalHeaders) throws IOException { + Map headersMap = prepareHeadersMap(userId, accept); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + HttpRequest http = new HttpRequest(); + RestResponse postResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + return postResourceResponse; + } + + // used form complex requests like import categories.. + protected static RestResponse sendPost(String url, HttpEntity entity, String userId, String accept) + throws IOException { + RestResponse postResponse = new RestResponse(); + CloseableHttpResponse response = null; + CloseableHttpClient client = null; + try { + client = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(url); + + httpPost.addHeader("USER_ID", userId); + httpPost.setEntity(entity); + response = client.execute(httpPost); + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getStatusLine().getStatusCode(); + + postResponse.setErrorCode(statusCode); + StringBuffer sb = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(responseEntity.getContent())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + sb.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + postResponse.setResponse(sb.toString()); + } finally { + try { + if (response != null) { + response.close(); + } + + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + } + return postResponse; + } + + // DELETE + protected static RestResponse sendDelete(String url, String userId) throws IOException { +// Map headersMap = prepareHeadersMap(userId); + + return sendDelete(url, userId, null); + } + + protected static RestResponse sendDelete(String url, String userId, Map additionalHeaders) throws IOException { + Map headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + HttpRequest http = new HttpRequest(); + RestResponse deleteResourceResponse = http.httpSendDelete(url, headersMap); + return deleteResourceResponse; + } + + /* + * // ------ protected static Boolean checkErrorCode(RestResponse + * deleteResponse) { if (deleteResponse.getErrorCode() == + * STATUS_CODE_SUCCESS || deleteResponse.getErrorCode() == + * STATUS_CODE_DELETE) { return true; } return false; } + * + * // *** STATUS CODE VALIDATION UTIITIES **** public static void + * checkStatusCode(RestResponse response, String assertMessage, boolean AND, + * int... statuses) { int statusCode = response.getErrorCode(); for (int + * status : statuses) { if (AND && statusCode != status) { + * Assert.fail(assertMessage + " status: " + statusCode); } else if + * (statusCode == status) { return; } } if (!AND) { + * Assert.fail(assertMessage + " status: " + statusCode); } } + * + * public static void checkDeleteResponse(RestResponse response) { + * checkStatusCode(response,"delete request failed",false,STATUS_CODE_DELETE + * ,STATUS_CODE_NOT_FOUND, STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for + * deActivate user } + * + * public static void checkCreateResponse(RestResponse response) { + * checkStatusCode(response, "create request failed", false, + * STATUS_CODE_CREATED); } + */ + public static String encodeUrlForDownload(String url) { + return url.replaceAll(" ", "%20"); + } + + public static Map addAuthorizeHeader(String userName, String password) { + String userCredentials = userName + ":" + password; + encodeBase64 = Base64.encodeBase64(userCredentials.getBytes()); + String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64); + Map authorizationHeader = new HashMap(); + authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials); + return authorizationHeader; + } + +} 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 new file mode 100644 index 0000000000..25fce34a75 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java @@ -0,0 +1,93 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +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; + +public class CatalogRestUtils extends BaseRestUtils { + + public static RestResponse getAbstractResources() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_ABSTRACT_RESOURCES, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getCatalog() throws IOException { + return getCatalog(UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getCatalog(String userId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort()); + return sendGet(url, userId); + } + + public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(), + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getAllCategoriesTowardsCatalogFeWithUuid(String uuid) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + Map additionalHeaders = new HashMap(); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders); + } + + public static RestResponse getOnboardVersion() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.ONBOARD_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getOsVersion() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.OS_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId()); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java new file mode 100644 index 0000000000..460518b35f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java @@ -0,0 +1,309 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +public class CategoryRestUtils extends BaseRestUtils { + + private static final int STATUS_CODE_CREATED = 201; + + private static Gson gson = new Gson(); + + public static RestResponse createCategory(CategoryDefinition categoryDefinition, User sdncModifierDetails, + String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType); + String bodyJson = gson.toJson(categoryDefinition); + RestResponse addCategoryResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + if (addCategoryResponse.getErrorCode().intValue() == STATUS_CODE_CREATED) + categoryDefinition.setUniqueId( + ResponseParser.getValueFromJsonResponse(addCategoryResponse.getResponse(), "uniqueId")); + return addCategoryResponse; + } + + // GET categories + public static RestResponse getAllCategories(User sdncModifierDetails, String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType); + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse getCategotyResponse = http.httpSendGet(url, headersMap); + return getCategotyResponse; + } + + public static RestResponse getAllCategoriesTowardsFe(User sdncModifierDetails, String categoryType) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), + categoryType); + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse getCategotyResponse = http.httpSendGet(url, headersMap); + return getCategotyResponse; + } + + // Delete Category + public static RestResponse deleteCategory(String categoryId, String psUserId, String categoryType) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, categoryId); + url = url.replace("#", "%23"); // HEX + url = url.replace(" ", "%20"); // HEX + RestResponse deleteCategoryResponse = sendDelete(url, psUserId); + return deleteCategoryResponse; + } + + public static RestResponse createSubCategory(SubCategoryDefinition subCategory, CategoryDefinition parentCategory, + User sdncModifierDetails, String categoryType) throws Exception { + // categoryType = service/resource/product + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, parentCategory.getUniqueId()); + String bodyJson = gson.toJson(subCategory); + RestResponse createSubCategoryPost = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + if (createSubCategoryPost.getErrorCode().intValue() == STATUS_CODE_CREATED) + subCategory.setUniqueId( + ResponseParser.getValueFromJsonResponse(createSubCategoryPost.getResponse(), "uniqueId")); + + return createSubCategoryPost; + } + + public static RestResponse deleteSubCategory(String subCategoryId, String categoryId, String psUserId, + String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, categoryId, subCategoryId); + url = url.replace("#", "%23"); // HEX + url = url.replace(" ", "%20"); // HEX + RestResponse deleteSubCategoryResponse = sendDelete(url, psUserId); + return deleteSubCategoryResponse; + } + + public static RestResponse deleteGrouping(String groupId, String subCategoryId, String categoryId, String psUserId, + String categoryType) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, categoryId, subCategoryId, groupId); + url = url.replace("#", "%23"); // HEX + url = url.replace(" ", "%20"); // HEX + RestResponse deleteGroupResponse = sendDelete(url, psUserId); + return deleteGroupResponse; + } + + public static RestResponse createServiceCategoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition, + User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + SERVICE_COMPONENT_TYPE); + + Map headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(categoryDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createCatergoryResponse = http.httpSendPost(url, userBodyJson, headersMap); + return createCatergoryResponse; + } + + public static RestResponse createSubCategoryHttpCspAtuUidIsMissing(SubCategoryDefinition subCategory, + CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception { + // categoryType = service/resource/product + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, parentCategory.getUniqueId()); + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String subCatJson = gson.toJson(subCategory); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(subCatJson); + RestResponse addCategoryResponse = http.httpSendPost(url, subCatJson, headersMap); + return addCategoryResponse; + } + + public static RestResponse deleteCatergoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition, + User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryDataDefinition.getName()); + + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(categoryDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse deleteCategotyResponse = http.httpSendDelete(url, headersMap); + return deleteCategotyResponse; + } + + public static RestResponse createGrouping(GroupingDefinition grouping, SubCategoryDefinition subCategory, + CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, parentCategory.getUniqueId(), subCategory.getUniqueId()); + String bodyJson = gson.toJson(grouping); + RestResponse addGroupingResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + return addGroupingResponse; + } + + public static RestResponse importCategories(MultipartEntityBuilder mpBuilder, String userId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.IMPORT_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort()); + + RestResponse importResponse = BaseRestUtils.sendPost(url, mpBuilder.build(), userId, acceptHeaderData); + return importResponse; + } + + public static int getMatchingCategoriesNum(RestResponse getAllCategoryRest, CategoryDefinition categoryDefinition) { + String response = getAllCategoryRest.getResponse(); + Gson gson = new Gson(); + List categoryDefinitions = gson.fromJson(response, + new TypeToken>() { + }.getType()); + int categoriesNum = 0; + String catName = categoryDefinition.getName(); + for (CategoryDefinition elem : categoryDefinitions) { + if (elem.getName().equals(catName)) { + categoryDefinition.setUniqueId(elem.getUniqueId()); + categoriesNum++; + } + } + + return categoriesNum; + } + + public static int getMatchingSubCategoriesNum(RestResponse getAllCategoryRest, String parentCategoryId, + SubCategoryDefinition expectedSubCategoryDefinition) { + + String response = getAllCategoryRest.getResponse(); + Gson gson = new Gson(); + List categoryDefinitions = gson.fromJson(response, + new TypeToken>() { + }.getType()); + int subCatNum = 0; + String subCatName = expectedSubCategoryDefinition.getName(); + for (CategoryDefinition elem : categoryDefinitions) { + if (elem.getUniqueId().equals(parentCategoryId)) { + List subCategories = elem.getSubcategories(); + if (subCategories != null) { + for (SubCategoryDefinition subCategoryDataDefinition : subCategories) { + if (subCatName.equals(subCategoryDataDefinition.getName())) { + expectedSubCategoryDefinition.setUniqueId(subCategoryDataDefinition.getUniqueId()); + subCatNum++; + } + } + } + + } + } + return subCatNum; + } + + public static int getMatchingGroupingNum(RestResponse getAllCategoryRest, String parentCategoryId, + String subCategoryId, GroupingDefinition expectedGroupingDefinition) { + + String response = getAllCategoryRest.getResponse(); + Gson gson = new Gson(); + List categoryDefinitions = gson.fromJson(response, + new TypeToken>() { + }.getType()); + int groupingNum = 0; + String groupingName = expectedGroupingDefinition.getName(); + for (CategoryDefinition elem : categoryDefinitions) { + if (elem.getUniqueId().equals(parentCategoryId)) { + List subCategories = elem.getSubcategories(); + if (subCategories != null) { + for (SubCategoryDefinition subCategoryDataDefinition : subCategories) { + // if + // (subCategoryId.equals(subCategoryDataDefinition.getUniqueId())) + // { + if (subCategoryId.equals(subCategoryDataDefinition.getUniqueId()) + && subCategoryDataDefinition.getGroupings() != null) { + List grouping = subCategoryDataDefinition.getGroupings(); + for (GroupingDefinition groupingDataDefinition : grouping) { + if (groupingName.equals(groupingDataDefinition.getName())) { + expectedGroupingDefinition.setUniqueId(groupingDataDefinition.getUniqueId()); + groupingNum++; + } + } + + } + } + } + + } + } + return groupingNum; + } + + public enum CategoryAuditJsonKeysEnum { + ACTION("ACTION"), MODIFIER("MODIFIER"), CATEGORY_NAME("CATEGORY_NAME"), SUB_CATEGORY_NAME("SUB_CATEGORY_NAME"), GROUPING_NAME("GROUPING_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), DESCRIPTION("DESCRIPTION"), DETAILS("DETAILS"); + + private String auditJsonKeyName; + + private CategoryAuditJsonKeysEnum(String auditJsonKeyName) { + this.auditJsonKeyName = auditJsonKeyName; + } + + public String getAuditJsonKeyName() { + return auditJsonKeyName.toLowerCase(); + } + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java new file mode 100644 index 0000000000..1b550e4fff --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java @@ -0,0 +1,276 @@ +/*- + * ============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.ci.tests.utils.rest; + +import static org.testng.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +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 com.google.gson.Gson; + +public class ComponentInstanceRestUtils extends BaseRestUtils { + public static String acceptHeaderDate = "application/json"; + static Config config = Config.instance(); + public static Gson gson = new Gson(); + + // 'componentType' can be 'services' or 'resources' + + public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, Component component) throws Exception { + return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, component.getUniqueId(), + component.getComponentType()); + } + + public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws Exception { + + return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, componentId, + ComponentTypeEnum.findParamByType(componentType)); + } + + public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, String componentId, String componentType) throws Exception { + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String serviceBodyJson = gson.toJson(componentInstanceReqDetails); + String url = String.format(Urls.CREATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), + componentType, componentId); + RestResponse createResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData); + if (createResourceInstance.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED)) { + String uniqueId = ResponseParser.getValueFromJsonResponse(createResourceInstance.getResponse(), "uniqueId"); + componentInstanceReqDetails.setUniqueId(uniqueId); + // Gson gson = new Gson(); + // ResourceInstanceReqDetails fromJson = + // gson.fromJson(createResourceInstance.getResponse(), + // ResourceInstanceReqDetails.class); + // componentInstanceReqDetails.setUniqueId(fromJson.getUniqueId()); + } + return createResourceInstance; + } + + public static RestResponse getComponentInstances(ComponentTypeEnum type, String componentId, User user) + throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + String url = String.format(Urls.GET_COMPONENT_INSTANCES, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(type), componentId); + + RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap); + + return sendGetServerRequest; + + } + + public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId, + String resourceInstanceId, ComponentTypeEnum componentType) throws Exception { + + return deleteComponentInstance(sdncModifierDetails, componentId, resourceInstanceId, + ComponentTypeEnum.findParamByType(componentType)); + } + + public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId, + String resourceInstanceId, String componentTypeString) throws Exception { + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String url = String.format(Urls.DELETE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), + componentTypeString, componentId, resourceInstanceId); + RestResponse sendCreateUserRequest = sendDelete(url, userId); + return sendCreateUserRequest; + } + + public static RestResponse updateComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws IOException { + + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String serviceBodyJson = gson.toJson(componentInstanceReqDetails); + String url = String.format(Urls.UPDATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(componentType), componentId, + componentInstanceReqDetails.getUniqueId()); + RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData); + return updateResourceInstance; + } + + //Tal G - CI for New API Multiple Instance Update + public static RestResponse updateMultipleComponentInstance( + List componentInstanceReqDetailsList, User sdncModifierDetails, + String componentId, ComponentTypeEnum componentType) throws IOException { + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String serviceBodyJson = gson.toJson(componentInstanceReqDetailsList.toArray()); + String url = String.format(Urls.UPDATE_MULTIPLE_COMPONENT_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentId); + RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData); + return updateResourceInstance; + } + + public static RestResponse associateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails, + String componentId, ComponentTypeEnum componentTypeEnum) throws IOException { + + Config config = Utils.getConfig(); + + String componentType = ""; + switch (componentTypeEnum) { + case RESOURCE: + componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME; + break; + case SERVICE: + componentType = ComponentTypeEnum.SERVICE_PARAM_NAME; + break; + default: + break; + } + String serviceBodyJson = gson.toJson(relation); + String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), componentType, componentId); + + RestResponse associateInstance = sendPost(url, serviceBodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + return associateInstance; + + } + + public static RestResponse dissociateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails, + String componentId, ComponentTypeEnum componentTypeEnum) throws IOException { + + Config config = Utils.getConfig(); + + String componentType = ""; + switch (componentTypeEnum) { + case RESOURCE: + componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME; + break; + case SERVICE: + componentType = ComponentTypeEnum.SERVICE_PARAM_NAME; + break; + default: + break; + } + String serviceBodyJson = gson.toJson(relation); + String url = String.format(Urls.DISSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), componentType, componentId); + + RestResponse associateInstance = sendPut(url, serviceBodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + return associateInstance; + + } + + public static void checkComponentInstanceType(RestResponse response, String expectedComponentType) { + String actualComponentType = ResponseParser.getComponentTypeFromResponse(response); + assertTrue(expectedComponentType.equals(actualComponentType), + "Failed. expected: " + expectedComponentType + ", actual: " + actualComponentType + "/"); + } + + public static RestResponse updatePropertyValueOnResourceInstance(Component component, ComponentInstance instDetails, + User user, ComponentInstanceProperty updatedInstanceProperty) throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + String url = String.format(Urls.UPDATE_PROPERTY_TO_RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), + component.getUniqueId(), instDetails.getUniqueId()); + String body = gson.toJson(updatedInstanceProperty); + + RestResponse sendGetServerRequest = sendPost(url, body, user.getUserId(), acceptHeaderData); + return sendGetServerRequest; + + } + + public static RestResponse changeComponentInstanceVersion(Component container, + ComponentInstance componentInstanceToReplace, Component newInstance, User sdncModifierDetails) + throws Exception { + + return changeComponentInstanceVersion(container.getUniqueId(), componentInstanceToReplace, newInstance, + sdncModifierDetails, container.getComponentType()); + } + + public static RestResponse changeComponentInstanceVersion(String containerUID, + ComponentInstance componentInstanceToReplace, Component component, User sdncModifierDetails, + ComponentTypeEnum componentType) throws IOException { + + Config config = Utils.getConfig(); + String resourceUid = ("{\"componentUid\":\"" + component.getUniqueId() + "\"}"); + String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), containerUID, + componentInstanceToReplace.getUniqueId()); + RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(), + acceptHeaderData); + + if (changeResourceInstanceVersion.getErrorCode() == 200 + || changeResourceInstanceVersion.getErrorCode() == 201) { + Gson gson = new Gson(); + // ResourceInstanceReqDetails + // convertResourceInstanceResponseToJavaObject = + // ResponseParser.convertResourceInstanceResponseToJavaObject(createResourceInstance.getResponse()); + ComponentInstanceReqDetails fromJson = gson.fromJson(changeResourceInstanceVersion.getResponse(), + ComponentInstanceReqDetails.class); + + componentInstanceToReplace.setUniqueId(fromJson.getUniqueId()); + + } + + return changeResourceInstanceVersion; + + } + + public static RestResponse changeComponentInstanceVersion(String componentUniqueId, + String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, + ComponentTypeEnum componentType) throws IOException { + Config config = Utils.getConfig(); + String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}"); + String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId, + serviceInstanceToReplaceUniqueId); + RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(), + acceptHeaderData); + return changeResourceInstanceVersion; + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java new file mode 100644 index 0000000000..dcebe4afa8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java @@ -0,0 +1,62 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.CapReqDef; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +public class ComponentRestUtils extends BaseRestUtils { + public static RestResponse getComponentRequirmentsCapabilities(User sdncModifierDetails, + ComponentReqDetails componentReqDetails) throws IOException { + Config config = Utils.getConfig(); + ComponentTypeEnum componentType = null; + if (componentReqDetails instanceof ResourceReqDetails) { + componentType = ComponentTypeEnum.RESOURCE; + } else if (componentReqDetails instanceof ServiceReqDetails) { + componentType = ComponentTypeEnum.SERVICE; + } else if (componentReqDetails instanceof ProductReqDetails) { + componentType = ComponentTypeEnum.PRODUCT; + } + String url = String.format(Urls.GET_COMPONENT_REQUIRMENTS_CAPABILITIES, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), + componentReqDetails.getUniqueId()); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static CapReqDef getAndParseComponentRequirmentsCapabilities(User user, ComponentReqDetails componentDetails) + throws IOException { + RestResponse getComponentReqCap = getComponentRequirmentsCapabilities(user, componentDetails); + ResourceRestUtils.checkSuccess(getComponentReqCap); + CapReqDef capReqDef = ResponseParser.parseToObject(getComponentReqCap.getResponse(), CapReqDef.class); + return capReqDef; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java new file mode 100644 index 0000000000..71735d5a4a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java @@ -0,0 +1,245 @@ +/*- + * ============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.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertEquals; + +import java.util.Map; + +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; + +public class ConsumerRestUtils extends BaseRestUtils { + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_CREATED = 201; + public static final int STATUS_CODE_DELETE = 204; + public static final int STATUS_CODE_NOT_FOUND = 404; + Utils utils = new Utils(); + private static Long expectedsLastupdatedtime; + private static Long expectedLastAuthenticationTime; + + public static RestResponse createConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) + throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(consumerDataDefinition); + + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) { + ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse); + consumerDataDefinition + .setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime()); + consumerDataDefinition + .setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime()); + consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid()); + } + return createConsumerResponse; + } + + public static RestResponse createConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, + User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(consumerDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) { + ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse); + consumerDataDefinition + .setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime()); + consumerDataDefinition + .setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime()); + consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid()); + } + return createConsumerResponse; + } + + public static RestResponse deleteConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, + User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), + consumerDataDefinition.getConsumerName()); + + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(consumerDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap); + return deleteConsumerResponse; + } + + public static ConsumerDataDefinition parseComsumerResp(RestResponse restResponse) throws Exception { + + String bodyToParse = restResponse.getResponse(); + ObjectMapper mapper = new ObjectMapper(); + try { + ConsumerDataDefinition component = mapper.readValue(bodyToParse, ConsumerDataDefinition.class); + return component; + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + public static RestResponse deleteConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) + throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), + consumerDataDefinition.getConsumerName()); + + String userId = sdncModifierDetails.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap); + return deleteConsumerResponse; + } + + public static RestResponse getConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) + throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), + consumerDataDefinition.getConsumerName()); + + String userId = sdncModifierDetails.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse getConsumerResponse = http.httpSendGet(url, headersMap); + return getConsumerResponse; + } + + public static void validateConsumerReqVsResp(ConsumerDataDefinition consumerDefinition, + ConsumerDataDefinition getConsumerDataObject) { + + String expected; + + expected = consumerDefinition.getConsumerName(); + assertEquals("consumer name - ", expected, getConsumerDataObject.getConsumerName()); + + expected = consumerDefinition.getConsumerPassword().toLowerCase(); + assertEquals("consumer password - ", expected, getConsumerDataObject.getConsumerPassword()); + + expected = consumerDefinition.getLastModfierAtuid(); + assertEquals("consumer Last Modfier Atuid - ", expected, getConsumerDataObject.getLastModfierAtuid()); + + expected = consumerDefinition.getConsumerSalt(); + assertEquals("consumer Salt - ", expected, getConsumerDataObject.getConsumerSalt()); + + expectedsLastupdatedtime = consumerDefinition.getConsumerDetailsLastupdatedtime(); + assertEquals("consumer Last updated time - ", expectedsLastupdatedtime, + getConsumerDataObject.getConsumerDetailsLastupdatedtime()); + + expectedLastAuthenticationTime = consumerDefinition.getConsumerLastAuthenticationTime(); + assertEquals("consumer Last authentication time - ", expectedLastAuthenticationTime, + getConsumerDataObject.getConsumerLastAuthenticationTime()); + } + + ///// New + public enum EcompConsumerAuditJsonKeysEnum { + ACTION("ACTION"), MODIFIER("MODIFIER"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), DESC("DESCRIPTION"); + private String auditJsonKeyName; + + private EcompConsumerAuditJsonKeysEnum(String auditJsonKeyName) { + this.auditJsonKeyName = auditJsonKeyName; + } + + public String getAuditJsonKeyName() { + return auditJsonKeyName.toLowerCase(); + } + } + + /* + * protected void resourceArtifatAuditSuccess(String action, + * ArtifactReqDetails artifact, ResourceReqDetails resourceDetails , User + * user) throws Exception { ExpectedResourceAuditJavaObject + * expectedResourceAuditJavaObject = + * Convertor.constructFieldsForAuditValidation(resourceDetails, + * resourceDetails.getVersion(), user); String auditAction = action; + * expectedResourceAuditJavaObject.setAction(auditAction); + * expectedResourceAuditJavaObject.setPrevState(""); + * expectedResourceAuditJavaObject.setPrevVersion(""); + * expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum. + * NOT_CERTIFIED_CHECKOUT).toString()); + * expectedResourceAuditJavaObject.setStatus("200"); + * expectedResourceAuditJavaObject.setDesc("OK"); + * expectedResourceAuditJavaObject.setArtifactName(artifact.getArtifactName( + * )); AuditUtils.validateAudit(expectedResourceAuditJavaObject, + * auditAction, null); } + */ + + /* + * protected void resourceArtifatValidateAuditWithErrorMessage(String + * actionStatus, ResourceReqDetails resourceDetails, String auditAction, + * String setCurrState, Object ... variables)throws Exception { ErrorInfo + * errorInfo = utils.parseYaml(actionStatus); + * ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + * Convertor.constructFieldsForAuditValidation(resourceDetails, + * resourceDetails.getVersion(), sdncUserDetails); + * expectedResourceAuditJavaObject.setAction(auditAction); + * expectedResourceAuditJavaObject.setPrevState(""); + * expectedResourceAuditJavaObject.setPrevVersion(""); + * expectedResourceAuditJavaObject.setCurrState(setCurrState); + * expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()) + * ; + * expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables) + * ); expectedResourceAuditJavaObject.setArtifactName(""); + * AuditUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, + * null); } + */ +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java new file mode 100644 index 0000000000..458aa4a91c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java @@ -0,0 +1,253 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +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; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class EcompUserRestUtils extends BaseRestUtils { + + static Gson gson = new Gson(); + + static Logger logger = LoggerFactory.getLogger(EcompUserRestUtils.class.getName()); + static String contentTypeHeaderData = "application/json"; + static String acceptHeaderDate = "application/json"; + static String ecompUsername = "12345"; + static String ecompPassword = "12345"; + + public EcompUserRestUtils() { + super(); + + StartTest.enableLogger(); + } + + public static RestResponse pushUser(EcompUser ecompUser) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + String userBodyJson = gson.toJson(ecompUser); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_PUSH_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + + logger.debug("Send POST request to create user: {}", url); + logger.debug("User body: {}", userBodyJson); + logger.debug("User headers: {}", headersMap); + + RestResponse sendPushUserResponse = http.httpSendPost(url, userBodyJson, headersMap); + + return sendPushUserResponse; + } + + /* + * loginId - equals to userId + */ + public static RestResponse editUser(String loginId, EcompUser ecompUser) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + String userBodyJson = gson.toJson(ecompUser); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_EDIT_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId); + + logger.debug("Send POST request to edit user: {}", url); + logger.debug("User body: {}", userBodyJson); + logger.debug("User headers: {}", headersMap); + + RestResponse sendEditUserResponse = http.httpSendPost(url, userBodyJson, headersMap); + + return sendEditUserResponse; + } + + /* + * loginId - equals to userId + */ + public static RestResponse getUser(String loginId) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId); + + logger.debug("Send GET request to get user: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + + return sendGetUserRequest; + } + + public static RestResponse getAllUsers() throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort()); + + logger.debug("Send POST request to get all users: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendGetAllUsersRequest = http.httpSendGet(url, headersMap); + + return sendGetAllUsersRequest; + } + + public static RestResponse getAllAvailableRoles() throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_ALL_AVAILABLE_ROLES, config.getCatalogBeHost(), + config.getCatalogBePort()); + + logger.debug("Send GET request to get all available roles: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendUpdateUserRequest = http.httpSendGet(url, headersMap); + + return sendUpdateUserRequest; + } + + /* + * loginId - equals to userId + */ + public static RestResponse pushUserRoles(String loginId, List roles) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + String roleBodyJson = gson.toJson(roles); + if(roleBodyJson.equals("[{}]")) { + roleBodyJson = "[]"; + } + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_PUSH_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), + loginId); + + logger.debug("Send POST request to push user role: {}", url); + logger.debug("Roles body: {}", roleBodyJson); + logger.debug("Request headers: {}", headersMap); + + RestResponse sendpushUserRolesResponse = http.httpSendPost(url, roleBodyJson, headersMap); + + return sendpushUserRolesResponse; + } + + /* + * loginId - equals to userId + */ + public static RestResponse getUserRoles(String loginId) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), + loginId); + + logger.debug("Send GET request to get user roles: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendGetUserRolesRequest = http.httpSendGet(url, headersMap); + + return sendGetUserRolesRequest; + } + + // TODO !!!!!!!!!!!!!! + /* + * Ask Eli if implementation of users is needed DELETE ECOMP USER + */ + + /* + * public static void main(String[] args) { EcompUser ecompUser = new + * EcompUser(); ecompUser.setFirstName("Test"); + * ecompUser.setLastName("Testovich"); + * ecompUser.setActive(true); + * + * EcompRole roleToUpdate = new EcompRole(); roleToUpdate.setId(new + * Long(6)); roleToUpdate.setName("PRODUCT_STRATEGIST"); List + * listOfRoles = new LinkedList<>(); listOfRoles.add(roleToUpdate); + * + * try { + * System.out.println("\n-----------------------------\n Testing pushUser"); + * System.out.println(pushUser(ecompUser)); + * System.out.println("\n-----------------------------\n Testing editUser"); + * System.out.println("\n-----------------------------\n Testing getUser"); + * // System.out.println(getUser(ecompUser.getLoginId())); System.out. + * println("\n-----------------------------\n Testing getAllUsers"); // + * System.out.println(getAllUsers()); System.out. + * println("\n-----------------------------\n Testing getAllAvailableRoles" + * ); // System.out.println(getAllAvailableRoles().toString()); System.out. + * println("\n-----------------------------\n Testing pushUserRoles"); + * TODO Auto-generated catch block e.printStackTrace(); } } + */ +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java new file mode 100644 index 0000000000..d79c8e002c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java @@ -0,0 +1,61 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +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 com.google.gson.Gson; + +public class GroupRestUtils extends BaseRestUtils { + public static String acceptHeaderDate = "application/json"; + static Config config = Config.instance(); + public static Gson gson = new Gson(); + + public static RestResponse getGroupById(Component component, String groupId, User user) throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + String url = String.format(Urls.GET_GROUP_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), groupId); + + RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap); + + return sendGetServerRequest; + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java new file mode 100644 index 0000000000..951831c39d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java @@ -0,0 +1,408 @@ +/*- + * ============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.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.codehaus.jettison.json.JSONException; +import org.openecomp.sdc.be.dao.rest.HttpRestClient; +import org.openecomp.sdc.be.model.User; +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.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ImportRestUtils extends BaseRestUtils { + + private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName()); + private static Properties downloadCsarHeaders = new Properties(); + + static { + downloadCsarHeaders.put("Accept", "application/octet-stream"); + } + + @SuppressWarnings("unused") + private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole) + throws IOException { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName()))); + mpBuilder.addPart("resourceMetadata", + new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"), + ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), + config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("USER_ID", userRole.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + return response.getStatusLine().getStatusCode(); + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + /* + * public static RestResponse importResourceByName(String resourceName, User + * user) throws IOException { Config config = Utils.getConfig(); + * CloseableHttpResponse response = null; MultipartEntityBuilder mpBuilder = + * MultipartEntityBuilder.create(); + * + * mpBuilder.addPart("resourceZip", new + * FileBody(getTestZipFile(resourceName))); + * mpBuilder.addPart("resourceMetadata", new + * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"), + * ContentType.APPLICATION_JSON)); + * + * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, + * config.getCatalogBeHost(), config.getCatalogBePort()); + * + * CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost + * httpPost = new HttpPost(url); RestResponse restResponse = new + * RestResponse(); httpPost.addHeader("USER_ID", user.getUserId()); + * httpPost.setEntity(mpBuilder.build()); response = + * client.execute(httpPost); HttpEntity entity = response.getEntity(); + * String responseBody = null; if (entity != null) { InputStream instream = + * entity.getContent(); StringWriter writer = new StringWriter(); + * IOUtils.copy(instream, writer); responseBody = writer.toString(); try { + * + * } finally { instream.close(); } } + * + * restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + * restResponse.setResponse(responseBody); if (restResponse.getErrorCode() + * == STATUS_CODE_CREATED ){ + * + * } + * + * return restResponse; + * + * } finally { closeResponse(response); closeHttpClient(client); + * + * } + * + * } + */ + + public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer) + throws Exception { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName()))); + mpBuilder.addPart("resourceMetadata", + new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"), + ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), + config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + httpPost.addHeader("USER_ID", importer.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + if (restResponse.getErrorCode() == STATUS_CODE_CREATED) { + resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse)); + resourceDetails.setCreatorUserId(importer.getUserId()); + resourceDetails.setCreatorFullName(importer.getFullName()); + } + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + + } + + public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException { + Config config = Utils.getConfig(); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName))); + mpBuilder.addPart("resourceMetadata", new StringBody( + getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON)); + HttpEntity requestEntity = mpBuilder.build(); + String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + Map headers = new HashMap(); + headers.put("USER_ID", userRole.getUserId()); + + return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers); + } + + public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole) + throws IOException { + Config config = Utils.getConfig(); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName))); + mpBuilder.addPart("resourceMetadata", new StringBody( + getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON)); + HttpEntity requestEntity = mpBuilder.build(); + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), + config.getCatalogBePort()); + Map headers = new HashMap(); + headers.put("USER_ID", userRole.getUserId()); + + return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers); + } + + public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole) + throws IOException { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName()))); + mpBuilder.addPart("resourceMetadata", + new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"), + ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), + config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + // restResponse.setResponse(response.getEntity().toString()); + restResponse.setResponse(responseBody); + return restResponse; + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + public static Boolean removeNormativeTypeResource(NormativeTypesEnum current) + throws FileNotFoundException, IOException, ClientProtocolException { + User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(), + UserRoleEnum.ADMIN.getUserId(), null, null, null); + RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(), + "1.0"); + if (deleteResponse.getErrorCode() == 200) { + return true; + } + return false; + } + + public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse) + throws IOException, JSONException { + + // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS ); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + List variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() + : new ArrayList()); + if (restResponse.getErrorCode() != 200) { + ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables, + restResponse.getResponse()); + } + } + + private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException { + // String sourceDir = "src/test/resources/CI/importResourceTests"; + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, + fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static File getTestZipFile(String elementName) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, + "normative-types-new-" + elementName + ".zip"); + return filePath.toFile(); + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + log.debug("failed to close client or response: ", e); + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + log.debug("failed to close client or response: {}", e); + } + } + + public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), + csarUid); + + String userId = sdncModifierDetails.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + // Gson gson = new Gson(); + // String userBodyJson = gson.toJson(resourceDetails); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + + HttpRestClient httpRestClient = new HttpRestClient(); + + for (Map.Entry mapEntry : headersMap.entrySet()) { + + downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue()); + } + RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders); + // RestResponse getCsar = http.httpSendGet(url, headersMap); + + return doGetAsByteArray; + + } + + private static File getGroupTypeZipFile(String elementName) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, + elementName + ".zip"); + return filePath.toFile(); + } + + public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole) + throws IOException { + Config config = Utils.getConfig(); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName))); + HttpEntity requestEntity = mpBuilder.build(); + String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort()); + Map headers = new HashMap(); + headers.put("USER_ID", userRole.getUserId()); + + return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java new file mode 100644 index 0000000000..de7be077d1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java @@ -0,0 +1,122 @@ +/*- + * ============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.ci.tests.utils.rest; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +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.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +/** + * RestUtils for inputs + * + * @author il0695 + * + */ +public class InputsRestUtils extends BaseRestUtils { + + @SuppressWarnings("unused") + private static Logger logger = LoggerFactory.getLogger(InputsRestUtils.class.getName()); + + /** + * Add inputs to service + * + * @param component + * @param inputs + * @param userRole + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse addInput(Component component, ComponentInstInputsMap inputs, UserRoleEnum userRole) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId()); + String json = new Gson().toJson(inputs); + return sendPost(url, json, userRole.getUserId(), acceptHeaderData); + } + + /** + * Get all Component inputs + * + * @param component + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse getComponentInputs(Component component) throws Exception { + Config config = Utils.getConfig(); + //services/{componentId}/inputs + String url = String.format(Urls.GET_COMPONENT_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId()); + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + /** + * Get all inputs of component instance + * + * @param parentComponent + * @param componentInstance + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse getComponentInstanceInputs(Component parentComponent, ComponentInstance componentInstance) throws Exception { + Config config = Utils.getConfig(); + //{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs + String url = String.format(Urls.GET_COMPONENT_INSTANCE_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), componentInstance.getUniqueId(), componentInstance.getComponentUid()); + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + /** + * Delete input from component + * + * @param parentComponent + * @param inputId + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse deleteInputFromComponent(Component parentComponent, String inputId) throws Exception { + return deleteInputFromComponent(ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), inputId); + } + + /** + * Delete input from component + * + * @param componentType + * @param componentId + * @param inputUniqueId + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse deleteInputFromComponent(String componentType, String componentId, String inputUniqueId) throws Exception { + Config config = Utils.getConfig(); + //{componentType}/{componentId}/delete/{inputId}/input + String url = String.format(Urls.DELETE_INPUT_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, componentId, inputUniqueId); + return sendDelete(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + +} 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 new file mode 100644 index 0000000000..d53d2da91b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java @@ -0,0 +1,451 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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.UserRoleEnum; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LifecycleRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(LifecycleRestUtils.class.getName()); + public static final String COMMENT = "comment"; + + // External APIs + public static RestResponse checkInResource(String resourceUUID, User sdncModifierDetails) throws IOException { + String comment = "Chekin resource: " + resourceUUID; + return changeLifeCycleOfAsset(resourceUUID, AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CHECKIN, sdncModifierDetails, comment); + } + + public static RestResponse checkInService(String serviceUUID, User sdncModifierDetails) throws IOException { + String comment = "Chekin service: " + serviceUUID; + return changeLifeCycleOfAsset(serviceUUID, AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CHECKIN, sdncModifierDetails, comment); + } + + public static RestResponse checkOutResource(String resourceUUID, User sdncModifierDetails) throws IOException { + String comment = "CheckOut resource: " + resourceUUID; + return changeLifeCycleOfAsset(resourceUUID, AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CHECKOUT, sdncModifierDetails, comment); + } + + public static RestResponse checkOutService(String serviceUUID, User sdncModifierDetails) throws IOException { + String comment = "CheckOut service: " + serviceUUID; + return changeLifeCycleOfAsset(serviceUUID, AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CHECKOUT, sdncModifierDetails, comment); + } + + public static RestResponse certificationRequestService(String serviceUUID, User sdncModifierDetails) throws IOException { + String comment = "Certification request service: " + serviceUUID; + return changeLifeCycleOfAsset(serviceUUID, AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CERTIFICATIONREQUEST, sdncModifierDetails, comment); + } + + public static RestResponse certificationRequestResource(String resourceUUID, User sdncModifierDetails) throws IOException { + String comment = "Certification request resource: " + resourceUUID; + return changeLifeCycleOfAsset(resourceUUID, AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CERTIFICATIONREQUEST, sdncModifierDetails, comment); + } + + public static RestResponse startTestingService(String serviceUUID, User sdncModifierDetails) throws IOException { + String comment = "Start testing request service: " + serviceUUID; + return changeLifeCycleOfAsset(serviceUUID, AssetTypeEnum.SERVICES, LifeCycleStatesEnum.STARTCERTIFICATION, sdncModifierDetails, comment); + } + + public static RestResponse startTestingResource(String resourceUUID, User sdncModifierDetails) throws IOException { + String comment = "Start testing request resource: " + resourceUUID; + return changeLifeCycleOfAsset(resourceUUID, AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.STARTCERTIFICATION, sdncModifierDetails, comment); + } + + public static RestResponse certifyService(String serviceUUID, User sdncModifierDetails) throws IOException { + String comment = "Certify request service: " + serviceUUID; + return changeLifeCycleOfAsset(serviceUUID, AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CERTIFY, sdncModifierDetails, comment); + } + + public static RestResponse certifyResource(String resourceUUID, User sdncModifierDetails) throws IOException { + String comment = "Certify request resource: " + resourceUUID; + return changeLifeCycleOfAsset(resourceUUID, AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CERTIFY, sdncModifierDetails, comment); + } + + + + + + private static RestResponse changeLifeCycleOfAsset(String assetUUID, AssetTypeEnum assetTypeEnum, LifeCycleStatesEnum lifeCycleStatesEnum, User sdncModifierDetails, String comment) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.POST_EXTERNAL_API_CHANGE_LIFE_CYCLE_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), assetTypeEnum.getValue(), assetUUID, lifeCycleStatesEnum.getState()); + + Map additionalHeaders = new HashMap(); + + additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + String jsonBody = "{\"userRemarks\": \"" + comment + "\"}"; + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + + return res; + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException { + return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + } + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException { + + return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, LifecycleChangeInfo); + + } + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException { + + return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + + } + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, String modifierUserId, + LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException { + User user = new User(); + user.setUserId(modifierUserId); + return changeResourceState(resourceDetails, user, LifeCycleStatesEnum, createLifecycleCommentJson(COMMENT)); + } + + private static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_RESOURCE_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetails.getUniqueId(), LifeCycleStatesEnum); + // System.out.println("url: " + url); + + RestResponse LifeCycleStatesEnumResourceResponse = sendPost(url, LifecycleChangeInfo, + sdncModifierDetails.getUserId(), acceptHeaderData); + if (LifeCycleStatesEnumResourceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String stateFromJsonResponse = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumResourceResponse.getResponse(), "lifecycleState"); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(LifeCycleStatesEnumResourceResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(LifeCycleStatesEnumResourceResponse)); + if (stateFromJsonResponse != null) { + resourceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse)); + } + } + return LifeCycleStatesEnumResourceResponse; + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + { + return changeServiceState(serviceDetails, sdncModifierDetails, version, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + } + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + { + return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + } + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + { + return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum, + lifecycleChangeInfo); + } + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + + Config config = Utils.getConfig(); + Map headersMap = prepareHeadersMap(sdncModifierDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CHANGE_SERVICE_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceDetails.getUniqueId(), LifeCycleStatesEnum); + // System.out.println("url: " + url); + RestResponse LifeCycleStatesEnumServiceResponse = http.httpSendPost(url, lifecycleChangeInfo, headersMap); + if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String serviceUniqueId = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId"); + serviceDetails.setUniqueId(serviceUniqueId); + String serviceVersion = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version"); + serviceDetails.setVersion(serviceVersion); + String stateFromJsonResponse = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState"); + serviceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse)); + } + return LifeCycleStatesEnumServiceResponse; + } + + public static RestResponse changeProductState(Product product, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + { + return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, lifecycleChangeInfo); + } + } + + public static RestResponse changeProductState(Product product, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + { + return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, COMMENT); + } + } + + public static RestResponse changeProductState(ProductReqDetails productDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), productDetails.getUniqueId(), LifeCycleStatesEnum); + RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), + sdncModifierDetails.getUserId(), acceptHeaderData); + if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String productUniqueId = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId"); + productDetails.setUniqueId(productUniqueId); + String productVersion = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version"); + productDetails.setVersion(productVersion); + String newLifecycleState = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState"); + productDetails.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState)); + } + return LifeCycleStatesEnumServiceResponse; + + } + + public static RestResponse changeComponentState(Component component, User sdncModifierDetails, + 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); + if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String productUniqueId = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId"); + component.setUniqueId(productUniqueId); + String productVersion = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version"); + component.setVersion(productVersion); + String newLifecycleState = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState"); + component.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState)); + } + return LifeCycleStatesEnumServiceResponse; + + } + + public static RestResponse certifyResource(ResourceReqDetails resourceDetails) throws Exception { + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + // if (restResponseResource.getErrorCode() == 200){ + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // }else + // return restResponseResource; + User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponseResource; + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails, + LifeCycleStatesEnum.CERTIFY); + if (restResponseResource.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponseResource); + resourceDetails.setVersion(newVersion); + resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resourceDetails.setLastUpdaterUserId(testerDetails.getUserId()); + resourceDetails.setLastUpdaterFullName(testerDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseResource); + resourceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponseResource; + } + + public static RestResponse certifyService(ServiceReqDetails serviceDetails) throws Exception { + RestResponse restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + // if (restResponseService.getErrorCode() == 200){ + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // }else + // return restResponseService; + if (restResponseService.getErrorCode() == 200) { + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponseService; + if (restResponseService.getErrorCode() == 200) { + User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, testerDetails, + LifeCycleStatesEnum.CERTIFY); + if (restResponseService.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponseService); + serviceDetails.setVersion(newVersion); + serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + serviceDetails.setLastUpdaterUserId(testerDetails.getUserId()); + serviceDetails.setLastUpdaterFullName(testerDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseService); + serviceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponseService; + } + + private static RestResponse _changeProductState(Product product, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), product.getUniqueId(), LifeCycleStatesEnum); + RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(lifecycleChangeInfo), + sdncModifierDetails.getUserId(), acceptHeaderData); + + return LifeCycleStatesEnumServiceResponse; + } + + public static String createLifecycleCommentJson(String commentContent) { + String res = null; + if (commentContent != null) { + res = "{\"userRemarks\": \"" + commentContent + "\"}"; + } + return res; + } + + public static void checkLCS_Response(RestResponse response) { + checkStatusCode(response, "change lifecycle request failed", false, STATUS_CODE_SUCCESS); + } + + private static Map prepareHeadersMap(User sdncModifierDetails) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + return headersMap; + } + + public static RestResponse changeDistributionStatus(ServiceReqDetails serviceDetails, String version, User user, + String userRemarks, DistributionStatusEnum reqDistributionStatus) throws Exception { + String uniqueId = serviceDetails.getUniqueId(); + Config config = Utils.getConfig(); + String environmentName = "PROD-Andreys-Only"; +// String environmentName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + DistributionStatusEnum distributionStatusEnum = DistributionStatusEnum.findState(reqDistributionStatus.getValue()); + switch(distributionStatusEnum){ + case DISTRIBUTION_APPROVED: + return sendApproveDistribution(user, uniqueId, userRemarks); + case DISTRIBUTED: + String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId, environmentName); + return sendDistrState(user, userRemarks, url); + case DISTRIBUTION_REJECTED: + return rejectDistribution(user, userRemarks, uniqueId); + default: + return null; + + } + +// if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_APPROVED) { +// return sendApproveDistribution(user, uniqueId, userRemarks); +// } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_REJECTED) { +// return rejectDistribution(user, userRemarks, uniqueId); +// } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTED) { +// Config config = Utils.getConfig(); +// // String url = +// // String.format("http://%s:%s/sdc2/rest/v1/catalog/services/%s/tempUrlToBeDeleted", +// // config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); +// String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), +// uniqueId, "PROD"); +// return sendDistrState(user, userRemarks, url); +// } else +// return null; + + } + + public static RestResponse sendApproveDistribution(User sdncModifierDetails, String uniqueId, String userRemarks) + throws FileNotFoundException, IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.APPROVE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId); + return sendDistrState(sdncModifierDetails, userRemarks, url); + } + + public static RestResponse rejectDistribution(ServiceReqDetails serviceDetails, String version, User user, + String userRemarks) throws Exception { + return rejectDistribution(user, userRemarks, serviceDetails.getUniqueId()); + } + + public static RestResponse rejectDistribution(User user, String userRemarks, String uniqueId) + throws FileNotFoundException, IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId); + return sendDistrState(user, userRemarks, url); + } + + private static RestResponse sendDistrState(User user, String userRemarks, String url) throws IOException { + Map headersMap = prepareHeadersMap(user); + Map userRemarksMap = new HashMap(); + userRemarksMap.put("userRemarks", userRemarks); + + String serviceBodyJson = new JSONObject().toJSONString(userRemarksMap); + + HttpRequest httpRequest = new HttpRequest(); + logger.debug(url); + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + logger.debug("Service headers: {}", headersMap); + RestResponse rejectDistributionResponse = httpRequest.httpSendPost(url, serviceBodyJson, headersMap); + + return rejectDistributionResponse; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java new file mode 100644 index 0000000000..93c0d05f87 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java @@ -0,0 +1,196 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; + +import com.google.gson.Gson; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProductRestUtils extends BaseRestUtils { + private static Gson gson = new Gson(); + private static Logger logger = LoggerFactory.getLogger(ProductRestUtils.class.getName()); + + public static RestResponse createProduct(ProductReqDetails product, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort()); + String serviceBodyJson = gson.toJson(product); + + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + product.setVersion(ResponseParser.getVersionFromResponse(res)); + product.setUUID(ResponseParser.getUuidFromResponse(res)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + product.setCreatorUserId(user.getUserId()); + product.setCreatorFullName(user.getFullName()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLastUpdaterUserId(user.getUserId()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + product.setVersion("0.1"); + String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate"); + product.setLastUpdateDate(Long.parseLong(lastUpdate, 10)); + product.setCreationDate(Long.parseLong(lastUpdate, 10)); + } + return res; + } + + public static RestResponse updateProduct(ProductReqDetails product, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), + product.getUniqueId()); + String serviceBodyJson = gson.toJson(product); + + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + product.setVersion(ResponseParser.getVersionFromResponse(res)); + product.setUUID(ResponseParser.getUuidFromResponse(res)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + product.setCreatorUserId(user.getUserId()); + product.setCreatorFullName(user.getFullName()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLastUpdaterUserId(user.getUserId()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(res.getResponse(), "version"); + product.setVersion(valueFromJsonResponse); + String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate"); + product.setLastUpdateDate(Long.parseLong(lastUpdate, 10)); + product.setCreationDate(Long.parseLong(lastUpdate, 10)); + } + return res; + } + + public static RestResponse createProduct_Invalid_Json(String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort()); + + RestResponse res = sendPost(url, "kukumuku", userId, acceptHeaderData); + return res; + } + + public static RestResponse deleteProduct(String id, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), id); + return sendDelete(url, userId); + } + + public static RestResponse getProduct(String productId) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), productId); + logger.debug("Send GET request to get product: {}", url); + + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + public static RestResponse getProduct(String productId, String userId) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), productId); + logger.debug("Send GET request to get product: {}", url); + + return sendGet(url, userId); + } + + public static RestResponse getFollowed(String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send GET request to get user followed page: {}", url); + return sendGet(url, userId); + + } + + public static RestResponse changeProductLifeCycle(Product product, User userModifier, LifeCycleStatesEnum lifeCycle) + throws Exception { + String checkinComment = "my comment"; + RestResponse changeLifeCycleResponse = LifecycleRestUtils.changeProductState(product, userModifier, lifeCycle, + checkinComment); + if (changeLifeCycleResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + product.setLastUpdaterUserId(userModifier.getUserId()); + product.setLastUpdaterFullName(userModifier.getFullName()); + String latestVersion = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "version"); + product.setVersion(latestVersion); + String lifecycleState = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "lifecycleState"); + product.setLifecycleState((LifecycleStateEnum.valueOf(lifecycleState))); + String uniqueId = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "uniqueId"); + product.setUniqueId(uniqueId); + String lastUpdate = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "lastUpdateDate"); + product.setLastUpdateDate((Long.parseLong(lastUpdate, 10))); + String uuid = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), "uuid"); + product.setUUID(uuid); + } + return changeLifeCycleResponse; + } + + public static RestResponse changeServiceInstanceVersion(String componentUniqueId, + String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, + ComponentTypeEnum componentType) throws IOException { + Config config = Utils.getConfig(); + String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}"); + String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId, + serviceInstanceToReplaceUniqueId); + RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(), + acceptHeaderData); + return changeResourceInstanceVersion; + + } + + public static RestResponse getProductByNameAndVersion(String productName, String productVersion, String userId) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_PRODUCT_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), productName, productVersion); + logger.debug("Send GET request to get product by name and version: {}", url); + return sendGet(url, userId); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java new file mode 100644 index 0000000000..b035694407 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java @@ -0,0 +1,310 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.PropertyDefinition; +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.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PropertyRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(PropertyRestUtils.class.getName()); + + public static RestResponse createProperty(String resourceId, String body, User user) throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + + return sendPost(url, body, user.getUserId(), acceptHeaderData); + } + + public static RestResponse updateProperty(String resourceId, String propertyId, String body, User user) + throws Exception { + Config config = Config.instance(); + + String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId, propertyId); + return sendPut(url, body, user.getUserId(), acceptHeaderData); + } + + public static RestResponse getProperty(String resourceId, String propertyId, User user) throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.GET_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, + propertyId); + return sendGet(url, user.getUserId()); + } + + public static RestResponse deleteProperty(String resourceId, String propertyId, User user) throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.DELETE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId, propertyId); + + return sendDelete(url, user.getUserId()); + } + + public static ComponentInstanceProperty getPropFromListByPropNameAndType(List propList, + String propNameToUpdate, String propTypeToUpdate) { + for (ComponentInstanceProperty componentInstanceProperty : propList) { + if (componentInstanceProperty.getName().equals(propNameToUpdate) + && componentInstanceProperty.getType().equals(propTypeToUpdate)) { + return componentInstanceProperty; + } + } + return null; + } + + public static ComponentInstanceProperty getPropFromListByPropNameTypeAndPath( + List propList, String propNameToUpdate, String propTypeToUpdate, + List path) { + for (ComponentInstanceProperty componentInstanceProperty : propList) { + if (componentInstanceProperty.getPath() == null) { + return getPropFromListByPropNameAndType(propList, propNameToUpdate, propTypeToUpdate); + } + if (componentInstanceProperty.getName().equals(propNameToUpdate) + && componentInstanceProperty.getType().equals(propTypeToUpdate) + && path.containsAll(componentInstanceProperty.getPath())) { + return componentInstanceProperty; + } + } + return null; + } + + public static ComponentInstanceProperty getPropFromListByPropIdAndPath(List propList, + String propId, List path) { + + for (ComponentInstanceProperty componentInstanceProperty : propList) { + if (path != null) { + if (componentInstanceProperty.getUniqueId().equals(propId) + && componentInstanceProperty.getPath().equals(path)) { + return componentInstanceProperty; + } + } else { + if (componentInstanceProperty.getUniqueId().equals(propId)) { + return componentInstanceProperty; + } + } + } + return null; + } + + public static void comparePropertyLists(List expectedList, + List actualList, Boolean isUpdate) { + + assertTrue( + "list size are not equals, expected size is: " + expectedList.size() + " ,actual: " + actualList.size(), + expectedList.size() == actualList.size()); + Boolean flag = false; + for (ComponentInstanceProperty expectedcompInstProp : expectedList) { + for (ComponentInstanceProperty actualcompInstProp : actualList) { + flag = comparePropertyObjects(expectedcompInstProp, actualcompInstProp, isUpdate); + if (flag) { + break; + } + } + } + // System.out.println("expected: " + expectedList + ", actual: " + + // actualList); + logger.debug("expected: {}, actual: {}",expectedList,actualList); + assertTrue("actual lists does not contain all uniqeIds", flag); + } + + public static Boolean comparePropertyObjects(ComponentInstanceProperty expectedCompInstProp, + ComponentInstanceProperty actualCompInstProp, Boolean isUpdate) { + String uniqueId = expectedCompInstProp.getUniqueId(); + String type = expectedCompInstProp.getType(); + String defaulValue = expectedCompInstProp.getDefaultValue(); + if (actualCompInstProp.getUniqueId().equals(uniqueId) + && actualCompInstProp.getPath().equals(expectedCompInstProp.getPath())) { + assertTrue("expected type is: " + type + " ,actual: " + actualCompInstProp.getType(), + actualCompInstProp.getType().equals(type)); + if (defaulValue == null) { + assertTrue( + "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getDefaultValue() == defaulValue); + } else { + assertTrue( + "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getDefaultValue().equals(defaulValue)); + } + if (isUpdate) { + assertTrue( + "actual [Value] parameter " + actualCompInstProp.getName() + + "should equal to expected [Value]: " + actualCompInstProp.getValue() + " ,Value: " + + actualCompInstProp.getValue(), + actualCompInstProp.getValue().equals(expectedCompInstProp.getValue())); + assertNotNull("valueId is null", actualCompInstProp.getValueUniqueUid()); + } else { + if (defaulValue == null) { + assertTrue( + "actual [Value] parameter " + actualCompInstProp.getName() + + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue() + + " ,defaultValue: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getValue() == expectedCompInstProp.getDefaultValue()); + } else { + assertTrue( + "actual [Value] parameter " + actualCompInstProp.getName() + + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue() + + " ,defaultValue: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getValue().equals(expectedCompInstProp.getDefaultValue())); + } + assertNull("valueId is not null", actualCompInstProp.getValueUniqueUid()); + } + return true; + } + return false; + } + + public static List addResourcePropertiesToList(Resource resource, + List listToFill) { + for (PropertyDefinition prop : resource.getProperties()) { + listToFill.add(new ComponentInstanceProperty(prop, null, null)); + } + return listToFill; + } + + public static List addComponentInstPropertiesToList(Component component, + List listToFill, String componentId) { + + if (componentId != null) { + List list = component.getComponentInstancesProperties().get(componentId); + for (ComponentInstanceProperty prop : list) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, null); + componentInstanceProperty.setPath(prop.getPath()); + componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid()); + componentInstanceProperty.setValue(prop.getValue()); + listToFill.add(componentInstanceProperty); + } + } else { + Map> componentInstancesProperties = component + .getComponentInstancesProperties(); + for (Map.Entry> componentInstanceProperties : componentInstancesProperties + .entrySet()) { + for (ComponentInstanceProperty prop : componentInstanceProperties.getValue()) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, + null); + componentInstanceProperty.setPath(prop.getPath()); + componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid()); + componentInstanceProperty.setValue(prop.getValue()); + listToFill.add(componentInstanceProperty); + } + } + } + + if (component.getComponentType().getValue().equals("Resource")) { + for (PropertyDefinition prop : ((Resource) component).getProperties()) { + listToFill.add(new ComponentInstanceProperty(prop, null, null)); + } + } + return listToFill; + } + + public static ComponentInstanceProperty getCompPropInstListByInstIdAndPropName(Component component, + ComponentInstance componentInstanceDetails, String name, String type) { + List propList = component.getComponentInstancesProperties() + .get(componentInstanceDetails.getUniqueId()); + if (propList != null) { + return getPropFromListByPropNameAndType(propList, name, type); + } + return null; + } + + private static void updatePropertyListWithPathParameter(Resource resource, List path, + List expectedPropertyList) { + List propertyList = resource.getProperties(); + for (PropertyDefinition propertyDefinition : propertyList) { + ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameAndType( + expectedPropertyList, propertyDefinition.getName(), propertyDefinition.getType()); + ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove; + propDetailsToAdd.setPath(path); + expectedPropertyList.remove(propDetailsToRemove); + expectedPropertyList.add(propDetailsToAdd); + } + } + + private static void updatePropertyListWithPathParameterOnCompInst(Service service, List path, + List expectedPropertyList) { + List servicePropertyList = new ArrayList<>(); + servicePropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, servicePropertyList, + path.get(0)); + + for (ComponentInstanceProperty serviceCompInstProperty : servicePropertyList) { + ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameTypeAndPath( + expectedPropertyList, serviceCompInstProperty.getName(), serviceCompInstProperty.getType(), + serviceCompInstProperty.getPath()); + ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove; + List tempPathList = new ArrayList(); + for (String tempPath : path) { + tempPathList.add(tempPath); + } + // path parameter can not contain the same service unique ID twice + if (propDetailsToAdd.getPath() != null + && !propDetailsToAdd.getPath().get(0).contains(service.getUniqueId())) { + if (!propDetailsToAdd.getPath().containsAll(tempPathList)) { + tempPathList.addAll(propDetailsToAdd.getPath()); + } + } + propDetailsToAdd.setPath(tempPathList); + expectedPropertyList.remove(propDetailsToRemove); + expectedPropertyList.add(propDetailsToAdd); + } + } + + public static void updatePropertyListWithPathOnResource(ComponentInstance componentInstDetails, Resource resource, + List list, Component container) { + List path = new ArrayList<>(); + if (container != null) { + List componentInstances = container.getComponentInstances(); + for (ComponentInstance componentInstance : componentInstances) { + if (componentInstance.getNormalizedName().equals(componentInstDetails.getNormalizedName())) { + path.add(componentInstance.getUniqueId()); + break; + } + } + + } else { + path.add(componentInstDetails.getUniqueId()); + } + updatePropertyListWithPathParameter(resource, path, list); + } + + public static void updatePropertyListWithPathOnComponentInstance(ComponentInstance componentInstDetails, + Service service, List list) { + List path = new ArrayList<>(); + path.add(componentInstDetails.getUniqueId()); + updatePropertyListWithPathParameterOnCompInst(service, path, list); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java new file mode 100644 index 0000000000..e08ef6523f --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java @@ -0,0 +1,679 @@ +/*- + * ============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.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.http.client.ClientProtocolException; +import org.json.JSONException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.RelationshipInstData; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.common.util.GeneralUtility; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResourceRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName()); + + // ****** CREATE ******* + + public static RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) + throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) { + resourceDetails.setUUID(ResponseParser.getUuidFromResponse(createResourceResponse)); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse)); + String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), + "lastUpdaterUserId"); + resourceDetails.setLastUpdaterUserId(lastUpdaterUserId); + String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), + "lastUpdaterFullName"); + resourceDetails.setLastUpdaterFullName(lastUpdaterFullName); + // Creator details never change after component is created - Ella, + // 12/1/2016 + resourceDetails.setCreatorUserId(userId); + resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName()); + } + return createResourceResponse; + + } + + public static RestResponse createImportResource(ImportReqDetails importReqDetails, User sdncModifierDetails, + Map additionalHeaders) throws JSONException, IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + String userId = sdncModifierDetails.getUserId(); + + Gson gson = new Gson(); + String resourceImportBodyJson = gson.toJson(importReqDetails); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(resourceImportBodyJson); + + Map headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } else { + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), + ArtifactRestUtils.calculateMD5(resourceImportBodyJson)); + } + + RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap); + if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) { + importReqDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse)); + importReqDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + importReqDetails.setCreatorUserId(userId); + importReqDetails.setCreatorFullName(sdncModifierDetails.getFullName()); + importReqDetails + .setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse)); + importReqDetails.setDerivedList(ResponseParser.getDerivedListFromJson(createResourceResponse)); + } + return createResourceResponse; + + } + + // ***** DELETE **** + public static RestResponse deleteResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, + String version) throws IOException { + + if (resourceDetails.getUniqueId() != null) { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetails.getName(), version); + return sendDelete(url, sdncModifierDetails.getUserId()); + } else { + return null; + } + + } + + public static RestResponse markResourceToDelete(String resourceId, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + RestResponse sendDelete = sendDelete(url, userId); + + return sendDelete; + + } + + public static RestResponse deleteResource(String resourceId, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + RestResponse sendDelete = sendDelete(url, userId); + + deleteMarkedResources(userId); + + return sendDelete; + + } + + public static void deleteMarkedResources(String userId) throws IOException { + String url; + Config config = Utils.getConfig(); + url = String.format(Urls.DELETE_MARKED_RESOURCES, config.getCatalogBeHost(), config.getCatalogBePort()); + sendDelete(url, userId); + } + + public static RestResponse deleteResourceByNameAndVersion(User sdncModifierDetails, String resourceName, + String resourceVersion) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceName, resourceVersion); + RestResponse sendDelete = sendDelete(url, sdncModifierDetails.getUserId()); + + deleteMarkedResources(sdncModifierDetails.getUserId()); + + return sendDelete; + } + + public static Boolean deleteResourceByNameAndVersion(String resourceName, String resourceVersion) + throws IOException { + RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion( + ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceName, resourceVersion); + return checkErrorCode(deleteResponse); + } + + public static Boolean removeResource(String resourceId) + throws FileNotFoundException, IOException, ClientProtocolException { + RestResponse response = deleteResource(resourceId, + ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId()); + return checkErrorCode(response); + } + + // ************** GET ************* + public static RestResponse getResource(User sdncModifierDetails, String uniqueId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getModule(User sdncModifierDetails, String componentId, String moduleId) + throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_MODULE_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), + componentId, moduleId); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getLatestResourceFromCsarUuid(User sdncModifierDetails, String csarUuid) + throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE_BY_CSAR_UUID, config.getCatalogBeHost(), config.getCatalogBePort(), + csarUuid); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) + throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceDetails.getUniqueId()); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion) + throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceName, resourceVersion); + + return sendGet(url, userId); + } + + public static RestResponse getResourceList(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + + return sendGet(url, sdncModifierDetails.getUserId()); + + } + + public static RestResponse getResourceListFilterByCategory(User sdncModifierDetails, String componentType, String category) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, "category=" + category); + + Map headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + return sendGet(url, sdncModifierDetails.getUserId(), headersMap); + + } + + public static RestResponse getResourceListFilterBySubCategory(User sdncModifierDetails, String componentType, String subcategory) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, "subCategory=" + subcategory); + + Map headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + return sendGet(url, sdncModifierDetails.getUserId(), headersMap); + + } + + public static RestResponse getResourceListFilterByCriteria(User sdncModifierDetails, String componentType, String criteria, String value) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, criteria + "=" + value); + + Map headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + return sendGet(url, sdncModifierDetails.getUserId(), headersMap); + + } + + public static RestResponse getResource(String resourceId) throws ClientProtocolException, IOException { + return getResource(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceId); + } + + public static RestResponse getLatestResourceFromCsarUuid(String csarUuid) + throws ClientProtocolException, IOException { + return getLatestResourceFromCsarUuid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), csarUuid); + } + + public static RestResponse getResourceLatestVersionList(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE_lATEST_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, sdncModifierDetails.getUserId()); + + } + + public static RestResponse putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(String uuid) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid); + HttpRequest http = new HttpRequest(); + + logger.debug("Send PUT request to get all categories (should be 405): {}", url); + return http.httpSendByMethod(url, "PUT", null, headersMap); + } + + public static RestResponse getAllTagsTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_TAGS, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse getAllPropertyScopesTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_PROPERTY_SCOPES_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse getAllArtifactTypesTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map headersMap = new HashMap(); + + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse getConfigurationTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_CONFIGURATION, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse sendOptionsTowardsCatalogFeWithUuid() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + HttpRequest http = new HttpRequest(); + + logger.debug("Send OPTIONS request for categories: {}", url); + return http.httpSendByMethod(url, "OPTIONS", null, headersMap); + } + + // ********** UPDATE ************* + public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails, + User sdncModifierDetails, String uniqueId, String encoding) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId); + + String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(updatedResourceDetails); + String userId = sdncModifierDetails.getUserId(); + + RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString); + + updatedResourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse)); + updatedResourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse)); + + return updateResourceResponse; + } + + public static RestResponse updateResourceTEST(Resource resource, User sdncModifierDetails, String uniqueId, + String encoding) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId); + + String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resource); + String userId = sdncModifierDetails.getUserId(); + + RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString); + + // String resourceUniqueId = + // ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), + // "uniqueId"); + // updatedResourceDetails.setUniqueId(resourceUniqueId); + // String resourceVersion = + // ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), + // "version"); + // updatedResourceDetails.setUniqueId(resourceVersion); + + return updateResourceResponse; + } + + public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails, + User sdncModifierDetails, String uniqueId) throws Exception { + return updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, uniqueId, ""); + } + + public static RestResponse updateResourceMetadata(String json, User sdncModifierDetails, String resourceId) + throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + String userId = sdncModifierDetails.getUserId(); + + RestResponse updateResourceResponse = sendPut(url, json, userId, contentTypeHeaderData); + + return updateResourceResponse; + } + + public static RestResponse updateResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, + String resourceId) throws IOException { + + String userId = sdncModifierDetails.getUserId(); + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + + Map headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); + HttpRequest http = new HttpRequest(); + RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap); + if (updateResourceResponse.getErrorCode() == STATUS_CODE_UPDATE_SUCCESS) { + resourceDetails.setUUID(ResponseParser.getUuidFromResponse(updateResourceResponse)); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse)); + String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), + "lastUpdaterUserId"); + resourceDetails.setLastUpdaterUserId(lastUpdaterUserId); + String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), + "lastUpdaterFullName"); + resourceDetails.setLastUpdaterFullName(lastUpdaterFullName); + resourceDetails.setCreatorUserId(userId); + resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName()); + } + return updateResourceResponse; + } + + public static RestResponse createResourceInstance(ResourceReqDetails resourceDetails, User modifier, + String vfResourceUniqueId) throws Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory + .getComponentResourceInstance(resourceDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance( + resourceInstanceReqDetails, modifier, vfResourceUniqueId, ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + return createResourceInstanceResponse; + } + + public static RestResponse associateResourceInstances(JSONObject body, User sdncModifierDetails, + Component component) throws IOException { + + Config config = Utils.getConfig(); + Gson gson = new Gson(); + String bodyJson = gson.toJson(body); + component.getComponentType(); + String componentType = ComponentTypeEnum.findParamByType(component.getComponentType()); + String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), componentType, component.getUniqueId()); + return sendPost(url, bodyJson, sdncModifierDetails.getUserId(), null); + + } + + public static RestResponse getFollowedList(User sdncModifierDetails) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static List restResponseToResourceObjectList(String restResponse) { + JsonElement jelement = new JsonParser().parse(restResponse); + JsonArray jsonArray = jelement.getAsJsonArray(); + List restResponseArray = new ArrayList<>(); + Resource resource = null; + for (int i = 0; i < jsonArray.size(); i++) { + String resourceString = (String) jsonArray.get(i).toString(); + resource = ResponseParser.convertResourceResponseToJavaObject(resourceString); + restResponseArray.add(resource); + } + + return restResponseArray; + + } + + public static Resource getResourceObjectFromResourceListByUid(List resourceList, String uid) { + if (resourceList != null && resourceList.size() > 0) { + for (Resource resource : resourceList) { + if (resource.getUniqueId().equals(uid)) + return resource; + } + } else + return null; + return null; + } + + // =======================================resource + // associate================================================== + public static RestResponse associate2ResourceInstances(Component container, ComponentInstance fromNode, + ComponentInstance toNode, String assocType, User sdncUserDetails) throws IOException { + return associate2ResourceInstances(container, fromNode.getUniqueId(), toNode.getUniqueId(), assocType, + sdncUserDetails); + } + + public static RestResponse associate2ResourceInstances(Component component, String fromNode, String toNode, + String assocType, User sdncUserDetails) throws IOException { + + RelationshipInstData relationshipInstData = new RelationshipInstData(); + Map> capabilitiesMap = component.getCapabilities(); + Map> requirementMap = component.getRequirements(); + List capabilitiesList = capabilitiesMap.get(assocType); + List requirementList = requirementMap.get(assocType); + + RequirementDefinition requirementDefinitionFrom = getRequirementDefinitionByOwnerId(requirementList, fromNode); + CapabilityDefinition capabilityDefinitionTo = getCapabilityDefinitionByOwnerId(capabilitiesList, toNode); + relationshipInstData.setCapabilityOwnerId(capabilityDefinitionTo.getOwnerId()); + relationshipInstData.setCapabiltyId(capabilityDefinitionTo.getUniqueId()); + relationshipInstData.setRequirementOwnerId(requirementDefinitionFrom.getOwnerId()); + relationshipInstData.setRequirementId(requirementDefinitionFrom.getUniqueId()); + + JSONObject assocBody = assocBuilder(relationshipInstData, capabilityDefinitionTo, requirementDefinitionFrom, + toNode, fromNode); + return ResourceRestUtils.associateResourceInstances(assocBody, sdncUserDetails, component); + + } + + private static JSONObject assocBuilder(RelationshipInstData relationshipInstData, + CapabilityDefinition capabilityDefinitionTo, RequirementDefinition requirementDefinitionFrom, String toNode, + String fromNode) { + + String type = capabilityDefinitionTo.getType(); + String requirement = requirementDefinitionFrom.getName(); + String capability = requirementDefinitionFrom.getName(); + + JSONObject wrapper = new JSONObject(); + JSONArray relationshipsArray = new JSONArray(); + JSONObject relationship = new JSONObject(); + JSONObject simpleObject = new JSONObject(); + + relationship.put("type", type); + simpleObject.put("relationship", relationship); + simpleObject.put("requirement", requirement); + simpleObject.put("capability", capability); + simpleObject.put("capabilityUid", relationshipInstData.getCapabiltyId()); + simpleObject.put("capabilityOwnerId", relationshipInstData.getCapabilityOwnerId()); + simpleObject.put("requirementOwnerId", relationshipInstData.getRequirementOwnerId()); + simpleObject.put("requirementUid", relationshipInstData.getRequirementId()); + relationshipsArray.add(simpleObject); + + ArrayList relationships = new ArrayList(relationshipsArray); + wrapper.put("fromNode", fromNode); + wrapper.put("toNode", toNode); + wrapper.put("relationships", relationships); + return wrapper; + + } + + private static CapabilityDefinition getCapabilityDefinitionByOwnerId( + List capabilityDefinitionList, String ownerId) { + + for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) { + if (capabilityDefinition.getOwnerId().equals(ownerId)) { + return capabilityDefinition; + } + } + return null; + } + + private static RequirementDefinition getRequirementDefinitionByOwnerId( + List requirementDefinitionList, String ownerId) { + + for (RequirementDefinition requirementDefinition : requirementDefinitionList) { + if (requirementDefinition.getOwnerId().equals(ownerId)) { + return requirementDefinition; + } + } + return null; + } + + public static String getRiUniqueIdByRiName(Component component, String resourceInstanceName) { + + List componentInstances = component.getComponentInstances(); + String name = null; + for (ComponentInstance componentInstance : componentInstances) { + if (componentInstance.getName().equals(resourceInstanceName)) { + name = componentInstance.getUniqueId(); + break; + } + } + return name; + } + + public static Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) + throws IOException { + RestResponse response = ResourceRestUtils.getResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue()); + return ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + } + + public static RestResponse changeResourceInstanceVersion(String containerUniqueId, String instanceToReplaceUniqueId, + String newResourceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType) throws IOException { + return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId, + newResourceUniqueId, sdncModifierDetails, componentType); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java new file mode 100644 index 0000000000..10f573cf0e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java @@ -0,0 +1,64 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.util.Map; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.common.util.GeneralUtility; + +import com.google.gson.Gson; + +public class ResourceRestUtilsExternalAPI extends BaseRestUtils { + + public static RestResponse createResource(ResourceExternalReqDetails resourceDetails, User sdncModifierDetails) + throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.POST_EXTERNAL_API_CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + Map headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + HttpRequest http = new HttpRequest(); + RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + + return createResourceResponse; + } + + +} 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 new file mode 100644 index 0000000000..ad9f482bc1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java @@ -0,0 +1,605 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.Version; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.JsonDeserializer; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.module.SimpleModule; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +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.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser; +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.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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class ResponseParser { + + // comment by Andrey, for test only + // public static void main(String[] args) { + // String response = + // "{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"resourceName\":\"importResource4test\",\"resourceVersion\":\"0.1\",\"creatorUserId\":\"jh0003\",\"creatorFullName\":\"Jimmy + // Hendrix\",\"lastUpdaterUserId\":\"jh0003\",\"lastUpdaterFullName\":\"Jimmy + // Hendrix\",\"creationDate\":1446742241514,\"lastUpdateDate\":1446742241514,\"description\":\"Represents + // a generic software component that can be managed and run by a Compute + // Node + // Type.\",\"icon\":\"defaulticon\",\"tags\":[\"importResource4test\"],\"category\":\"Generic/Infrastructure\",\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\",\"derivedFrom\":[\"tosca.nodes.Root\"],\"artifacts\":{},\"deploymentArtifacts\":{},\"properties\":[{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.port\",\"type\":\"integer\",\"required\":false,\"description\":\"the + // port the DBMS service will listen to for data and + // requests\",\"password\":false,\"name\":\"port\",\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"definition\":true},{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.root_password\",\"type\":\"string\",\"required\":false,\"description\":\"the + // optional root password for the DBMS + // service\",\"password\":false,\"name\":\"root_password\",\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"definition\":true}],\"interfaces\":{\"standard\":{\"type\":\"tosca.interfaces.node.lifecycle.Standard\",\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard\",\"operations\":{\"stop\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.stop\",\"description\":\"Standard + // lifecycle stop + // operation.\",\"definition\":false},\"start\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.start\",\"description\":\"Standard + // lifecycle start + // operation.\",\"definition\":false},\"delete\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.delete\",\"description\":\"Standard + // lifecycle delete + // operation.\",\"definition\":false},\"create\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.create\",\"description\":\"Standard + // lifecycle create + // operation.\",\"definition\":false},\"configure\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.configure\",\"description\":\"Standard + // lifecycle configure + // operation.\",\"definition\":false}},\"definition\":false}},\"capabilities\":{\"feature\":{\"uniqueId\":\"capability.8313348e-3623-4f4a-9b8f-d2fbadaf9a31.feature\",\"type\":\"tosca.capabilities.Node\"},\"feature2\":{\"uniqueId\":\"capability.52eb0139-a855-47b9-a0e6-c90f0a90b1d2.feature2\",\"type\":\"tosca.capabilities.Node\"}},\"requirements\":{\"dependency\":{\"uniqueId\":\"8313348e-3623-4f4a-9b8f-d2fbadaf9a31.dependency\",\"capability\":\"tosca.capabilities.Node\",\"node\":\"tosca.nodes.Root\",\"relationship\":\"tosca.relationships.DependsOn\"},\"dependency2\":{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.dependency2\",\"capability\":\"tosca.capabilities.Node\",\"node\":\"tosca.nodes.importResource4test\",\"relationship\":\"tosca.relationships.DependsOn\"}},\"vendorName\":\"ATT + // (Tosca)\",\"vendorRelease\":\"1.0.0.wd03\",\"contactId\":\"jh0003\",\"systemName\":\"Importresource4test\",\"additionalInformation\":[{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.additionalinformation\",\"lastCreatedCounter\":0,\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"parameters\":[]}],\"allVersions\":{\"0.1\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\"},\"abstract\":false,\"highestVersion\":true,\"uuid\":\"2e91a2df-b066-49bb-abde-4c1c01e409db\"}"; + // convertResourceResponseToJavaObject(response); + // } + + private static final String INVARIANT_UUID = "invariantUUID"; + public static final String UNIQUE_ID = "uniqueId"; + public static final String VERSION = "version"; + public static final String UUID = "uuid"; + public static final String NAME = "name"; + public static final String ORIGIN_TYPE = "originType"; + public static final String TOSCA_RESOURCE_NAME = "toscaResourceName"; + + static Logger logger = Logger.getLogger(ResponseParser.class.getName()); + + public static String getValueFromJsonResponse(String response, String fieldName) { + try { + JSONObject jsonResp = (JSONObject) JSONValue.parse(response); + Object fieldValue = jsonResp.get(fieldName); + return fieldValue.toString(); + + } catch (Exception e) { + return null; + } + + } + + public static String getUniqueIdFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID); + } + + public static String getInvariantUuid(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID); + } + + public static String getUuidFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), UUID); + } + + public static String getNameFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), NAME); + } + + public static String getVersionFromResponse(RestResponse response) { + return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION); + } + + public static String getComponentTypeFromResponse(RestResponse response) { + return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE); + } + + public static String getToscaResourceNameFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME); + } + + @SuppressWarnings("unchecked") + public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse, + String resourceType, String searchPattern, String expectedResult) throws Exception { + + // Gson gson = new Gson; + + JsonElement jElement = new JsonParser().parse(restResponse.getResponse()); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType); + Gson gson = new Gson(); + Map map = new HashMap(); + ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject(); + + for (int counter = 0; counter < arrayOfObjects.size(); counter++) { + JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter); + + map = (Map) gson.fromJson(jHitObject.toString(), map.getClass()); + if (map.get(searchPattern).toString().contains(expectedResult)) { + + jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class); + break; + } + } + return jsonToJavaObject; + + } + + public static Resource convertResourceResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer deserializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, deserializer); + + mapper.registerModule(module); + Resource resource = null; + try { +// TODO Andrey L. uncomment line below in case to ignore on unknown properties, not recommended +// mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + resource = mapper.readValue(response, Resource.class); + + logger.debug(resource.toString()); + } catch (IOException e) { + try { + List resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class)); + resource = resources.get(0); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + return resource; + } + + public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + ComponentInstanceProperty propertyDefinition = null; + try { + propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class); + logger.debug(propertyDefinition.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return propertyDefinition; + } + + public static String toJson(Object object) { + Gson gson = new Gson(); + return gson.toJson(object); + } + + public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) { + ObjectMapper mapper = new ObjectMapper(); + ArtifactDefinition artifactDefinition = null; + try { + + artifactDefinition = mapper.readValue(response, ArtifactDefinition.class); + logger.debug(artifactDefinition.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return artifactDefinition; + + } + + public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) { + + ArtifactReqDetails artifactReqDetails = null; + Gson gson = new Gson(); + artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class); + return artifactReqDetails; + } + + public static T parseToObject(String json, Class clazz) { + Gson gson = new Gson(); + T object; + try { + object = gson.fromJson(json, clazz); + } catch (Exception e) { + object = parseToObjectUsingMapper(json, clazz); + } + return object; + } + + public static T parseToObjectUsingMapper(String json, Class clazz) { + // Generic convert + ObjectMapper mapper = new ObjectMapper(); + T object = null; + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + mapper.registerModule(module); + try { + object = mapper.readValue(json, clazz); + // System.out.println("Class: "+clazz.getSimpleName()+", json: + // "+json); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return object; + } + + public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject( + ArtifactDefinition artifactDefinition) { + + ArtifactReqDetails artifactReqDetails = null; + Gson gson = new Gson(); + String artDef = gson.toJson(artifactDefinition); + artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class); + return artifactReqDetails; + } + + public static void addDeserializer(SimpleModule module, Class clazz, + final JsonDeserializer deserializer) { + module.addDeserializer(clazz, deserializer); + } + + public static Service convertServiceResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer deserializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, deserializer); + + mapper.registerModule(module); + Service service = null; + try { + service = mapper.readValue(response, Service.class); + logger.debug(service.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return service; + } + + public static Product convertProductResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + + Product product = null; + try { + product = mapper.readValue(response, Product.class); + logger.debug(product.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return product; + } + + public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + ComponentInstance componentInstance = null; + try { + componentInstance = mapper.readValue(response, ComponentInstance.class); + logger.debug(componentInstance.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return componentInstance; + } + + public static List getValuesFromJsonArray(RestResponse message) throws Exception { + List artifactTypesArrayFromApi = new ArrayList(); + + org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse()); + JSONArray jArr = responseObject.getJSONArray("artifactTypes"); + + for (int i = 0; i < jArr.length(); i++) { + org.json.JSONObject jObj = jArr.getJSONObject(i); + String value = jObj.get("name").toString(); + + artifactTypesArrayFromApi.add(value); + } + return artifactTypesArrayFromApi; + } + + public static String calculateMD5Header(ArtifactReqDetails artifactDetails) { + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // calculate MD5 for json body + return calculateMD5(jsonBody); + + } + + public static String calculateMD5(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + String encodeBase64Str = new String(encodeBase64); + return encodeBase64Str; + + } + + public static List> getAuditFromMessage(Map auditingMessage) { + List> auditList = new ArrayList>(); + // JsonElement jElement = new JsonParser().parse(auditingMessage); + // JsonObject jObject = jElement.getAsJsonObject(); + // JsonObject hitsObject = (JsonObject) jObject.get("hits"); + // JsonArray hitsArray = (JsonArray) hitsObject.get("hits"); + // + // Iterator hitsIterator = hitsArray.iterator(); + // while(hitsIterator.hasNext()) + // { + // JsonElement nextHit = hitsIterator.next(); + // JsonObject jHitObject = nextHit.getAsJsonObject(); + // JsonObject jSourceObject = (JsonObject) jHitObject.get("_source"); + // + // Gson gson=new Gson(); + // String auditUnparsed = jSourceObject.toString(); + // + // Map map = new HashMap(); + // map = (Map) gson.fromJson(auditUnparsed, + // map.getClass()); + + auditList.add(auditingMessage); + // } + return auditList; + } + + public static List parseCategories(RestResponse getAllCategoriesRest) { + + List categories = new ArrayList<>(); + try { + JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse()); + JsonArray cagegories = jElement.getAsJsonArray(); + Iterator iter = cagegories.iterator(); + while (iter.hasNext()) { + JsonElement next = iter.next(); + CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class); + categories.add(category); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return categories; + } + + public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException { + String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field); + JSONArray jArr = new JSONArray(valueFromJsonResponse); + + return jArr; + } + + public static List getDerivedListFromJson(RestResponse res) throws JSONException { + JSONArray listFromJson = getListFromJson(res, "derivedList"); + List lst = new ArrayList(); + for (int i = 0; i < listFromJson.length(); i++) { + lst.add(listFromJson.getString(i)); + } + + return lst; + } + + public static Map convertStringToMap(String obj) { + Map object = (Map) JSONValue.parse(obj); + return object; + } + + public static List> getListOfMapsFromJson(RestResponse res, String field) throws Exception { + List> list = new ArrayList>(); + JSONArray listFromJson = getListFromJson(res, field); + for (int i = 0; i < listFromJson.length(); i++) { + Map convertStringToMap = convertStringToMap(listFromJson.getString(i)); + list.add(convertStringToMap); + } + return list; + + } + + public static Map getJsonValueAsMap(RestResponse response, String key) { + String valueField = getValueFromJsonResponse(response.getResponse(), key); + Map convertToMap = convertStringToMap(valueField); + return convertToMap; + } + + public static String getJsonObjectValueByKey(String metadata, String key) { + JsonElement jelement = new JsonParser().parse(metadata); + + JsonObject jobject = jelement.getAsJsonObject(); + Object obj = jobject.get(key); + if (obj == null) { + return null; + } else { + return obj.toString(); + } + } + + public static Map> convertCatalogResponseToJavaObject(String response) { + + // Map> map = new HashMap>(); + Map> map = new HashMap>(); + + JsonElement jElement = new JsonParser().parse(response); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray jArrReousrces = jObject.getAsJsonArray("resources"); + JsonArray jArrServices = jObject.getAsJsonArray("services"); + JsonArray jArrProducts = jObject.getAsJsonArray("products"); + + if (jArrReousrces != null && jArrServices != null && jArrProducts != null){ + + + //////// RESOURCE///////////////////////////// + ArrayList restResponseArray = new ArrayList<>(); + Component component = null; + for (int i = 0; i < jArrReousrces.size(); i++) { + String resourceString = (String) jArrReousrces.get(i).toString(); + component = ResponseParser.convertResourceResponseToJavaObject(resourceString); + restResponseArray.add(component); + } + + map.put("resources", restResponseArray); + + ///////// SERVICE///////////////////////////// + + restResponseArray = new ArrayList<>(); + component = null; + for (int i = 0; i < jArrServices.size(); i++) { + String resourceString = (String) jArrServices.get(i).toString(); + component = ResponseParser.convertServiceResponseToJavaObject(resourceString); + restResponseArray.add(component); + } + + map.put("services", restResponseArray); + + ///////// PRODUCT///////////////////////////// + restResponseArray = new ArrayList<>(); + component = null; + for (int i = 0; i < jArrProducts.size(); i++) { + String resourceString = (String) jArrProducts.get(i).toString(); + component = ResponseParser.convertProductResponseToJavaObject(resourceString); + restResponseArray.add(component); + } + + map.put("products", restResponseArray); + + } + else { + map.put("resources", new ArrayList<>()); + map.put("services", new ArrayList<>()); + map.put("products", new ArrayList<>()); + } + + return map; + + } + + + public static Map convertServiceDistributionStatusToObject(String response) throws ParseException { + + Map serviceDistributionStatusMap = new HashMap(); + ServiceDistributionStatus serviceDistributionStatusObject = null; + + JsonElement jElement = new JsonParser().parse(response); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList"); + + for (int i = 0; i < jDistrStatusArray.size(); i++){ + Gson gson = new Gson(); + String servDistrStatus = gson.toJson(jDistrStatusArray.get(i)); + serviceDistributionStatusObject = gson.fromJson(servDistrStatus, ServiceDistributionStatus.class); + serviceDistributionStatusMap.put(Utils.getEpochTimeFromUTC(serviceDistributionStatusObject.getTimestamp()), serviceDistributionStatusObject); + } + + return serviceDistributionStatusMap; + + } + + public static Map getPropertiesNameType(RestResponse restResponse) + throws JSONException { + Map propertiesMap = new HashMap(); + JSONArray propertiesList = getListFromJson(restResponse, "properties"); + for (int i = 0; i < propertiesList.length() ; i ++){ + JSONObject prop = (JSONObject) JSONValue.parse(propertiesList.get(i).toString()); + String propName = prop.get("name").toString(); + String propType = prop.get("type").toString(); + propertiesMap.put(propName, propType); + } + + return propertiesMap; + } + + public static ResourceAssetStructure getDataOutOfSearchExternalAPIResponseForResourceName(String response, String resourceName) { + Gson gson = new Gson(); + JsonElement jsonElement = new JsonParser().parse(response); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + for(JsonElement jElement: jsonArray) { + ResourceAssetStructure parsedResponse = gson.fromJson(jElement, ResourceAssetStructure.class); + + if(resourceName.contains(parsedResponse.getName()) && parsedResponse.getName().contains(resourceName)) { + return parsedResponse; + } + } + + return null; + } +} 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 new file mode 100644 index 0000000000..a93587dbbc --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java @@ -0,0 +1,296 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class ServiceRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(ServiceRestUtils.class.getName()); + private final static String cacheControl = "no-cache"; + private final static String contentTypeHeaderData = "application/json"; + private final static String acceptHeaderDate = "application/json"; + // ****** CREATE ******* + + private static Gson gson = new Gson(); + + public static RestResponse deleteService(String serviceName, String version, User sdncModifierDetails) + throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceName, version); + + String userId = sdncModifierDetails.getUserId(); + RestResponse sendDelete = sendDelete(url, userId); + deleteMarkedServices(userId); + return sendDelete; + } + + public static RestResponse markServiceToDelete(String resourceId, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + RestResponse sendDelete = sendDelete(url, userId); + + return sendDelete; + + } + + public static RestResponse deleteServiceById(String serviceId, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), + serviceId); + RestResponse sendDelete = sendDelete(url, userId); + deleteMarkedServices(userId); + return sendDelete; + } + + public static void deleteMarkedServices(String userId) throws IOException { + String url; + Config config = Utils.getConfig(); + url = String.format(Urls.DELETE_MARKED_SERVICES, config.getCatalogBeHost(), config.getCatalogBePort()); + sendDelete(url, userId); + } + + 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); + + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + service.setVersion(ResponseParser.getVersionFromResponse(res)); + service.setUUID(ResponseParser.getUuidFromResponse(res)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFullName()); + } + + return res; + } + + public static RestResponse updateService(ServiceReqDetails service, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_SERVICE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + service.getUniqueId()); + String serviceBodyJson = gson.toJson(service); + + logger.debug("Send PUT request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + service.setVersion(ResponseParser.getVersionFromResponse(res)); + } + + return res; + } + + public static RestResponse getService(String serviceId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + return getServiceFromUrl(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), false); + } + + public static RestResponse getService(ServiceReqDetails serviceReqDetails, User sdncModifierDetails) + throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), + serviceReqDetails.getUniqueId()); + return getServiceFromUrl(url, sdncModifierDetails, false); + } + + public static RestResponse getService(String serviceId, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + return getServiceFromUrl(url, sdncModifierDetails, false); + } + + public static RestResponse getServiceByNameAndVersion(User sdncModifierDetails, String serviceName, + String serviceVersion) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceName, serviceVersion); + return getServiceFromUrl(url, sdncModifierDetails, false); + } + + public static RestResponse getServiceFromUrl(String url, User sdncModifierDetails, boolean isCached) + throws IOException { + Map headersMap = prepareHeadersMap(sdncModifierDetails, isCached); + HttpRequest http = new HttpRequest(); + logger.debug("Send GET request to create service: {}", url); + logger.debug("Service headers: {}", headersMap); + RestResponse sendGetServerRequest = http.httpSendGet(url, headersMap); + + return sendGetServerRequest; + } + + public static Map prepareHeadersMap(User sdncModifierDetails, boolean isCached) { + Map headersMap = new HashMap(); + if (isCached) + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), cacheControl); + + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + return headersMap; + } + + public static RestResponse approveServiceDistribution(String serviceId, String userId) throws Exception { + return changeServiceDistributionState(serviceId, userId, Urls.APPROVE_DISTRIBUTION); + } + + public static RestResponse rejectServiceDistribution(String serviceId, String userId) throws Exception { + return changeServiceDistributionState(serviceId, userId, Urls.REJECT_DISTRIBUTION); + } + + // Benny + public static RestResponse rejectServiceDistribution(String serviceId, String userId, String comment) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + serviceId); + String userBodyJson = gson.toJson(comment); + return sendPost(url, userBodyJson, userId, acceptHeaderData); + + } + + private static RestResponse changeServiceDistributionState(String serviceId, String userId, String distributionUrl) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(distributionUrl, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + String defComment = "{ userRemarks : \"this is an test\" }"; + String userBodyJson = gson.toJson(defComment); + return sendPost(url, userBodyJson, userId, acceptHeaderData); + + } + + public static RestResponse getServiceLatestVersionList(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE_lATEST_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, sdncModifierDetails.getUserId()); + + } + + public static RestResponse createServiceByHttpMethod(ServiceReqDetails serviceDetails, User sdncModifierDetails, + String method, String urls) throws IOException { + Map headersMap = prepareHeadersMap(sdncModifierDetails, true); + + Config config = Utils.getConfig(); + String serviceBodyJson = gson.toJson(serviceDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(urls, config.getCatalogBeHost(), config.getCatalogBePort()); + // TODO: ADD AUTHENTICATION IN REQUEST + logger.debug(url); + logger.debug("Send {} request to create user: {}",method,url); + logger.debug("User body: {}", serviceBodyJson); + logger.debug("User headers: {}", headersMap); + RestResponse sendCreateUserRequest = http.httpSendByMethod(url, method, serviceBodyJson, headersMap); + + return sendCreateUserRequest; + + } + + public static RestResponse deleteServiceByNameAndVersion(User sdncModifierDetails, String serviceName, + String serviceVersion) throws IOException { + Config config = Utils.getConfig(); + + Map headersMap = prepareHeadersMap(sdncModifierDetails, true); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceName, serviceVersion); + RestResponse deleteResponse = http.httpSendDelete(url, headersMap); + + return deleteResponse; + } + + public static RestResponse getFollowed(User user) throws Exception { + Config config = Utils.getConfig(); + + HttpRequest httpRequest = new HttpRequest(); + + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap); + + return getResourceNotAbstarctResponse; + } + + public static JSONArray getListArrayFromRestResponse(RestResponse restResponse) { + String json = restResponse.getResponse(); + JSONObject jsonResp = (JSONObject) JSONValue.parse(json); + JSONArray servicesArray = (JSONArray) jsonResp.get("services"); + + logger.debug("services= {}", servicesArray); + + return servicesArray; + } + + public static RestResponse getDistributionServiceList(Service service, User user) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DISTRIBUTION_SERVICE_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), service.getUUID()); + return getServiceFromUrl(url, user, false); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java new file mode 100644 index 0000000000..881e9469dd --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java @@ -0,0 +1,299 @@ +/*- + * ============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.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +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; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class UserRestUtils extends BaseRestUtils { + + static Gson gson = new Gson(); + + static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName()); + static String contentTypeHeaderData = "application/json"; + static String acceptHeaderDate = "application/json"; + + public UserRestUtils() { + super(); + + StartTest.enableLogger(); + } + + public static RestResponse createUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + String userBodyJson = gson.toJson(sdncUserDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + + logger.debug("Send POST request to create user: {}", url); + logger.debug("User body: {}", userBodyJson); + logger.debug("User headers: {}", headersMap); + RestResponse sendCreateUserRequest = http.httpSendPost(url, userBodyJson, headersMap); + + return sendCreateUserRequest; + + } + + public static RestResponse deactivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + return deleteUser(sdncUserDetails, sdncModifierDetails, true); + } + + public static RestResponse deActivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + return deleteUser(sdncUserDetails, sdncModifierDetails, false); + } + + public static RestResponse deleteUser(User sdncUserDetails, User sdncModifierDetails, boolean isForceDelete) + throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + if (isForceDelete) { + headersMap.put(User.FORCE_DELETE_HEADER_FLAG, User.FORCE_DELETE_HEADER_FLAG); + } + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.DELETE_USER, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncUserDetails.getUserId()); + RestResponse sendDeleteUserRequest = http.httpSendDelete(url, headersMap); + return sendDeleteUserRequest; + + } + + public static RestResponse updateUser(User sdncUserDetails, User sdncModifierDetails) + throws IOException, CloneNotSupportedException { + + Config config = Utils.getConfig(); + User user = new User(sdncModifierDetails); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + user.setUserId(StringUtils.EMPTY); + user.setRole(StringUtils.EMPTY); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(user); + logger.debug("userBodyJson: {}", userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_USER, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncModifierDetails.getUserId()); + RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap); + + return sendUpdateUserRequest; + } + + /// Benny + public static RestResponse updateUserRole(User sdncUserDetails, User sdncModifierDetails, String userIdToUpdate) + throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(sdncUserDetails); + logger.debug("userBodyJson: {}", userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_USER_ROLE, config.getCatalogBeHost(), config.getCatalogBePort(), + userIdToUpdate); + RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap); + + return sendUpdateUserRequest; + + } + + public static RestResponse getUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncUserDetails.getUserId()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + + } + + public static RestResponse getUserRole(User sdncUserDetails, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_USER_ROLE, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncUserDetails.getUserId()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + + } + + + + public static RestResponse getAllAdminUsers(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + // Gson gson = new Gson(); + // String userBodyJson = gson.toJson(sdncModifierDetails); + // System.out.println(userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_ADMIN_USERS, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send following url: {} and headers: {}",url, headersMap.toString()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + + return sendGetUserRequest; + + } + + // US571255 + public static RestResponse getUsersByRoles(User sdncModifierDetails, String roles) throws IOException { + + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + HttpRequest http = new HttpRequest(); + String url; + if (roles == "/") { + url = String.format(Urls.GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort()); + } else { + url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), roles); + + } + logger.debug("Send following url: {} and headers: {}",url, headersMap.toString()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + } + + public static RestResponse getUsersByRolesHttpCspAtuUidIsMissing(User sdncModifierDetails, String roles) + throws Exception { + + Config config = Utils.getConfig(); + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + headersMap.remove("USER_ID"); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), + roles); + logger.debug( + "Send following url without USER_ID header : " + url + " headers: " + headersMap.toString()); + + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + } + + public static RestResponse authorizedUserTowardsCatalogBe(User sdncUserDetails) throws IOException { + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (sdncUserDetails.getFirstName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName()); + } + if (sdncUserDetails.getLastName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName()); + } + if (sdncUserDetails.getEmail() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail()); + } + + logger.debug("headersMap: {}", headersMap.toString()); + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send GET request to login as seal user : {}", url); + return http.httpSendGet(url, headersMap); + } + + public static RestResponse authorizedUserTowardsCatalogBeQA(User sdncUserDetails) throws IOException { + + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (sdncUserDetails.getFirstName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName()); + } + if (sdncUserDetails.getLastName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName()); + } + if (sdncUserDetails.getEmail() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail()); + } + + logger.debug("headersMap: {}", headersMap.toString()); + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send GET request to login as seal user : {}", url); + return http.httpSendGet(url, headersMap); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java new file mode 100644 index 0000000000..b211cb723b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java @@ -0,0 +1,226 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.JsonProcessingException; +import org.codehaus.jackson.map.ObjectMapper; +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.resources.data.ESArtifactData; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Decoder; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.FileUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class ArtifactValidationUtils { + + private static String desc = "description"; + private static String artifactType = "artifactType"; + private static String artifactName = "artifactName"; + private static String artifactChecksum = "artifactChecksum"; + private static String uniqueId = "uniqueId"; + protected Utils utils; + + public static void validateInformationalArtifact(ArtifactReqDetails expectedArtifact, + Map actualArtifact) { + assertTrue("description is not as expected", + expectedArtifact.getDescription().equals(actualArtifact.get(desc).toString())); + assertTrue("artifactType is not as expected", + expectedArtifact.getArtifactType().toUpperCase().equals(actualArtifact.get(artifactType).toString())); + assertTrue("artifactName is not as expected", + expectedArtifact.getArtifactName().equals(actualArtifact.get(artifactName).toString())); + assertTrue("uniqueId is not as expected", + expectedArtifact.getUniqueId().equals(actualArtifact.get(uniqueId).toString())); + assertTrue("description is not as expected", expectedArtifact.getArtifactLabel().toLowerCase() + .equals(actualArtifact.get("artifactLabel").toString())); + } + + public static void validateArtifactsNumberInComponent(Component component, ArtifactGroupTypeEnum artifactGroupType, + ArtifactTypeEnum artifactType, int expectedNumber) { + Map deploymentArtifacts; + int counter = 0; + if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + deploymentArtifacts = component.getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getArtifacts(); + } + if (deploymentArtifacts != null) { + for (ArtifactDefinition artifactDefinition : deploymentArtifacts.values()) { + if (artifactDefinition.getArtifactType().equals(artifactType.getType())) { + counter++; + } + } + } + assertEquals("Unexpected number of " + artifactGroupType.getType() + " artifacts in component", expectedNumber, + counter); + } + + // Benny + public static void validateArtifactsNumberInComponentInstance(ComponentInstance componentInstance, + ArtifactGroupTypeEnum artifactGroupType, ArtifactTypeEnum artifactType, int expectedNumber) { + Map deploymentArtifacts = null; + int counter = 0; + if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + deploymentArtifacts = componentInstance.getDeploymentArtifacts(); + } + if (deploymentArtifacts != null) { + for (ArtifactDefinition artifactDefinition : deploymentArtifacts.values()) { + if (artifactDefinition.getArtifactType().equals(artifactType.getType())) { + counter++; + } + } + } + assertEquals("Unexpected number of " + artifactGroupType.getType() + " artifacts in component", expectedNumber, + counter); + } + + public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse) + throws JsonParseException, JsonProcessingException, Exception { + String bodyToParse = resResponse.getResponse(); + JsonElement jElement = new JsonParser().parse(bodyToParse); + JsonElement jsourceElement = jElement.getAsJsonObject().get("_source"); + + ObjectMapper mapper = new ObjectMapper(); + ESArtifactData esArtifactObject = mapper.readValue(jsourceElement.toString(), ESArtifactData.class); + + return esArtifactObject; + + } + + public static void validateArtifactReqVsResp(ArtifactReqDetails expectedArtifactDetails, + ArtifactDefinition actualArtifactJavaObject) { + String expected; + + expected = expectedArtifactDetails.getArtifactName(); + if (expected == null) + expected = ""; + assertEquals("artifact name is not correct ", expected, actualArtifactJavaObject.getArtifactName()); + + expected = expectedArtifactDetails.getArtifactType(); + if (expected == null) + expected = ""; + assertEquals("artifact type is not correct ", expected, actualArtifactJavaObject.getArtifactType()); + + expected = expectedArtifactDetails.getDescription(); + if (expected == null) + expected = ""; + assertEquals("artifact description is not correct ", expected, actualArtifactJavaObject.getDescription()); + + expected = expectedArtifactDetails.getArtifactLabel(); + if (expected == null || expected == "") { + expected = expectedArtifactDetails.getArtifactName().toLowerCase().substring(0, + expectedArtifactDetails.getArtifactName().lastIndexOf(".")); + // expected = tmp.substring(0, + // artifactInfo.getArtifactName().lastIndexOf(".")); + } + assertEquals("artifact label is not correct ", expected, actualArtifactJavaObject.getArtifactLabel()); + + expected = expectedArtifactDetails.getUrl(); + if (expected != "") { + assertEquals(expected, actualArtifactJavaObject.getApiUrl()); + assertEquals(expectedArtifactDetails.getArtifactDisplayName(), + actualArtifactJavaObject.getArtifactDisplayName()); + } + + // assertEquals(validChecksum, + // actualArtifactJavaObject.getArtifactChecksum()); + + // expected = expectedArtifactDetails.getArtifactDisplayName(); + // if (expected != "") + // { + // assertEquals(expected, + // actualArtifactJavaObject.getArtifactDisplayName()); + // } + + boolean actual = actualArtifactJavaObject.getMandatory(); + assertEquals(expectedArtifactDetails.isMandatory(), actual); + + if (actualArtifactJavaObject.getServiceApi()) { + + boolean actual2 = actualArtifactJavaObject.getServiceApi(); + assertEquals(expectedArtifactDetails.isServiceApi(), actual2); + } + + } + + public static void validateEsArtifactReqVsResp(ArtifactReqDetails expectedArtifactInfo, + ESArtifactData esArtifactData) throws Exception { + String expectedArtifactUid = expectedArtifactInfo.getUniqueId(); + if (expectedArtifactUid == null) + expectedArtifactUid = ""; + assertEquals("artifact name is not correct ", expectedArtifactUid, esArtifactData.getId()); + + String actualPayload = Decoder.encode(esArtifactData.getData().array()); + assertEquals("artifact payloadData is not correct ", expectedArtifactInfo.getPayload(), actualPayload); + } + + public static List getListOfArtifactFromFolder(String folderName) throws IOException, Exception { + Config config = Utils.getConfig(); + String sourceDir = config.getResourceConfigDir(); + String testResourcesPath = sourceDir + File.separator + folderName; + List listofFiles = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + return listofFiles; + } + + public static ArtifactReqDetails replaceDefaultArtWithArtFromList_(ArtifactReqDetails heatArtifactDetails, + String heatExtension, String folderName, int positionInlist) throws IOException, Exception { + + Config config = Utils.getConfig(); + String ext = heatExtension; + String sourceDir = config.getResourceConfigDir(); + String testResourcesPath = sourceDir + File.separator + folderName; + List listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath); + String payload = FileUtils.loadPayloadFile(listFileName, ext, true); + heatArtifactDetails.setPayload(payload); + heatArtifactDetails.setArtifactName(listFileName.get(positionInlist) + "." + ext); + return heatArtifactDetails; + } + + public static ArtifactReqDetails replaceDefaultArtWithArtFromList(ArtifactReqDetails heatArtifactDetails, + String heatExtension, String folderName, int positionInlist) throws IOException, Exception { + List listOfArtifactFromFolder = getListOfArtifactFromFolder(folderName); + String payload = FileUtils.loadPayloadFileFromListUsingPosition(listOfArtifactFromFolder, heatExtension, true, + positionInlist); + heatArtifactDetails.setPayload(payload); + heatArtifactDetails.setArtifactName(heatArtifactDetails.getArtifactType() + + listOfArtifactFromFolder.get(positionInlist) + "." + heatExtension); + return heatArtifactDetails; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java new file mode 100644 index 0000000000..7a5b7bb546 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java @@ -0,0 +1,1418 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.javatuples.Pair; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.AuditEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.AuditJsonKeysEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ComponentType; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedDistDownloadAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedEcomConsumerAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedGetUserListAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.ArtifactUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils.CategoryAuditJsonKeysEnum; +import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils.EcompConsumerAuditJsonKeysEnum; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.Row; + +public class AuditValidationUtils { + protected static Logger logger = Logger.getLogger(AuditValidationUtils.class.getName()); + private static final String auditKeySpaceName = "sdcaudit"; + + public AuditValidationUtils() { + super(); + + StartTest.enableLogger(); + logger = Logger.getLogger(AuditValidationUtils.class.getName()); + + } + + public static String buildAuditDescription(ErrorInfo errorInfo, List variables) { + + String auditDesc = errorInfo.getMessageId() + ": " + errorInfo.getMessage(); + if(! variables.isEmpty() && variables.get(0) != null && ! variables.get(0).isEmpty()){ + for (int i = 0; i < variables.size(); i++) { + if (auditDesc.contains("%" + (i + 1))) { + auditDesc = auditDesc.replace("%" + (i + 1), variables.get(i)); + } + } + } + return auditDesc; + } + + public static String getModifierString(String userName, String uid) { + + if (userName.isEmpty() && uid.isEmpty()) + return "(UNKNOWN)"; + + StringBuilder sb = new StringBuilder(); + sb.append(userName).append("(").append(uid).append(")"); + return sb.toString(); + + } + + public static void validateAuditDownloadExternalAPI(ExpectedResourceAuditJavaObject resourceAuditJavaObject, + String action, String body, boolean checkAllFields) throws Exception { + Map actualAuditRecords = new HashMap(); + // Andrey's comment + // actualAuditRecords = parseAuditResourceByAction(action, body); + actualAuditRecords = parseAuditResourceByAction(action, null); + + // List> actualAuditRecords = new + // ArrayList>(); + // actualAuditRecords = parseAuditResourceByActionToList(action, body); + + validateField(actualAuditRecords, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + + validateField(actualAuditRecords, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + resourceAuditJavaObject.getStatus()); + validateField(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), + resourceAuditJavaObject.getDesc()); + + // validateField(actualAuditRecords, + // AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), + // resourceAuditJavaObject.getCONSUMER_ID()); + // validateField(actualAuditRecords, + // AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), + // resourceAuditJavaObject.getRESOURCE_URL()); + + } + + public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action, + String body, boolean checkAllFields) throws Exception { + Map actualAuditRecords = new HashMap(); + // Andrey's comment + // actualAuditRecords = parseAuditResourceByAction(action, body); + actualAuditRecords = parseAuditResourceByAction(action, null); + + if ((resourceAuditJavaObject.getModifierName() != null) && (resourceAuditJavaObject.getModifierUid() != null)) { + resourceAuditJavaObject.setModifierUid(getModifierString(resourceAuditJavaObject.getModifierName(), + resourceAuditJavaObject.getModifierUid())); + } + + validateField(actualAuditRecords, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getPrevVersion()); + validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + + validateField(actualAuditRecords, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), + resourceAuditJavaObject.getModifierUid()); + validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), + resourceAuditJavaObject.getPrevState()); + validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrState()); + validateField(actualAuditRecords, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + resourceAuditJavaObject.getStatus()); + // validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + // Double.parseDouble(resourceAuditJavaObject.getStatus())); + validateField(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), + resourceAuditJavaObject.getDesc()); + validateField(actualAuditRecords, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), + resourceAuditJavaObject.getComment()); + // validateField(map2, + // AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(), + // resourceAuditJavaObject.getArtifactData()); + validateField(actualAuditRecords, AuditJsonKeysEnum.TOSCA_NODE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getToscaNodeType()); + validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_ARTIFACT_UUID.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrArtifactUuid()); + validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_ARTIFACT_UUID.getAuditJsonKeyName(), + resourceAuditJavaObject.getPrevArtifactUuid()); + + validateAtifactDataField(actualAuditRecords, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(), + resourceAuditJavaObject.getArtifactData(), checkAllFields); + } + + public static void validateExternalAudit(ExpectedExternalAudit externalAuditObject, String action, + Map body) throws Exception { + + Map actualAuditRecord = new HashMap(); + actualAuditRecord = parseAuditResourceByAction(action, body); + + validateField(actualAuditRecord, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), + externalAuditObject.getCONSUMER_ID()); + // TODO + validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), + externalAuditObject.getRESOURCE_URL()); + //TODO + validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + externalAuditObject.getRESOURCE_NAME()); + validateField(actualAuditRecord, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(), + externalAuditObject.getSERVICE_INSTANCE_ID()); + //TODO + validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + externalAuditObject.getRESOURCE_TYPE()); + validateField(actualAuditRecord, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + externalAuditObject.getSTATUS()); + validateField(actualAuditRecord, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), + externalAuditObject.getDESC()); + //TODO +// validateField(actualAuditRecord, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), +// externalAuditObject.getMODIFIER()); + validateField(actualAuditRecord, AuditJsonKeysEnum.PREV_ARTIFACT_UUID.getAuditJsonKeyName(), + externalAuditObject.getPREV_ARTIFACT_UUID()); + validateField(actualAuditRecord, AuditJsonKeysEnum.CURR_ARTIFACT_UUID.getAuditJsonKeyName(), + externalAuditObject.getCURR_ARTIFACT_UUID()); + //TODO + validateField(actualAuditRecord, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(), + externalAuditObject.getARTIFACT_DATA()); + + } + + public enum ArtifactDataFieldEnum { + attGroup, artLable, artType, artName, artTimeout, artPayloadUUID, artVersion, artUUID + } + + private static void validateAtifactDataField(Map map, String auditJsonKeyName, + String expectedArtifactData, boolean checkAllFields) { + Map expectedArtifactDataFileds = new HashMap(); + Map actualAtifactDataFileds = new HashMap(); + if (expectedArtifactData != null) { + String[] expected = expectedArtifactData.split(","); + + assertTrue("Audit field " + auditJsonKeyName + " not found", map.containsKey(auditJsonKeyName)); + String actualValue = (String) map.get(auditJsonKeyName); + String[] actual = actualValue.split(","); + + if (expected.length == 1 && actual.length == 1) { + assertEquals(expectedArtifactData, actualValue); + return; + } + + assertEquals(ArtifactDataFieldEnum.values().length, expected.length); + assertEquals(ArtifactDataFieldEnum.values().length, actual.length); + + for (ArtifactDataFieldEnum field : ArtifactDataFieldEnum.values()) { + + expectedArtifactDataFileds.put(field, expected[field.ordinal()]); + actualAtifactDataFileds.put(field, actual[field.ordinal()]); + } + for (Map.Entry entry : expectedArtifactDataFileds.entrySet()) { + ArtifactDataFieldEnum field = entry.getKey(); + if (checkAllFields || (!field.equals(ArtifactDataFieldEnum.artVersion) + && !field.equals(ArtifactDataFieldEnum.artUUID))) { + assertTrue("Audit field ArtifactData dosn't containt " + field, + actualAtifactDataFileds.containsKey(field)); + assertEquals("Audit field ArtifactData dosn't equal " + field, + expectedArtifactDataFileds.get(field), actualAtifactDataFileds.get(field)); + } + + } + } + } + + // //Benny + public static void validateEcompConsumerAudit(ExpectedEcomConsumerAudit ecompConsumerAuditJavaObject, String action) + throws Exception { + + String fixedAction = BaseRestUtils.encodeUrlForDownload(action); + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(fixedAction, null); + + validateField(map2, EcompConsumerAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), + ecompConsumerAuditJavaObject.getModifier()); + validateField(map2, EcompConsumerAuditJsonKeysEnum.ECOMP_USER.getAuditJsonKeyName(), + ecompConsumerAuditJavaObject.getEcomUser()); + validateField(map2, EcompConsumerAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + ecompConsumerAuditJavaObject.getStatus()); + validateField(map2, EcompConsumerAuditJsonKeysEnum.DESC.getAuditJsonKeyName(), + ecompConsumerAuditJavaObject.getDesc()); + validateField(map2, EcompConsumerAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + } + + public static void ecompConsumerAuditSuccess(String action, ConsumerDataDefinition consumerDataDefinition, + User user, int status) throws Exception { + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(action); + expectedEcomConsumerAuditJavaObject.setEcomUser( + consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase() + + "," + consumerDataDefinition.getConsumerPassword().toLowerCase()); + expectedEcomConsumerAuditJavaObject.setStatus(String.valueOf(status)); + expectedEcomConsumerAuditJavaObject.setDesc("OK"); + expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action); + } + + public static void createEcompConsumerAuditFailure(String action, ConsumerDataDefinition consumerDataDefinition, + User user, ActionStatus errorMessage, Object... variables) throws Exception { + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + expectedEcomConsumerAuditJavaObject.setAction(action); + expectedEcomConsumerAuditJavaObject.setEcomUser( + consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase() + + "," + consumerDataDefinition.getConsumerPassword().toLowerCase()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action); + } + + public static void deleteEcompConsumerAuditFailure(String action, ConsumerDataDefinition consumerDataDefinition, + User user, ActionStatus errorMessage, Object... variables) throws Exception { + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name()); + ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); + // String auditAction = ADD_ECOMP_USER_CREDENTIALS_AUDIT_ACTION; + expectedEcomConsumerAuditJavaObject.setAction(action); + expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName()); + expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString()); + expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); + AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action); + } + + ////////////////////// US571255 + public static void GetListOfUsersByRolesAuditFailure(String action, String roles, int status, User userModifier, + ActionStatus errorMessage, Object... variables) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name()); + ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit(); // String + // auditAction + // = + // ADD_ECOMP_USER_CREDENTIALS_AUDIT_ACTION; + expectedGetListOfUsersAuditJavaObject.setAction(action); + expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status)); + expectedGetListOfUsersAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + + expectedGetListOfUsersAuditJavaObject.setDetails(roles); + if (errorMessage == ActionStatus.USER_INACTIVE || errorMessage == ActionStatus.MISSING_INFORMATION) { + expectedGetListOfUsersAuditJavaObject.setModifier("(UNKNOWN)"); + } else { + expectedGetListOfUsersAuditJavaObject + .setModifier(userModifier.getFullName() + "(" + userModifier.getUserId() + ")"); + } + AuditValidationUtils.validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action); + } + + public static void GetListOfUsersByRolesAuditSuccess(String action, String roles, User user, int status) + throws Exception { + ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit(); + expectedGetListOfUsersAuditJavaObject.setAction(action); + expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status)); + expectedGetListOfUsersAuditJavaObject.setDesc("OK"); + expectedGetListOfUsersAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); + expectedGetListOfUsersAuditJavaObject.setDetails(roles); + validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action); + } + + public static void validateAuditGetListOfUsersByRoles(ExpectedGetUserListAudit GetListOfUsersAuditJavaObject, + String action) throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), GetListOfUsersAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), + GetListOfUsersAuditJavaObject.getModifier()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), + GetListOfUsersAuditJavaObject.getDesc()); + validateField(map2, AuditJsonKeysEnum.DETAILS.getAuditJsonKeyName(), + GetListOfUsersAuditJavaObject.getDetails()); + } + + public static void validateAuditImport(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) + throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + + resourceAuditJavaObject.setModifierUid( + getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getPrevVersion()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid()); + validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getPrevState()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + + } + + public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) + throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + + resourceAuditJavaObject.setModifierUid( + getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState()); + validateField(map2, AuditJsonKeysEnum.DPREV_STATUS.getAuditJsonKeyName(), + resourceAuditJavaObject.getDprevStatus()); + validateField(map2, AuditJsonKeysEnum.DCURR_STATUS.getAuditJsonKeyName(), + resourceAuditJavaObject.getDcurrStatus()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment()); + validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId()); + + } + + // Benny + public static void validateAudit_Distribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, + String action) throws Exception { + + List> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1); + Map map2 = actionToList.get(0); + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getMODIFIER()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState()); + validateField(map2, AuditJsonKeysEnum.DPREV_STATUS.getAuditJsonKeyName(), + resourceAuditJavaObject.getDprevStatus()); + validateField(map2, AuditJsonKeysEnum.DCURR_STATUS.getAuditJsonKeyName(), + resourceAuditJavaObject.getDcurrStatus()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment()); + + } + + public void validateAuditNotification(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) + throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + + resourceAuditJavaObject.setModifierUid( + getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId()); + validateField(map2, AuditJsonKeysEnum.TOPIC_NAME.getAuditJsonKeyName(), resourceAuditJavaObject.getTopicName()); + + } + + public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action) + throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedDistDownloadAudit.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedDistDownloadAudit.getDesc()); + validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), + expectedDistDownloadAudit.getConsumerId()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), + expectedDistDownloadAudit.getResourceUrl()); + } + + public static void validateAuditExternalSearchAPI(ExpectedExternalAudit expectedDistDownloadAudit, String action, Map body) + throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, body); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedDistDownloadAudit.getSTATUS()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedDistDownloadAudit.getDESC()); + validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), + expectedDistDownloadAudit.getCONSUMER_ID()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), + expectedDistDownloadAudit.getRESOURCE_URL()); + } + + public static void validateAuditExternalCreateResource(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map body) throws Exception { + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, body); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), expectedExternalAudit.getResourceName()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), expectedExternalAudit.getResourceType()); + validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), expectedExternalAudit.getCONSUMER_ID()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), expectedExternalAudit.getRESOURCE_URL()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), expectedExternalAudit.getMODIFIER()); + + validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getPrevVersion()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), expectedExternalAudit.getPrevState()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), expectedExternalAudit.getCurrState()); + + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedExternalAudit.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedExternalAudit.getDesc()); + } + + public static void validateAuditExternalChangeAssetLifeCycle(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map body) throws Exception { + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, body); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedExternalAudit.getDesc()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedExternalAudit.getStatus()); + + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), expectedExternalAudit.getResourceType()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), expectedExternalAudit.getResourceName()); + validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), expectedExternalAudit.getCONSUMER_ID()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), expectedExternalAudit.getRESOURCE_URL()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), expectedExternalAudit.getMODIFIER()); + + validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getPrevVersion()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), expectedExternalAudit.getPrevState()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), expectedExternalAudit.getCurrState()); + + + // TODO: Remove comment +// validateField(map2, AuditJsonKeysEnum.INVARIANT_UUID.getAuditJsonKeyName(), expectedExternalAudit.getINVARIANT_UUID()); + } + + public void validateAuditDeploy(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) + throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + + resourceAuditJavaObject.setModifierUid( + getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId()); + + } + + public static void validateAuditProduct(ExpectedProductAudit productExpectedAudit, String action, + AuditJsonKeysEnum... additionalFields) throws Exception { + + Map map2 = new HashMap(); + map2 = parseAuditResourceByAction(action, null); + + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + productExpectedAudit.getRESOURCE_NAME()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + productExpectedAudit.getRESOURCE_TYPE()); + validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), + productExpectedAudit.getPREV_VERSION()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + productExpectedAudit.getCURR_VERSION()); + validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), productExpectedAudit.getPREV_STATE()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), productExpectedAudit.getCURR_STATE()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), productExpectedAudit.getMODIFIER()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), productExpectedAudit.getSTATUS()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), productExpectedAudit.getDESC()); + validateField(map2, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(), + productExpectedAudit.getSERVICE_INSTANCE_ID()); + if (additionalFields != null) { + List fieldsList = Arrays.asList(additionalFields); + if (fieldsList.contains(AuditJsonKeysEnum.COMMENT)) { + validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), productExpectedAudit.getCOMMENT()); + } + } + } + + private static List> getAuditListByAction(String action, int expectedNumOfAudit) + throws Exception { + List> actionToList = parseAuditResourceByActionToList(action, null); + assertEquals("recieved different audits number than expected", expectedNumOfAudit, actionToList.size()); + return actionToList; + } + + public static void validateAuthenticationAudit(ExpectedAuthenticationAudit expectedAudit) throws Exception { + List> actionToList = getAuditListByAction(expectedAudit.getAction(), 1); + assertEquals("expected number of ES action is 1", 1, actionToList.size()); + + Map map = actionToList.get(0); + validateField(map, AuditEnum.ACTION.getValue(), expectedAudit.getAction()); + validateField(map, AuditEnum.URL.getValue(), expectedAudit.getUrl()); + validateField(map, AuditEnum.USER.getValue(), expectedAudit.getUser()); + validateField(map, AuditEnum.AUTH_STATUS.getValue(), expectedAudit.getAuthStatus()); + validateField(map, AuditEnum.REALM.getValue(), expectedAudit.getRealm()); + + } + + private static void validateField(Map actualAuditRecord, String jsonField, Object expectedValue) { + if (expectedValue == null) { + // || changed to && + if (actualAuditRecord.containsKey(jsonField)) { + assertTrue("Audit field " + jsonField + ": expected null, actual " + actualAuditRecord.get(jsonField), + actualAuditRecord.get(jsonField).toString().equals("null") + || actualAuditRecord.get(jsonField).toString().equals(Constants.EMPTY_STRING)); + } + + } else { + assertTrue("Audit field " + jsonField + " not found in actual", actualAuditRecord.containsKey(jsonField)); + Object foundValue = actualAuditRecord.get(jsonField); + compareElements(expectedValue, foundValue); + } + } + + public static void compareElements(Object expectedValue, Object foundValue) { + if (expectedValue instanceof String) { + assertTrue("Actual value " + foundValue + " is not string", foundValue instanceof String); + assertTrue("Expected " + expectedValue + " not equal to actual " + foundValue, + foundValue.equals(expectedValue)); + } + /* + * else if( expectedValue instanceof Number){ assertTrue(foundValue + * instanceof Number); assertTrue(foundValue == expectedValue); } + */ + else if (expectedValue instanceof Boolean) { + assertTrue(foundValue instanceof Boolean); + assertTrue(foundValue == expectedValue); + } else if (expectedValue instanceof Map) { + assertTrue(foundValue instanceof Map); + Map foundMap = (Map) foundValue; + Map excpectedMap = (Map) expectedValue; + assertTrue("size of maps is not equel", foundMap.size() == excpectedMap.size()); + Iterator foundkeyItr = foundMap.keySet().iterator(); + while (foundkeyItr.hasNext()) { + String foundKey = foundkeyItr.next(); + assertTrue(excpectedMap.containsKey(foundKey)); + compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey)); + } + + } else if (expectedValue instanceof List) { + assertTrue(foundValue instanceof List); + List foundList = (List) foundValue; + List excpectedList = (List) expectedValue; + assertTrue("size of maps is not equel", foundList.size() == excpectedList.size()); + if( foundList.size() > 0 ){ + final Object elementInList = foundList.get(0); + if( !(elementInList instanceof List || elementInList instanceof Map) ){ + List tempList = new ArrayList<>(); + tempList.addAll(foundList); + for(Object expectedObj : excpectedList){ + if( tempList.contains(expectedObj)){ + tempList.remove(expectedObj); + } + else{ + assertTrue(false); + } + } + assertTrue("Lists are not equel", tempList.isEmpty()); + } + } + + } else { + assertTrue(foundValue.equals(expectedValue)); + } + } + + // public static Map parseAuditResourceByAction(String + // action, String body) throws Exception { + // + // Map auditingMessage = null; + // auditingMessage = retrieveAuditMessagesByPattern(action, null); + // + // return auditingMessage; + // + // } + + public static Map parseAuditResourceByAction(String action, Map body) throws Exception { + + Map auditingMessage = null; + auditingMessage = retrieveAuditMessagesByPattern(action, body, false); + + return auditingMessage; + + } + + // public static List> + // parseAuditResourceByActionToList(String action, String body) throws + // Exception { + // + // List> auditList = new ArrayList>(); + // + //// String auditingMessage = null; + // + // Map auditingMessage = null; + // auditingMessage = retrieveAuditMessagesByPattern(action); + // + // if (body == null) { + //// String pattern = "/_search?q=ACTION:\"" + action + "\""; + //// auditingMessage = retrieveAuditMessagesByPattern(action); + //// auditingMessage = retrieveAuditMessagesByPattern(pattern); + // } else { + //// auditingMessage = retrieveAuditMessagesUsingBody(body); + // } + // + // return ResponseParser.getAuditFromMessage(auditingMessage); + // + // } + + public static List> parseAuditResourceByActionToList(String action, + Map body) throws Exception { + + List> auditList = new ArrayList>(); + + // String auditingMessage = null; + + Map auditingMessage = null; + + if (body == null || body.isEmpty()) { + auditingMessage = retrieveAuditMessagesByPattern(action, null, false); + // String pattern = "/_search?q=ACTION:\"" + action + "\""; + // auditingMessage = retrieveAuditMessagesByPattern(action); + // auditingMessage = retrieveAuditMessagesByPattern(pattern); + } else { + auditingMessage = retrieveAuditMessagesByPattern(action, body, false); + // auditingMessage = retrieveAuditMessagesUsingBody(body); + } + + return ResponseParser.getAuditFromMessage(auditingMessage); + + } + + public JSONObject buildElasticQueryStringObject(String defaultField, String queryValue) throws JSONException { + + JSONObject query_string = new JSONObject(); + JSONObject jSONObject = new JSONObject(); + jSONObject.put("default_field", defaultField); + jSONObject.put("query", queryValue); + + query_string.put("query_string", jSONObject); + + return query_string; + } + + public static JSONObject buildElasticQueryBody(List listObjects) throws JSONException { + + JSONObject query = new JSONObject(); + JSONObject bool = new JSONObject(); + JSONObject must = new JSONObject(); + JSONArray mustA = new JSONArray(); + + for (int i = 0; i < listObjects.size(); i++) { + JSONObject match = new JSONObject(); + match.put("match", listObjects.get(i)); + mustA.put(match); + + } + + must.put("must", mustA); + bool.put("bool", must); + query.put("query", bool); + + return query; + } + + public static String retrieveAuditMessagesUsingBody(String query_string) throws IOException { + + Config config = Utils.getConfig(); + HttpRequest getAuditingMessage = new HttpRequest(); + Map headersMap = new HashMap(); + String body = query_string; + + String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), "_search"); + RestResponse restResponse = getAuditingMessage.httpSendPost(url, body, headersMap); + + return restResponse.getResponse(); + } + + public static Map retrieveAuditMessagesByPattern(String action, Map body, Boolean retryFlag) + throws IOException { + + // get cassandra table name by action + String esType = AuditingActionEnum.getActionByName(action).getAuditingEsType(); + Map resultsMap = new HashMap(); + + List> myFields = new ArrayList>(); + Pair myPair = new Pair( + AuditingFieldsKeysEnum.AUDIT_ACTION, action); + myFields.add(0, myPair); + if (body != null && !body.isEmpty()) { + for (Map.Entry mapElement : body.entrySet()) { + myFields.add(new Pair(mapElement.getKey(), mapElement.getValue())); + } + } + + List fetchFromTable = CassandraUtils.fetchFromTable(auditKeySpaceName, esType, myFields); + if(retryFlag){ + if(fetchFromTable.size() == 0){ + return resultsMap; + } + } +// assertTrue("expected on fetching from data base one record only, actual: " + fetchFromTable.size(), fetchFromTable.size() == 1); + + + + + Row row =null; + + if (fetchFromTable.size() > 1){ + List fetchFromTable2 = fetchFromTable; + fetchFromTable2.sort((p1, p2) -> p1.getTimestamp(1).compareTo(p2.getTimestamp(1))); + row = fetchFromTable2.get(fetchFromTable2.size() - 1); + } + else {row = fetchFromTable.get(0);} + + ColumnDefinitions columnDefinitions = row.getColumnDefinitions(); + + for (int i = 0; i < columnDefinitions.size(); i++) { + resultsMap.put(columnDefinitions.getName(i), row.getObject(columnDefinitions.getName(i)) == null ? "null" + : row.getObject(columnDefinitions.getName(i)).toString()); + } + + return resultsMap; + } + + // public static Map retrieveAuditMessagesByPattern(String pattern) throws + // IOException { + // + //// Config config = Utils.getConfig(); + //// HttpRequest getAuditingMessage = new HttpRequest(); + //// String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, + // config.getEsHost(), config.getEsPort(), pattern); + //// RestResponse restResponse = getAuditingMessage.httpSendGet(url, null); + // + //// get cassandra table name by action + // String esType = + // AuditingActionEnum.getActionByName(pattern).getAuditingEsType(); + //// AuditingActionEnum actionByName = + // AuditingActionEnum.getActionByName(pattern); + // + //// Map myFields= new + // HashMap(); + //// myFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION , pattern); + // + // List> myFields = new + // ArrayList>(); + // Pair myPair = new + // Pair(AuditingFieldsKeysEnum.AUDIT_ACTION + // , pattern); + // myFields.add(0, myPair); + // + // + // List fetchFromTable = CassandraUtils.fetchFromTable("sdcaudit", + // esType, myFields); + // Row row = fetchFromTable.get(0); + // + // + // ColumnDefinitions columnDefinitions = row.getColumnDefinitions(); + //// String string = row.getString(columnDefinitions.getName(1)); + // + //// String metaData = row.getColumnDefinitions().toString(); + //// metaData =metaData.replaceAll("\\((.*?)\\)|\\[|\\]|Columns", ""); + //// List metaDataList = new + // ArrayList(Arrays.asList(metaData.split(", "))); + // + // + // + // Map resultsMap = new HashMap(); + // + // + // for (int i=0 ; i < columnDefinitions.size() ; i++){ + // resultsMap.put(columnDefinitions.getName(i) , + // row.getObject(columnDefinitions.getName(i)) == null ? "null" : + // row.getObject(columnDefinitions.getName(i)).toString()); + // } + //// for (String string : metaDataList) { + //// resultsMap.put(string , row.getString(string)); + //// } + //// + // + //// String dataString = fetchFromTable.toString(); + //// dataString = dataString.replaceAll("\\[|\\]|Row", ""); + //// List dataArray = new + // ArrayList(Arrays.asList(dataString.split(", "))); + //// + //// + //// Map resultsMap = new HashMap(); + //// for (int i=0 ; i> actionToList = getAuditListByAction(expectedAddUserAuditJavaObject.getAction(), 1); + Map map = actionToList.get(0); + validateField(map, UserAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map, UserAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), + expectedAddUserAuditJavaObject.getModifier()); + validateField(map, UserAuditJsonKeysEnum.USER_AFTER.getAuditJsonKeyName(), + expectedAddUserAuditJavaObject.getUserAfter()); + validateField(map, UserAuditJsonKeysEnum.USER_BEFORE.getAuditJsonKeyName(), + expectedAddUserAuditJavaObject.getUserBefore()); + validateField(map, UserAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + expectedAddUserAuditJavaObject.getStatus()); + validateField(map, UserAuditJsonKeysEnum.DESC.getAuditJsonKeyName(), expectedAddUserAuditJavaObject.getDesc()); + + } + + private static void categoryAuditFailureInternal(String action, CategoryDefinition categoryDataDefinition, + SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, + ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception { + // validate audit + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name()); + ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit(); + expectedCatrgoryAuditJavaObject.setAction(action); + expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); + expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName()); + String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() + : Constants.EMPTY_STRING); + expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName); + String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING); + expectedCatrgoryAuditJavaObject.setGroupingName(groupingName); + expectedCatrgoryAuditJavaObject.setResourceType(resourceType); + expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status)); + expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)); + AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action); + } + + public static void validateGetCategoryHirarchy(ExpectedCategoryAudit expectedCatrgoryAuditJavaObject, String action) + throws Exception { + + List> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1); + Map map = actionToList.get(0); + + expectedCatrgoryAuditJavaObject.setModifier(getModifierString(expectedCatrgoryAuditJavaObject.getModifierName(), + expectedCatrgoryAuditJavaObject.getModifierUid())); + validateField(map, CategoryAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map, CategoryAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getModifier()); + validateField(map, CategoryAuditJsonKeysEnum.DETAILS.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getDetails()); + validateField(map, CategoryAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getStatus()); + validateField(map, CategoryAuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getDesc()); + + } + + public static void validateCategoryAudit(ExpectedCategoryAudit expectedCatrgoryAuditJavaObject, String action) + throws Exception { + + List> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1); + Map map = actionToList.get(0); + validateField(map, CategoryAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map, CategoryAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getModifier()); + validateField(map, CategoryAuditJsonKeysEnum.CATEGORY_NAME.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getCategoryName()); + validateField(map, CategoryAuditJsonKeysEnum.SUB_CATEGORY_NAME.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getSubCategoryName()); + validateField(map, CategoryAuditJsonKeysEnum.GROUPING_NAME.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getGroupingName()); + validateField(map, CategoryAuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getResourceType()); + validateField(map, CategoryAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getStatus()); + validateField(map, CategoryAuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), + expectedCatrgoryAuditJavaObject.getDesc()); + } + + public static void GetCategoryHierarchyAuditSuccess(String action, String componentType, User user, int status) + throws Exception { + ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit(); + expectedGetListOfUsersAuditJavaObject.setAction(action); + expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status)); + expectedGetListOfUsersAuditJavaObject.setDesc("OK"); + expectedGetListOfUsersAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); + expectedGetListOfUsersAuditJavaObject.setDetails(componentType.toLowerCase()); + validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action); + } + + public static String buildArtifactDataAudit(ArtifactDefinition artifactDefinition) { + StringBuilder sb = new StringBuilder(); + if (artifactDefinition.getTimeout() == null) { + artifactDefinition.setTimeout(0); + } + if (artifactDefinition != null) { + sb.append(artifactDefinition.getArtifactGroupType() == null ? null + : artifactDefinition.getArtifactGroupType().getType()).append(",").append("'") + .append(artifactDefinition.getArtifactLabel()).append("'").append(",") + .append(artifactDefinition.getArtifactType()).append(",") + .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()) + .append(",").append(artifactDefinition.getEsId()); + sb.append(","); + if (artifactDefinition.getArtifactVersion() != null) { + sb.append(artifactDefinition.getArtifactVersion()); + } else { + sb.append(" "); + } + sb.append(","); + if (artifactDefinition.getArtifactUUID() != null) { + sb.append(artifactDefinition.getArtifactUUID()); + } else { + sb.append(" "); + } + } + + return sb.toString(); + } + + public static ExpectedResourceAuditJavaObject expectedMissingInformationAuditObject(String Action, + String resourceUid, ComponentType resourceType) throws FileNotFoundException { + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceUid); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(""); + expectedAudit.setModifierName(""); + expectedAudit.setModifierUid(""); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(""); + expectedAudit.setPrevArtifactUuid(""); + expectedAudit.setCurrArtifactUuid(""); + expectedAudit.setArtifactData(""); + expectedAudit.setStatus("403"); + expectedAudit.setDesc(buildAuditDescription( + new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()), + new ArrayList())); + return expectedAudit; + } + + public static ExpectedResourceAuditJavaObject expectedComponentNotFoundAuditObject(String Action, + String resourceUid, ComponentType resourceType, String artifactUid, User user, + ArrayList notFoundComponent) throws FileNotFoundException { + String desc = null; + + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceUid); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(""); + expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName()); + expectedAudit.setModifierUid(user.getUserId()); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(""); + expectedAudit.setPrevArtifactUuid(""); + expectedAudit.setCurrArtifactUuid(artifactUid); + expectedAudit.setArtifactData(""); + expectedAudit.setStatus("404"); + + if (resourceType.getValue() == ComponentType.SERVICE.getValue()) { + desc = buildAuditDescription( + new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()), + notFoundComponent); + } else if (resourceType.getValue() == ComponentType.RESOURCE.getValue()) + desc = buildAuditDescription( + new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()), + notFoundComponent); + + expectedAudit.setDesc(desc); + return expectedAudit; + } + + public static ExpectedResourceAuditJavaObject expectedArtifactNotFoundAuditObject(String Action, String resourceUid, + ComponentType resourceType, String artifactUid, User user, String currState, String currVersion) + throws FileNotFoundException { + String desc = null; + + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceUid); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(currVersion); + expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName()); + expectedAudit.setModifierUid(user.getUserId()); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(currState); + expectedAudit.setPrevArtifactUuid(""); + expectedAudit.setCurrArtifactUuid(artifactUid); + expectedAudit.setArtifactData(""); + expectedAudit.setStatus("404"); + + desc = buildAuditDescription( + new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()), + Arrays.asList("")); + + expectedAudit.setDesc(desc); + return expectedAudit; + } + + public static ExpectedResourceAuditJavaObject expectedArtifactNotFoundAuditObject(String Action, + String resourceName, ComponentType resourceType, String artifactUid, LifecycleStateEnum lifecycle, + User user, String currVersion) throws FileNotFoundException { + String desc = null; + + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceName); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(currVersion); + expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName()); + expectedAudit.setModifierUid(user.getUserId()); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(lifecycle.name()); + expectedAudit.setPrevArtifactUuid(""); + expectedAudit.setCurrArtifactUuid(artifactUid); + expectedAudit.setArtifactData(""); + expectedAudit.setStatus("404"); + + desc = buildAuditDescription( + new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()), + new ArrayList()); + + expectedAudit.setDesc(desc); + return expectedAudit; + } + + public static ExpectedResourceAuditJavaObject expectedRestrictedOperationAuditObject(String Action, + String resourceNameOrUid, ComponentType resourceType, String artifactUid, User user, String currVersion, + String currState) throws FileNotFoundException { + String desc = null; + + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceNameOrUid); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(currVersion); + expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName()); + expectedAudit.setModifierUid(user.getUserId()); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(currState); + expectedAudit.setPrevArtifactUuid(""); + expectedAudit.setCurrArtifactUuid(artifactUid); + expectedAudit.setArtifactData(""); + expectedAudit.setStatus("409"); + + desc = buildAuditDescription( + new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()), + new ArrayList()); + + expectedAudit.setDesc(desc); + return expectedAudit; + } + + public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(String Action, String resourceName, + ComponentType resourceType, String artifactUid, User user, String currVersion, String currState, + ArrayList invalidContentList) throws FileNotFoundException { + return expectedInvalidContentAuditObject(ActionStatus.INVALID_CONTENT, Action, resourceName, resourceType, + artifactUid, user, currVersion, currState, invalidContentList); + } + + public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(ActionStatus actionStatus, + String Action, String resourceName, ComponentType resourceType, String artifactUid, User user, + String currVersion, String currState, ArrayList invalidContentList) throws FileNotFoundException { + String desc = null; + + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceName); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(currVersion); + expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName()); + expectedAudit.setModifierUid(user.getUserId()); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(currState); + expectedAudit.setPrevArtifactUuid(""); + expectedAudit.setCurrArtifactUuid(artifactUid); + expectedAudit.setArtifactData(""); + expectedAudit.setStatus("400"); + + desc = buildAuditDescription(new ErrorValidationUtils().parseErrorConfigYaml(actionStatus.name()), + invalidContentList); + + expectedAudit.setDesc(desc); + return expectedAudit; + } + + public static ExpectedResourceAuditJavaObject expectedSuccessAuditObject(String Action, String resourceName, + ComponentType resourceType, ArtifactReqDetails artifactReq, User user, String currVersion, String currState, + String prevArtifactUuid) throws FileNotFoundException { + ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject(); + expectedAudit.setAction(Action); + expectedAudit.setResourceName(resourceName); + expectedAudit.setResourceType(resourceType.getValue()); + expectedAudit.setPrevVersion(""); + expectedAudit.setCurrVersion(currVersion); + expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName()); + expectedAudit.setModifierUid(user.getUserId()); + expectedAudit.setPrevState(""); + expectedAudit.setCurrState(currState); + expectedAudit.setPrevArtifactUuid(prevArtifactUuid); + expectedAudit.setCurrArtifactUuid(artifactReq.getUniqueId()); + expectedAudit + .setArtifactData(buildArtifactDataAudit(ArtifactUtils.convertArtifactReqToDefinition(artifactReq))); + expectedAudit.setStatus("200"); + expectedAudit.setDesc("OK"); + return expectedAudit; + } + + public static JSONObject filterAuditByUuid(String action, String uuid) throws Exception { + Map actionMap = new HashMap(); + actionMap.put("ACTION", action); + JSONObject actionJsonObject = new JSONObject(actionMap); + Map uuidMap = new HashMap(); + uuidMap.put("SERVICE_INSTANCE_ID", uuid); + JSONObject uuidJsonObject = new JSONObject(uuidMap); + + List filters = new ArrayList(Arrays.asList(actionJsonObject, uuidJsonObject)); + JSONObject body = buildElasticQueryBody(filters); + return body; + } + + public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) + throws Exception { + List> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1); + Map map2 = actionToList.get(0); + validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); + validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceName()); + validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), + resourceAuditJavaObject.getResourceType()); + validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getPrevVersion()); + validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), + resourceAuditJavaObject.getCurrVersion()); + validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getMODIFIER()); + validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getPrevState()); + validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState()); + validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus()); + validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment()); + } + + ////// service audit validation///////////////////// + + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails, + String serviceVersion, User sdncUserDetails) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + + expectedResourceAuditJavaObject.setAction("Create"); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + String userFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName(); + expectedResourceAuditJavaObject.setModifierName(userFirstLastName); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setResourceName(serviceReqDetails.getName()); + expectedResourceAuditJavaObject.setResourceType("Service"); + expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(serviceVersion) - 0.1f)); + expectedResourceAuditJavaObject.setCurrVersion(serviceVersion); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setComment(null); + + return expectedResourceAuditJavaObject; + + } + + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails, + String serviceVersion, User sdncUserDetails, ActionStatus errorStatus, List variables) + throws FileNotFoundException { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = constructFieldsForAuditValidation( + serviceReqDetails, serviceVersion, sdncUserDetails); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorStatus.name()); + + expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()); + String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + expectedResourceAuditJavaObject.setDesc(auditDesc); + + return expectedResourceAuditJavaObject; + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java new file mode 100644 index 0000000000..0d49d97302 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java @@ -0,0 +1,117 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.FileNotFoundException; +import java.util.Arrays; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.exception.ResponseFormat; +import org.testng.Assert; + +public class BaseValidationUtils { + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_CREATED = 201; + public static final int STATUS_CODE_DELETE = 204; + public static final int STATUS_CODE_NOT_FOUND = 404; + public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204; + public static final int STATUS_CODE_SUCCESS_DELETE = 204; + public static final int STATUS_CODE_INVALID_CONTENT = 400; + public static final int STATUS_CODE_MISSING_DATA = 400; + public static final int STATUS_CODE_MISSING_INFORMATION = 403; + public static final int STATUS_CODE_RESTRICTED_ACCESS = 403; + public static final int STATUS_CODE_RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_ALREADY_EXISTS = 409; + + // ------ + protected static Boolean checkErrorCode(RestResponse deleteResponse) { + if (deleteResponse.getErrorCode() == STATUS_CODE_SUCCESS + || deleteResponse.getErrorCode() == STATUS_CODE_DELETE) { + return true; + } + return false; + } + + // *** STATUS CODE VALIDATION UTIITIES **** + public static void checkStatusCode(RestResponse response, String assertMessage, boolean AND, int... statuses) { + int statusCode = response.getErrorCode(); + for (int status : statuses) { + if (AND && statusCode != status) { + Assert.fail(assertMessage + " status: " + statusCode); + } else if (statusCode == status) { + return; + } + } + if (!AND) { + Assert.fail(assertMessage + " status: " + statusCode); + } + } + + public static void checkDeleteResponse(RestResponse response) { + checkStatusCode(response, "delete request failed", false, STATUS_CODE_DELETE, STATUS_CODE_NOT_FOUND, + STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for deActivate user + } + + public static void checkCreateResponse(RestResponse response) { + checkStatusCode(response, "create request failed", false, STATUS_CODE_CREATED); + } + + public static void checkSuccess(RestResponse response) { + checkStatusCode(response, "request failed", false, STATUS_CODE_SUCCESS); + } + + public static void checkErrorResponse(RestResponse errorResponse, ActionStatus actionStatus, + String... expectedVariables) throws FileNotFoundException { + // Expected error + ErrorInfo expectedError = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + String expectedMessage = expectedError.getMessage(); + + // Actual error + ResponseFormat responseFormat = ResponseParser.parseToObjectUsingMapper(errorResponse.getResponse(), + ResponseFormat.class); + String actualMessage = responseFormat.getText(); + String[] actualVariables = responseFormat.getVariables(); + + assertEquals("Unexpected error message", expectedMessage, actualMessage); + assertEquals("Unexpected error variables", Arrays.asList(expectedVariables), Arrays.asList(actualVariables)); + } + + public static void checkErrorMessageResponse(RestResponse errorResponse, ActionStatus actionStatus) + throws FileNotFoundException { + // Expected error + ErrorInfo expectedError = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + String expectedMessage = expectedError.getMessage(); + + // Actual error + ResponseFormat responseFormat = ResponseParser.parseToObjectUsingMapper(errorResponse.getResponse(), + ResponseFormat.class); + String actualMessage = responseFormat.getText(); + + assertEquals("Unexpected error message", expectedMessage, actualMessage); + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java new file mode 100644 index 0000000000..d63a514b3a --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java @@ -0,0 +1,125 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.assertEquals; +import org.json.JSONObject; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; + +public class CategoryValidationUtils { + + public static void verifyCategoryExistInGetResponse(RestResponse getAllCategoryRest, + CategoryDefinition categoryDefinition) { + + int categoriesNum = CategoryRestUtils.getMatchingCategoriesNum(getAllCategoryRest, categoryDefinition); + assertEquals("category " + categoryDefinition.getName() + " not found during get or found more than once", 1, + categoriesNum); + } + + public static void verifyCategoryNotExistsInGetResponse(RestResponse getAllCategoryRest, + CategoryDefinition categoryDefinition) { + + int categoriesNum = CategoryRestUtils.getMatchingCategoriesNum(getAllCategoryRest, categoryDefinition); + assertEquals("category " + categoryDefinition.getName() + " should't be found during get", 0, categoriesNum); + } + + public static void verifySubCategoryExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId, + SubCategoryDefinition expectedSubCategoryDefinition) { + + int subCategoriesNum = CategoryRestUtils.getMatchingSubCategoriesNum(getAllCategoryRest, parentCategoryId, + expectedSubCategoryDefinition); + assertEquals( + "sub-category " + expectedSubCategoryDefinition.getName() + + " not found during get or found more than once for parentId " + parentCategoryId, + 1, subCategoriesNum); + } + + public static void verifyGroupingExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId, + String subCategoryId, GroupingDefinition expectedGroupingDefinition) { + + int groupingNum = CategoryRestUtils.getMatchingGroupingNum(getAllCategoryRest, parentCategoryId, subCategoryId, + expectedGroupingDefinition); + assertEquals( + "sub-category " + expectedGroupingDefinition.getName() + + " not found during get or found more than once for parentId " + parentCategoryId, + 1, groupingNum); + } + + public static void verifyGroupingNotExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId, + String subCategoryId, GroupingDefinition expectedGroupingDefinition) { + + int groupingNum = CategoryRestUtils.getMatchingGroupingNum(getAllCategoryRest, parentCategoryId, subCategoryId, + expectedGroupingDefinition); + assertEquals( + "sub-category " + expectedGroupingDefinition.getName() + + " not found during get or found more than once for parentId " + parentCategoryId, + 0, groupingNum); + } + + public static void verifySubCategoryNotExistsInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId, + SubCategoryDefinition expectedSubCategoryDefinition) { + + int subCategoriesNum = CategoryRestUtils.getMatchingSubCategoriesNum(getAllCategoryRest, parentCategoryId, + expectedSubCategoryDefinition); + assertEquals("sub-category " + expectedSubCategoryDefinition.getName() + + " should't be found during get for parentId " + parentCategoryId, 0, subCategoriesNum); + } + + /// NEE Benny + public static void validateCreateGroupResponse(RestResponse createSubCategoryRest, + GroupingDefinition expectedGroupDefinition) throws Exception { + + String response = createSubCategoryRest.getResponse(); + JSONObject jobject = new JSONObject(response); + assertTrue(jobject.get("name").equals(expectedGroupDefinition.getName())); + assertTrue(jobject.get("normalizedName").equals(expectedGroupDefinition.getNormalizedName())); + // assertNotNull(jobject.get("normalizedName")); + assertNotNull(jobject.get("uniqueId")); + expectedGroupDefinition.setUniqueId(jobject.get("uniqueId").toString()); + + } + + public static void validateCreateSubCategoryResponse(RestResponse createSubCategoryRest, + SubCategoryDefinition expectedSubCategoryDefinition) throws Exception { + + String response = createSubCategoryRest.getResponse(); + JSONObject jobject = new JSONObject(response); + assertTrue(jobject.get("name").equals(expectedSubCategoryDefinition.getName())); + assertNotNull(jobject.get("normalizedName")); + assertNotNull(jobject.get("uniqueId")); + } + + public static void validateCreateCategoryResponse(RestResponse createCategoryRest, + CategoryDefinition expectedCategoryDefinition) throws Exception { + String response = createCategoryRest.getResponse(); + JSONObject jobject = new JSONObject(response); + assertTrue(jobject.get("name").equals(expectedCategoryDefinition.getName())); + assertTrue(jobject.get("normalizedName").equals(expectedCategoryDefinition.getNormalizedName())); + assertNotNull(jobject.get("uniqueId")); + } + +} 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 new file mode 100644 index 0000000000..0fe11537e4 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java @@ -0,0 +1,488 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.utils.CsarParserUtils; +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.common.rest.api.RestResponseAsByteArray; +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 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 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 listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarUUID); + assertTrue( + "check group count, expected: " + getGroupCount(listTypeHeatMetaDefinition) + ", actual: " + + resource.getGroups().size(), + getGroupCount(listTypeHeatMetaDefinition) == resource.getGroups().size()); + assertTrue( + "check artifact count, expected: " + getArtifactCount(listTypeHeatMetaDefinition, false) + ", actual: " + + resource.getDeploymentArtifacts().size(), + getArtifactCount(listTypeHeatMetaDefinition, false) == resource.getDeploymentArtifacts().size()); + + } + + /*public static List getListTypeHeatMetaDefinition(String csarUUID) throws Exception { + + String artifactHeatMetaLocation = "Artifacts/HEAT.meta"; + JSONParser parser = new JSONParser(); + String csarPayload = getCsarPayload(csarUUID, artifactHeatMetaLocation); + if (csarPayload != null) { + Object parse = parser.parse(csarPayload); + JSONObject jsonObject = (JSONObject) parse; + JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure"); + List listHeatMetaDefenition = new ArrayList(); + listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition); + return listHeatMetaDefenition; + } + return null; + + }*/ + + /*public static List getListTypeHeatMetaDefinition(File csarUUID) throws Exception { + + String artifactHeatMetaLocation = "Artifacts/HEAT.meta"; + JSONParser parser = new JSONParser(); + String csarPayload = getCsarPayload(csarUUID, artifactHeatMetaLocation); + if (csarPayload != null) { + Object parse = parser.parse(csarPayload); + JSONObject jsonObject = (JSONObject) parse; + JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure"); + List listHeatMetaDefenition = new ArrayList(); + listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition); + return listHeatMetaDefenition; + } + return null; + + }*/ + + private static Integer getGroupCount(List listHeatMetaDefenition) { + int count = 0; + for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) { + count = count + typeHeatMetaDefinition.getGroupHeatMetaDefinition().size(); + } + return count; + } + + private static Integer getArtifactCount(List listHeatMetaDefenition, Boolean isEnvIncluded) { + int count = 0; + List uniqeArtifactList = new ArrayList<>(); + + for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) { + for (GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition + .getGroupHeatMetaDefinition()) { + if (isEnvIncluded) { + count = count + groupHeatMetaDefinition.getArtifactList().size(); + } else { + for (HeatMetaFirstLevelDefinition fileName : groupHeatMetaDefinition.getArtifactList()) { + if (!fileName.getFileName().contains(".env") && !uniqeArtifactList.contains(fileName)) { + uniqeArtifactList.add(fileName); + count = count + 1; + } + } + } + } + } + return count; + } + + /*protected static List getArtifactsByGroup(JSONObject jsonObjectImportStructure, List listHeatMetaDefenition) { + + @SuppressWarnings("unchecked") + Set typeSet = jsonObjectImportStructure.keySet(); + for (Object type : typeSet) { + TypeHeatMetaDefinition heatMetaDefenition = new TypeHeatMetaDefinition(); + log.debug(type.toString()); + log.debug("{}", jsonObjectImportStructure.get(type)); + JSONArray array = (JSONArray) jsonObjectImportStructure.get(type); + heatMetaDefenition.setTypeName((String) type); + List groupHeatMetaDefinitions = new ArrayList(); + heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroupFromJsonArray(array, groupHeatMetaDefinitions, true, false)); + listHeatMetaDefenition.add(heatMetaDefenition); + } + return listHeatMetaDefenition; + }*/ + +/* protected static List fetchArtifactByGroupFromJsonArray(JSONArray array, List listGroupHeatMetaDefinition, Boolean openNewGroup, Boolean isNested) { + + GroupHeatMetaDefinition groupHeatMetaDefinition; + + if (array != null) { + for (int i = 0; i < array.size(); i++) { + if (openNewGroup) { + groupHeatMetaDefinition = new GroupHeatMetaDefinition(); + int groupNumber = listGroupHeatMetaDefinition.size() + 1; + log.debug("groupName={}", groupNumber); + groupHeatMetaDefinition.setGroup(groupNumber); + listGroupHeatMetaDefinition.add(groupHeatMetaDefinition); + PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition(); + propertyHeatMetaDefinition.setName("isBase"); + propertyHeatMetaDefinition.setValue(false); + groupHeatMetaDefinition.setPropertyHeatMetaDefinition(propertyHeatMetaDefinition); + } + groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1); + JSONObject jsonObject = (JSONObject) array.get(i); + fetchArtifactByGroupFromJsonObject(listGroupHeatMetaDefinition, groupHeatMetaDefinition, jsonObject, isNested); + } + } + return listGroupHeatMetaDefinition; + }*/ + + + /*public static void fetchArtifactByGroupFromJsonObject(List listGroupHeatMetaDefinition, GroupHeatMetaDefinition groupHeatMetaDefinition, JSONObject jsonObject, Boolean isNested) { + @SuppressWarnings("unchecked") + Set groupsKey = jsonObject.keySet(); + for (Object groupKey : groupsKey) { + String groupKeyStr = (String) groupKey; + if (groupKeyStr.equals("isBase")) { + PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition(); + propertyHeatMetaDefinition.setName(groupKeyStr); + propertyHeatMetaDefinition.setValue((boolean) jsonObject.get(groupKeyStr)); + if (!groupHeatMetaDefinition.getPropertyHeatMetaDefinition().equals(propertyHeatMetaDefinition)) { + groupHeatMetaDefinition.getPropertyHeatMetaDefinition().setValue((boolean) jsonObject.get(groupKeyStr)); + } + } + if (groupKeyStr.equals("fileName")) { + String artifactName = (String) jsonObject.get(groupKeyStr); + String artifactType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); + if(isNested){ + artifactType = ArtifactTypeEnum.HEAT_NESTED.getType(); + } + if(jsonObject.get("type") != null && isNested == false){ + artifactType = (String) jsonObject.get("type"); + } + HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition = new HeatMetaFirstLevelDefinition(artifactName, artifactType); + List listArtifactNames = groupHeatMetaDefinition.getArtifactList(); + listArtifactNames.add(heatMetaFirstLevelDefinition); + groupHeatMetaDefinition.setArtifactList(listArtifactNames); + } else { + if((groupKeyStr.equals("env"))){ + if (jsonObject.get(groupKeyStr) instanceof JSONObject){ + fetchArtifactByGroupFromJsonObject(listGroupHeatMetaDefinition, groupHeatMetaDefinition, (JSONObject) jsonObject.get(groupKeyStr), false); + }else{ + assertTrue("Expected object is JSONObject, but actual: " + jsonObject.get(groupKeyStr).getClass(), jsonObject.get(groupKeyStr).getClass().equals("JSONObject")); + } + } + if((groupKeyStr.equals("nested"))){ + if (jsonObject.get(groupKeyStr) instanceof JSONArray){ + fetchArtifactByGroupFromJsonArray((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, false, true); + }else{ + assertTrue("Expected object is JSONArray, but actual: " + jsonObject.get(groupKeyStr).getClass(), jsonObject.get(groupKeyStr).getClass().equals("JSONArray")); + } + + }else if (!(groupKeyStr.equals("isBase") || groupKeyStr.equals("type") || groupKeyStr.equals("env"))) { + if (jsonObject.get(groupKeyStr) instanceof JSONArray){ + fetchArtifactByGroupFromJsonArray((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, false, false); + }else{ + assertTrue("Expected object is JSONArray, but actual: " + jsonObject.get(groupKeyStr).getClass(), jsonObject.get(groupKeyStr).getClass().equals("JSONArray")); + } + } + } + } + }*/ + + /*public static List getListTypeHeatMetaDefinition(String csarUUID) throws Exception { + + String artifactHeatMetaLocation = "Artifacts/HEAT.meta"; + JSONParser parser = new JSONParser(); + String csarPayload = getCsarPayload(csarUUID, artifactHeatMetaLocation); + if (csarPayload != null) { + Object parse = parser.parse(csarPayload); + JSONObject jsonObject = (JSONObject) parse; + JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure"); + List listHeatMetaDefenition = new ArrayList(); + listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition); + return listHeatMetaDefenition; + } + return null; + + } + + protected static List getArtifactsByGroup(JSONObject jsonObjectImportStructure, + List listHeatMetaDefenition) { + + @SuppressWarnings("unchecked") + Set typeSet = jsonObjectImportStructure.keySet(); + for (Object type : typeSet) { + TypeHeatMetaDefinition heatMetaDefenition = new TypeHeatMetaDefinition(); + log.debug(type.toString()); + log.debug("{}", jsonObjectImportStructure.get(type)); + JSONArray array = (JSONArray) jsonObjectImportStructure.get(type); + heatMetaDefenition.setTypeName((String) type); + List groupHeatMetaDefinitions = new ArrayList(); + heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroup(array, groupHeatMetaDefinitions, true)); + listHeatMetaDefenition.add(heatMetaDefenition); + } + return listHeatMetaDefenition; + } + + protected static List fetchArtifactByGroup(JSONArray array, + List listGroupHeatMetaDefinition, Boolean openNewGroup) { + + GroupHeatMetaDefinition groupHeatMetaDefinition; + + if (array != null) { + for (int i = 0; i < array.size(); i++) { + if (openNewGroup) { + groupHeatMetaDefinition = new GroupHeatMetaDefinition(); + int groupNumber = listGroupHeatMetaDefinition.size() + 1; + log.debug("groupName={}", groupNumber); + groupHeatMetaDefinition.setGroup(groupNumber); + listGroupHeatMetaDefinition.add(groupHeatMetaDefinition); + PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition(); + propertyHeatMetaDefinition.setName("isBase"); + propertyHeatMetaDefinition.setValue(false); + groupHeatMetaDefinition.setPropertyHeatMetaDefinition(propertyHeatMetaDefinition); + } + groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1); + JSONObject jsonObject = (JSONObject) array.get(i); + @SuppressWarnings("unchecked") + Set groupsKey = jsonObject.keySet(); + for (Object groupKey : groupsKey) { + String groupKeyStr = (String) groupKey; + if (groupKeyStr.equals("isBase")) { + PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition(); + propertyHeatMetaDefinition.setName(groupKeyStr); + propertyHeatMetaDefinition.setValue((boolean) jsonObject.get(groupKeyStr)); + if (!groupHeatMetaDefinition.getPropertyHeatMetaDefinition() + .equals(propertyHeatMetaDefinition)) { + groupHeatMetaDefinition.getPropertyHeatMetaDefinition() + .setValue((boolean) jsonObject.get(groupKeyStr)); + } + } + if (groupKeyStr.equals("fileName") || groupKeyStr.equals("env")) { + String artifactName = (String) jsonObject.get(groupKeyStr); + List listArtifactNames = groupHeatMetaDefinition.getArtifactList(); + listArtifactNames.add(artifactName); + groupHeatMetaDefinition.setArtifactList(listArtifactNames); + } else { + if (!groupKeyStr.equals("isBase")) { + fetchArtifactByGroup((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, + false); + } + } + } + } + } + return listGroupHeatMetaDefinition; + } + + private static Integer getArtifactCount(List listHeatMetaDefenition, + Boolean isEnvIncluded) { + int count = 0; + List uniqeArtifactList = new ArrayList<>(); + + for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) { + for (GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition + .getGroupHeatMetaDefinition()) { + if (isEnvIncluded) { + count = count + groupHeatMetaDefinition.getArtifactList().size(); + } else { + for (String fileName : groupHeatMetaDefinition.getArtifactList()) { + if (!fileName.contains(".env") && !uniqeArtifactList.contains(fileName)) { + uniqeArtifactList.add(fileName); + count = count + 1; + } + } + } + } + } + return count; + } + + private static Integer getGroupCount(List listHeatMetaDefenition) { + int count = 0; + for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) { + count = count + typeHeatMetaDefinition.getGroupHeatMetaDefinition().size(); + } + return count; + } + + private static String groupNameBuilder(Resource resource) { + String separator = "::"; + String module = "module-"; + String groupName = resource.getSystemName() + separator + module; + return groupName; + } + + public static void validateCsarVfArtifact(String csarUUID, Resource resource) throws Exception { + + List listTypeHeatMetaDefinition = getListTypeHeatMetaDefinition(csarUUID); + assertTrue( + "check group count, expected: " + getGroupCount(listTypeHeatMetaDefinition) + ", actual: " + + resource.getGroups().size(), + getGroupCount(listTypeHeatMetaDefinition) == resource.getGroups().size()); + assertTrue( + "check artifact count, expected: " + getArtifactCount(listTypeHeatMetaDefinition, false) + ", actual: " + + resource.getDeploymentArtifacts().size(), + getArtifactCount(listTypeHeatMetaDefinition, false) == resource.getDeploymentArtifacts().size()); + + } + + public static void validateToscaDefinitonObjectVsResource(ToscaDefinition toscaDefinition, Resource resource) + throws Exception { + + assertTrue( + "check resource instance count, expected: " + getResourceInstanceCount(toscaDefinition) + ", actual: " + + resource.getComponentInstances().size(), + getResourceInstanceCount(toscaDefinition) == resource.getComponentInstances().size()); + assertTrue( + "check resource instance relation count, expected: " + getResourceInstanceRelationCount(toscaDefinition) + + ", actual: " + resource.getComponentInstancesRelations().size(), + getResourceInstanceRelationCount(toscaDefinition) == resource.getComponentInstancesRelations().size()); + + } + + public static Integer getResourceInstanceCount(ToscaDefinition toscaDefinition) { + + return toscaDefinition.getTopology_template().getNode_templates().size(); + } + + public static Integer getResourceInstanceRelationCount(ToscaDefinition toscaDefinition) { + int count = 0; +// List toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition +// .getTopology_template().getToscaNodeTemplatesTopologyTemplateDefinition(); + Map toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition.getTopology_template().getNode_templates(); + for (int i = 0; i < toscaNodeTemplatesTopologyTemplateDefinition.size(); i++) { +// List requirements = toscaNodeTemplatesTopologyTemplateDefinition.get(i).getRequirements(); + + for(Entry entry: toscaDefinition.getTopology_template().getNode_templates().entrySet() ){ + if (entry.getValue().equals("requirements")){ + + } + } + + if (requirements != null) { + for (ToscaRequirementsNodeTemplatesDefinition requirement : requirements) { + if (requirement.getNode() != null) { + count = count + 1; + } + } + } + } + return count; + } + + // not finished yet + private static void validateCsarVfgroup(String csarUUID, Resource resource) { + + List groups = resource.getGroups(); + for (GroupDefinition groupDefinition : groups) { + List artifacts = groupDefinition.getArtifacts(); + assertTrue("group description is null", groupDefinition.getDescription() != null); + assertTrue("InvariantUUID is null", groupDefinition.getInvariantUUID() != null); + // groupDefinition.getMembers(); + assertTrue( + "name format mismatch, expected: " + groupNameBuilder(resource) + "[0-9], actual: " + + groupDefinition.getName(), + groupDefinition.getName().contains(groupNameBuilder(resource))); + // groupDefinition.getProperties(); + // groupDefinition.getPropertyValueCounter(); + assertTrue(groupDefinition.getType().equals(getGroupType())); + } + + String expectedCsarUUID = csarUUID; + // String expectedToscaResourceName = "org.openecomp.resource.vf." + + // WordUtils.capitalize(resourceDetails.getName().toLowerCase()); + // + // assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, + // resource.getCsarUUID()), + // expectedCsarUUID.equals(resource.getCsarUUID())); + // assertTrue("toscaResourceName : " + + // buildAssertMessage(expectedToscaResourceName, + // resource.getToscaResourceName()), + // expectedToscaResourceName.equals(resource.getToscaResourceName())); + // + // RestResponse getResourceResponse = + // ResourceRestUtils.getResource(resource.getUniqueId()); + // Resource getResource = + // ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), + // Resource.class); + // assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, + // getResource.getCsarUUID()), + // expectedCsarUUID.equals(getResource.getCsarUUID())); + // assertTrue("toscaResourceName : " + + // buildAssertMessage(expectedToscaResourceName, + // getResource.getToscaResourceName()), + // expectedToscaResourceName.equals(getResource.getToscaResourceName())); + + } + + private static String getGroupType() { + return "org.openecomp.groups.VfModule"; + } +*/ + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java new file mode 100644 index 0000000000..46948d8f5b --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java @@ -0,0 +1,86 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.IOException; +import java.text.ParseException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.utils.DistributionUtils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +public class DistributionValidationUtils { + + public static Map verifyDistributedArtifactDownloadUsingDB(String distributionID, Map expectedArtifactsMapOfDistributedService, List distributionStatusEnumList) throws Exception { + + String action = "DStatus"; + int timer = 0; + int timeWaitPerArtifcat = 3; + if(expectedArtifactsMapOfDistributedService.size() != 0){ + timer = (expectedArtifactsMapOfDistributedService.size()/10*15 + expectedArtifactsMapOfDistributedService.size() * timeWaitPerArtifcat * distributionStatusEnumList.size() + 30) * 1000 ; + } + for (String distributionStatusList : distributionStatusEnumList){ + for (Entry url : expectedArtifactsMapOfDistributedService.entrySet()){ + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionID); + body.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url.getValue()); + body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, distributionStatusList); + Map actualAuditRecord = new HashMap(); + actualAuditRecord = AuditValidationUtils.retrieveAuditMessagesByPattern(action, body, true); + while (timer != 0) { + if(actualAuditRecord.size() == 0 ){ + Thread.sleep(1000); + actualAuditRecord = AuditValidationUtils.retrieveAuditMessagesByPattern(action, body, true); + timer-=1000; + if(timer == 0 && actualAuditRecord.size() == 0){ + assertNotNull("audit record did not found in DB for artifact url: " + url.getValue(), null); + } + }else{ + timer = timer - timeWaitPerArtifcat * 1000; + break; + } + + } + } + } + return null; + } + + public static void validateDistributedArtifactsByAudit(Service service, List distributionStatusList) throws Exception, IOException, ParseException { + String distributionID; + AtomicOperationUtils.distributeService(service, true); + distributionID = DistributionUtils.getLatestServiceDistributionObject(service).getDistributionID(); + if(distributionID != null){ + Map expectedArtifactsMapOfDistributedService = DistributionUtils.getArtifactsMapOfDistributedService(service); + DistributionValidationUtils.verifyDistributedArtifactDownloadUsingDB(distributionID, expectedArtifactsMapOfDistributedService, distributionStatusList); + } + else{ + assertNotNull("distributionID is null", distributionID); + } + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java new file mode 100644 index 0000000000..b79e4c63fc --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java @@ -0,0 +1,120 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import org.yaml.snakeyaml.Yaml; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.ExceptionEnumType; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ErrorValidationUtils { + static Logger logger = LoggerFactory.getLogger(ErrorValidationUtils.class.getName()); + + public static void checkBodyResponseOnError(String errorType, List variables, String actualResponse) + throws FileNotFoundException, JSONException { + + ErrorInfo errorInfo = parseErrorConfigYaml(errorType); + JSONObject expectedResponseBody = null; + if (errorInfo.getMessageId() != null) { + if (errorInfo.getMessageId().contains("SVC")) { + expectedResponseBody = restExceptionFormatBuilder(errorInfo.getMessageId(), errorInfo.getMessage(), + variables, ExceptionEnumType.SERVICE_EXCEPTION.getValue()); + } else { + expectedResponseBody = restExceptionFormatBuilder(errorInfo.getMessageId(), errorInfo.getMessage(), + variables, ExceptionEnumType.POLICY_EXCPTION.getValue()); + } + } + actualResponse = actualResponse.replaceAll("\\n", ""); + logger.debug("actualResponse - {}", actualResponse); + logger.debug("expectedResponseBody - {}", expectedResponseBody); + assertEquals(expectedResponseBody, new JSONObject(actualResponse)); + } + + public static String checkUIResponseOnError(String errorType) + throws FileNotFoundException, JSONException { + + ErrorInfo errorInfo = parseErrorConfigYaml(errorType); + String messageId = errorInfo.getMessageId(); + + return messageId; + } + + public static JSONObject restExceptionFormatBuilder(String messageId, String text, List variables, + String type) { + + JSONObject simpleElements = new JSONObject(); + JSONObject exceptionType = new JSONObject(); + JSONObject requestError = new JSONObject(); + + try { + simpleElements.put("messageId", messageId); + simpleElements.put("text", text); + simpleElements.put("variables", variables); + exceptionType.put(type, simpleElements); + requestError.put("requestError", exceptionType); + + } catch (JSONException e) { + e.printStackTrace(); + } + + return requestError; + + } + + public static ErrorInfo parseErrorConfigYaml(String error) throws FileNotFoundException { + Yaml yaml = new Yaml(); + ErrorInfo errInfo = null; + Config config = Utils.getConfig(); + String errorConfigurationFile = config.getErrorConfigurationFile(); + File file = new File(errorConfigurationFile); + // File file = new + // File("../catalog-be/src/main/resources/config/error-configuration.yaml"); + InputStream inputStream = new FileInputStream(file); + Map map = (Map) yaml.load(inputStream); + // System.out.println(map.get("errors")); + @SuppressWarnings("unchecked") + Map errorMap = (Map) map.get("errors"); + @SuppressWarnings("unchecked") + Map errorInfo = (Map) errorMap.get(error); + + String message = (String) errorInfo.get("message"); + String messageId = (String) errorInfo.get("messageId"); + int code = (Integer) errorInfo.get("code"); + errInfo = new ErrorInfo(code, message, messageId); + + return errInfo; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java new file mode 100644 index 0000000000..ba5114c1bc --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java @@ -0,0 +1,239 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.log4j.Logger; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest.ComponentOperationEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +public class ProductValidationUtils { + + static Logger logger = Logger.getLogger(ProductValidationUtils.class.getName()); + + public static void compareExpectedAndActualProducts(Product expectedProduct, Product actualProduct) { + compareExpectedAndActualProducts(expectedProduct, actualProduct, null); + } + + public static void compareExpectedAndActualProducts(Product expectedProduct, Product actualProduct, + ComponentOperationEnum operation) { + + assertEquals(expectedProduct.getName(), actualProduct.getName()); + assertEquals(expectedProduct.getFullName(), actualProduct.getFullName()); + assertEquals(expectedProduct.getDescription(), actualProduct.getDescription()); + + List expectedContacts = expectedProduct.getContacts(); + List actualContacts = actualProduct.getContacts(); + assertTrue( + "Expected contacts:" + Arrays.toString(expectedContacts.toArray()) + ", actual contacts:" + + Arrays.toString(actualContacts.toArray()), + expectedContacts.size() == actualContacts.size() && expectedContacts.containsAll(actualContacts) + && actualContacts.containsAll(expectedContacts)); + + List expectedTags = expectedProduct.getTags(); + List actualTags = actualProduct.getTags(); + assertTrue( + "Expected tags:" + Arrays.toString(expectedTags.toArray()) + ", actual tags:" + + Arrays.toString(actualTags.toArray()), + expectedTags.size() == actualTags.size() && expectedTags.containsAll(actualTags) + && actualTags.containsAll(expectedTags)); + + assertEquals(expectedProduct.getLifecycleState(), actualProduct.getLifecycleState()); + assertEquals(expectedProduct.getVersion(), actualProduct.getVersion()); + assertEquals(expectedProduct.isHighestVersion(), actualProduct.isHighestVersion()); + assertEquals(expectedProduct.getNormalizedName(), actualProduct.getNormalizedName()); + + compareCategories(expectedProduct, actualProduct); + assertEquals(expectedProduct.getLastUpdaterUserId(), actualProduct.getLastUpdaterUserId()); + if (operation != null) { + assertEquals(expectedProduct.getCreatorUserId(), actualProduct.getCreatorUserId()); + } + + Long lastUpdateDate = actualProduct.getLastUpdateDate(); + Long creationDate = actualProduct.getCreationDate(); + Map allVersions = actualProduct.getAllVersions(); + + if (operation != null) { + if (operation == ComponentOperationEnum.UPDATE_COMPONENT + || operation == ComponentOperationEnum.CHANGE_STATE_CHECKOUT + || operation == ComponentOperationEnum.CHANGE_STATE_CHECKIN + || operation == ComponentOperationEnum.CHANGE_STATE_UNDO_CHECKOUT) { + assertTrue("Last update date:" + lastUpdateDate + ", creation date: " + creationDate, + lastUpdateDate > 0 && creationDate > 0 && lastUpdateDate > creationDate); + } else { + assertTrue("Last update date:" + lastUpdateDate + ", creation date: " + creationDate, + lastUpdateDate > 0 && lastUpdateDate.equals(creationDate)); + } + } + + // Check UUIDs + // If just created, no way to test the UUIDs themselves + // If updated, we expect the UUIDs of actual to match the expected + String uniqueId = actualProduct.getUniqueId(); + if (operation == ComponentOperationEnum.CREATE_COMPONENT) { + UUID.fromString(uniqueId); + UUID.fromString(actualProduct.getUUID()); + UUID.fromString(actualProduct.getInvariantUUID()); + assertTrue(allVersions.size() == 1); + assertTrue(allVersions.get("0.1").equals(uniqueId)); + } else { + if (operation == ComponentOperationEnum.CHANGE_STATE_CHECKOUT) { + assertFalse(expectedProduct.getUniqueId().equals(uniqueId)); + // Assigning the updated uniqueId to expected so that it can be + // passed to further logic + expectedProduct.setUniqueId(uniqueId); + } else if (operation != null) { + assertTrue(expectedProduct.getUniqueId().equals(uniqueId)); + } + assertEquals(expectedProduct.getUUID(), actualProduct.getUUID()); + assertEquals(expectedProduct.getInvariantUUID(), actualProduct.getInvariantUUID()); + } + } + + private static void compareCategories(Product expectedProduct, Product actualProduct) { + List expectedCategories = expectedProduct.getCategories(); + List actualCategories = actualProduct.getCategories(); + if (expectedCategories != null && actualCategories != null) { + int expSize = expectedCategories.size(); + int actSize = actualCategories.size(); + + assertTrue("Expected size:" + expSize + ", actual size:" + actSize, expSize == actSize); + + for (CategoryDefinition actualDefinition : actualCategories) { + int lastIndexOfCat = expectedCategories.lastIndexOf(actualDefinition); + assertTrue("Actual category " + actualDefinition + " not found in expected.", lastIndexOfCat != -1); + CategoryDefinition expectedDefinition = expectedCategories.get(lastIndexOfCat); + List actualSubcategories = actualDefinition.getSubcategories(); + List expectedSubcategories = expectedDefinition.getSubcategories(); + for (SubCategoryDefinition actualSub : actualSubcategories) { + lastIndexOfCat = expectedSubcategories.lastIndexOf(actualSub); + assertTrue("Actual subcategory " + actualSub + " not found in expected.", lastIndexOfCat != -1); + SubCategoryDefinition expectedSub = expectedSubcategories.get(lastIndexOfCat); + List actualGroupings = actualSub.getGroupings(); + List expectedGroupings = expectedSub.getGroupings(); + for (GroupingDefinition actualGrouping : actualGroupings) { + lastIndexOfCat = expectedGroupings.lastIndexOf(actualGrouping); + assertTrue("Actual grouping " + actualSub + " not found in expected.", lastIndexOfCat != -1); + } + } + } + + for (CategoryDefinition expectedDefinition : expectedCategories) { + int lastIndexOfCat = actualCategories.lastIndexOf(expectedDefinition); + assertTrue("Expected category " + expectedDefinition + " not found in actual.", lastIndexOfCat != -1); + CategoryDefinition actualDefinition = actualCategories.get(lastIndexOfCat); + List actualSubcategories = actualDefinition.getSubcategories(); + List expectedSubcategories = expectedDefinition.getSubcategories(); + for (SubCategoryDefinition expectedSub : expectedSubcategories) { + lastIndexOfCat = actualSubcategories.lastIndexOf(expectedSub); + assertTrue("Expected subcategory " + expectedSub + " not found in actual.", lastIndexOfCat != -1); + SubCategoryDefinition actualSub = actualSubcategories.get(lastIndexOfCat); + List actualGroupings = actualSub.getGroupings(); + List expectedGroupings = expectedSub.getGroupings(); + for (GroupingDefinition expectedGrouping : expectedGroupings) { + lastIndexOfCat = actualGroupings.lastIndexOf(expectedGrouping); + assertTrue("Expected grouping " + expectedGrouping + " not found in actual.", + lastIndexOfCat != -1); + } + } + } + } + } + + public static void verifyProductsNotExistInUserFollowedPage(User user, Product... nonExpectedProducts) + throws Exception { + String component = "products"; + Boolean isExist; + Product nonExpectedProduct; + RestResponse getFollowedPage = ProductRestUtils.getFollowed(user.getUserId()); + JSONArray followedProductes = getListArrayFromRestResponse(getFollowedPage, component); + if (followedProductes != null) { // if any product exist in followed + // page + for (int i = 0; i < nonExpectedProducts.length; i++) { + nonExpectedProduct = nonExpectedProducts[i]; + isExist = false; + for (int k = 0; k < followedProductes.size(); k++) { + JSONObject jobject = (JSONObject) followedProductes.get(k); + if (jobject.get("uuid").toString().equals(nonExpectedProduct.getUUID())) { + isExist = true; + k = followedProductes.size(); + } + } + assertFalse(isExist); + } + } + + } + + public static void checkUserFollowedPage(User user, Product... expectedProducts) throws Exception { + String component = "products"; + Boolean isExist; + Product expectedProduct; + RestResponse getFollowedPage = ProductRestUtils.getFollowed(user.getUserId()); + JSONArray followedProductes = getListArrayFromRestResponse(getFollowedPage, component); + assertTrue("check if any followedProductes received ", followedProductes != null); + assertTrue("check if any expectedProducts and followedProductes are the same size", + expectedProducts.length == followedProductes.size()); + for (int i = 0; i < expectedProducts.length; i++) { + expectedProduct = expectedProducts[i]; + isExist = false; + for (int k = 0; k < followedProductes.size(); k++) { + JSONObject jobject = (JSONObject) followedProductes.get(k); + // if(jobject.get("uuid").toString().equals(expectedProduct.getUUID())) + if (jobject.get("uniqueId").toString().equals(expectedProduct.getUniqueId())) { + + String productString = jobject.toJSONString(); + Product actualProduct = ResponseParser.parseToObjectUsingMapper(productString, Product.class); + ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, null); + isExist = true; + k = followedProductes.size(); + } + } + assertTrue(isExist); + } + } + + private static JSONArray getListArrayFromRestResponse(RestResponse restResponse, String lst) { + String json = restResponse.getResponse(); + JSONObject jsonResp = (JSONObject) JSONValue.parse(json); + JSONArray resources = (JSONArray) jsonResp.get(lst); + return resources; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java new file mode 100644 index 0000000000..07f2ef8188 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java @@ -0,0 +1,358 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +import com.google.gson.Gson; + +public class ResourceValidationUtils { + + public static void validateResourceReqVsResp(ResourceReqDetails resourceDetails, + ResourceRespJavaObject resourceRespJavaObject) { + + String expected; + + expected = resourceDetails.getDescription(); + assertEquals("resource description - ", expected, resourceRespJavaObject.getDescription()); + + expected = resourceDetails.getVendorName(); + assertEquals("resource vendorName - ", expected, resourceRespJavaObject.getVendorName()); + + expected = resourceDetails.getVendorRelease(); + assertEquals("resource vendorReleaseName - ", expected, resourceRespJavaObject.getVendorRelease()); + + expected = resourceDetails.getContactId(); + assertEquals("resource contactId - ", expected, resourceRespJavaObject.getContactId()); + + } + + public static void validateResourceReqVsResp(ResourceReqDetails resourceDetails, Resource resourceRespJavaObject) { + + String expected; + + expected = resourceDetails.getDescription(); + assertEquals("resource description - ", expected, resourceRespJavaObject.getDescription()); + + expected = resourceDetails.getVendorName(); + assertEquals("resource vendorName - ", expected, resourceRespJavaObject.getVendorName()); + + expected = resourceDetails.getVendorRelease(); + assertEquals("resource vendorReleaseName - ", expected, resourceRespJavaObject.getVendorRelease()); + + expected = resourceDetails.getContactId(); + assertEquals("resource contactId - ", expected, resourceRespJavaObject.getContactId()); + + // Validating deduplication of tags + List expectedTags = resourceDetails.getTags(); + if (expectedTags != null) { + Set hs = new LinkedHashSet<>(expectedTags); + expectedTags.clear(); + expectedTags.addAll(hs); + List receivedTags = resourceRespJavaObject.getTags(); + assertEquals("resource tags - ", expectedTags, receivedTags); + } + + } + + public static void validateModelObjects(Resource expected, Resource actual) throws Exception { + + compareElements(expected.getUniqueId(), actual.getUniqueId()); + compareElements(expected.getName(), actual.getName()); + compareElements(expected.getVersion(), actual.getVersion()); + compareElements(expected.getCreatorUserId(), actual.getCreatorUserId()); + compareElements(expected.getCreatorFullName(), actual.getCreatorFullName()); + compareElements(expected.getLastUpdaterUserId(), actual.getLastUpdaterUserId()); + compareElements(expected.getLastUpdaterFullName(), actual.getLastUpdaterFullName()); + compareElements(expected.getCreatorFullName(), actual.getCreatorFullName()); + compareElements(expected.getCreationDate(), actual.getCreationDate()); + compareElements(expected.getLastUpdateDate(), actual.getLastUpdateDate()); + compareElements(expected.getDescription(), actual.getDescription()); + compareElements(expected.getIcon(), actual.getIcon()); + compareElements(expected.getLastUpdateDate(), actual.getLastUpdateDate()); + // TODO compare tags + compareElements(expected.getCategories(), actual.getCategories()); + compareElements(expected.getLifecycleState(), actual.getLifecycleState()); + compareElements(expected.getVendorName(), actual.getVendorName()); + compareElements(expected.getVendorRelease(), actual.getVendorRelease()); + compareElements(expected.getContactId(), actual.getContactId()); + compareElements(expected.getUUID(), actual.getUUID()); + compareElements(expected.getVersion(), actual.getVersion()); + + } + + public static void validateResp(RestResponse restResponse, ResourceRespJavaObject resourceRespJavaObject) + throws Exception { + + Gson gson = new Gson(); + String response = restResponse.getResponse(); + + validateResp(response, resourceRespJavaObject, gson); + + } + + public static void validateResp(String response, ResourceRespJavaObject resourceRespJavaObject, Gson gson) { + + Map map = new HashMap(); + map = (Map) gson.fromJson(response, map.getClass()); + + // De-duplicating the tags list for comparison + List tags = resourceRespJavaObject.getTags(); + if (tags != null) { + Set hs = new LinkedHashSet<>(tags); + tags = new ArrayList(hs); + resourceRespJavaObject.setTags(tags); + tags = new ArrayList(hs); + resourceRespJavaObject.setTags(tags); + } + + validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceRespJavaObject.getName()); + validateField(map, RespJsonKeysEnum.RESOURCE_DESC.getRespJsonKeyName(), + resourceRespJavaObject.getDescription()); + // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(), + // resourceRespJavaObject.getCategories()); + validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), resourceRespJavaObject.getVendorName()); + validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(), + resourceRespJavaObject.getVendorRelease()); + validateField(map, RespJsonKeysEnum.CONTACT_ID.getRespJsonKeyName(), resourceRespJavaObject.getContactId()); + validateField(map, RespJsonKeysEnum.ICON.getRespJsonKeyName(), resourceRespJavaObject.getIcon()); + validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(), + Boolean.valueOf(resourceRespJavaObject.getAbstractt())); + validateField(map, RespJsonKeysEnum.HIGHEST_VERSION.getRespJsonKeyName(), + Boolean.valueOf(resourceRespJavaObject.getIsHighestVersion())); + validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), resourceRespJavaObject.getUniqueId()); + validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceRespJavaObject.getVersion()); + validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(), + resourceRespJavaObject.getLifecycleState()); + validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), tags); + validateField(map, RespJsonKeysEnum.CREATOR_ATT_UID.getRespJsonKeyName(), + resourceRespJavaObject.getCreatorUserId()); + validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(), + resourceRespJavaObject.getCreatorFullName()); + validateField(map, RespJsonKeysEnum.LAST_UPDATER_ATT_UID.getRespJsonKeyName(), + resourceRespJavaObject.getLastUpdaterUserId()); + validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(), + resourceRespJavaObject.getLastUpdaterFullName()); + validateField(map, RespJsonKeysEnum.COST.getRespJsonKeyName(), resourceRespJavaObject.getCost()); + validateField(map, RespJsonKeysEnum.LICENSE_TYPE.getRespJsonKeyName(), resourceRespJavaObject.getLicenseType()); + validateField(map, RespJsonKeysEnum.RESOURCE_TYPE.getRespJsonKeyName(), + resourceRespJavaObject.getResourceType().toString()); + if (resourceRespJavaObject.getResourceType().equals("VF")) { + validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), null); + } else { + validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), + resourceRespJavaObject.getDerivedFrom()); + } + + validateCategories(resourceRespJavaObject, map); + + String uuid = ResponseParser.getValueFromJsonResponse(response, RespJsonKeysEnum.UUID.getRespJsonKeyName()); + assertTrue("UUID is empty", uuid != null && !uuid.isEmpty()); + } + + private static void validateCategories(ResourceRespJavaObject resourceRespJavaObject, Map map) { + assertTrue(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName() + " is missing", + map.containsKey(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName())); + Object foundValue = map.get(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName()); + List> foundList = (List>) foundValue; + List excpectedList = resourceRespJavaObject.getCategories(); + + assertTrue(foundList.size() == excpectedList.size()); + for (int i = 0; i < foundList.size(); i++) { + CategoryDefinition expCat = excpectedList.get(i); + Map foun = foundList.get(i); + assertTrue("expected " + expCat.getName() + " not equal to actual " + foundValue, + foun.get("name").equals(expCat.getName())); + } + } + + public static void validateField(Map map, String jsonField, Object expectedValue) { + if (expectedValue == null) { + assertTrue(jsonField + " is expected to be null", !map.containsKey(jsonField)); + } else { + assertTrue(jsonField + " is missing", map.containsKey(jsonField)); + Object foundValue = map.get(jsonField); + compareElements(expectedValue, foundValue); + } + } + + public static void compareElements(Object expectedValue, Object foundValue) { + if (expectedValue instanceof String) { + assertTrue(foundValue instanceof String); + assertTrue("expected " + expectedValue + " not equal to actual " + foundValue, + foundValue.equals(expectedValue)); + } + /* + * else if( expectedValue instanceof Number){ assertTrue(foundValue + * instanceof Number); assertTrue(foundValue == expectedValue); } + */ + else if (expectedValue instanceof Boolean) { + assertTrue(foundValue instanceof Boolean); + assertTrue(foundValue == expectedValue); + } else if (expectedValue instanceof Map) { + assertTrue(foundValue instanceof Map); + Map foundMap = (Map) foundValue; + Map excpectedMap = (Map) expectedValue; + assertTrue(foundMap.size() == excpectedMap.size()); + Iterator foundkeyItr = foundMap.keySet().iterator(); + while (foundkeyItr.hasNext()) { + String foundKey = foundkeyItr.next(); + assertTrue(excpectedMap.containsKey(foundKey)); + compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey)); + } + + } else if (expectedValue instanceof List) { + assertTrue(foundValue instanceof List); + List foundList = (List) foundValue; + List excpectedList = (List) expectedValue; + assertTrue(foundList.size() == excpectedList.size()); + for (int i = 0; i < foundList.size(); i++) { + compareElements(excpectedList.get(i), foundList.get(i)); + } + + } else { + assertTrue(foundValue.equals(expectedValue)); + } + } + + public static boolean validateUuidAfterChangingStatus(String oldUuid, String newUuid) { + return oldUuid.equals(newUuid); + + } + + public static void validateRespArt(RestResponse restResponse, ResourceRespJavaObject resourceRespJavaObject, + String interfaze) throws Exception { + + Gson gson = new Gson(); + String response = restResponse.getResponse(); + + Map map = new HashMap(); + map = (Map) gson.fromJson(response, map.getClass()); + + Resource resource = gson.fromJson(response, Resource.class); + + Map artifacts = resource.getArtifacts(); + Map interfaces = null; + + if (interfaze != null) { + interfaces = resource.getInterfaces(); + Map operation = interfaces.get(interfaze).getOperationsMap(); + // operation.get("configure").getUniqueId(); + } + + validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceRespJavaObject.getName()); + validateField(map, RespJsonKeysEnum.RESOURCE_DESC.getRespJsonKeyName(), + resourceRespJavaObject.getDescription()); + // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(), + // resourceRespJavaObject.getCategories()); + validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), resourceRespJavaObject.getDerivedFrom()); + validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), resourceRespJavaObject.getVendorName()); + validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(), + resourceRespJavaObject.getVendorRelease()); + validateField(map, RespJsonKeysEnum.CONTACT_ID.getRespJsonKeyName(), resourceRespJavaObject.getContactId()); + validateField(map, RespJsonKeysEnum.ICON.getRespJsonKeyName(), resourceRespJavaObject.getIcon()); + validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(), + Boolean.valueOf(resourceRespJavaObject.getAbstractt())); + validateField(map, RespJsonKeysEnum.HIGHEST_VERSION.getRespJsonKeyName(), + Boolean.valueOf(resourceRespJavaObject.getIsHighestVersion())); + validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), resourceRespJavaObject.getUniqueId()); + validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceRespJavaObject.getVersion()); + validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(), + resourceRespJavaObject.getLifecycleState()); + validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), resourceRespJavaObject.getTags()); + validateField(map, RespJsonKeysEnum.CREATOR_ATT_UID.getRespJsonKeyName(), + resourceRespJavaObject.getCreatorUserId()); + validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(), + resourceRespJavaObject.getCreatorFullName()); + validateField(map, RespJsonKeysEnum.LAST_UPDATER_ATT_UID.getRespJsonKeyName(), + resourceRespJavaObject.getLastUpdaterUserId()); + validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(), + resourceRespJavaObject.getLastUpdaterFullName()); + + // validate number of artifacts + if (resourceRespJavaObject.getArtifacts() != null) { + + // assertEquals("check number of artifacts", + // resourceRespJavaObject.getArtifacts().size(), artifacts.size()); + int iterNum = -1; + ArrayList myArtifacats = new ArrayList(); + Iterator it = artifacts.entrySet().iterator(); + while (it.hasNext()) { + iterNum++; + Map.Entry pair = (Map.Entry) it.next(); + // System.out.println(pair.getKey() + " = " + pair.getValue()); + ArtifactDefinition myArtifact = artifacts.get(pair.getKey()); + myArtifacats.add(myArtifact.getEsId()); + it.remove(); // avoids a ConcurrentModificationException + } + // assertTrue("check service contains + // artifacts",myArtifacats.containsAll(resourceRespJavaObject.getArtifacts())); + } + + // validate number of interfaces: + + if (interfaze != null) { + assertEquals("check number of interfaces", resourceRespJavaObject.getInterfaces().size(), + interfaces.size()); + } + + } + + public static boolean validateResourceIsAbstartct(List resourceList, Boolean bool) { + if (resourceList != null && resourceList.size() > 0) { + for (Resource resource : resourceList) { + if (resource.isAbstract().equals(bool)) + continue; + else + return false; + } + } else + return false; + return true; + } + + public static void validateResourceVersion(Resource resource, String expectedVersion) { + if (resource != null && !resource.equals("")) { + assertTrue("expected resource version is: " + expectedVersion + ", but actual is: " + resource.getVersion(), + resource.getVersion().equals(expectedVersion)); + } + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java new file mode 100644 index 0000000000..a7c7b7d34e --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java @@ -0,0 +1,130 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertEquals; +import java.util.LinkedHashSet; +import java.util.List; +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.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +public class ServiceValidationUtils { + + public static void validateServiceResponseMetaData(ServiceReqDetails serviceDetails, Service service, User user, + LifecycleStateEnum lifecycleState) { + validateServiceResponseMetaData(serviceDetails, service, user, user, lifecycleState); + } + + public static void validateServiceResponseMetaData(ServiceReqDetails expectedService, Service service, + User creatorUser, User updaterUser, LifecycleStateEnum lifeCycleState) { + List expectedTags = expectedService.getTags(); + expectedTags.add(expectedService.getName()); + List receivedTags = service.getTags(); + if (expectedTags != null) { + Set hs = new LinkedHashSet<>(expectedTags); + expectedTags.clear(); + expectedTags.addAll(hs); + } + + assertEquals("Check service name on response after create service", expectedService.getName(), + service.getName()); + // check size of list + assertEquals("Check only 1 category returned on response after create service", 1, + expectedService.getCategories().size()); + assertEquals("Check service name on response after create service", expectedService.getName(), + service.getName()); + assertEquals("Check categories on response after create service", + expectedService.getCategories().get(0).getName(), service.getCategories().get(0).getName()); + assertEquals("Check tag list on response after create service", expectedTags, receivedTags); + assertEquals("Check description on response after create service", expectedService.getDescription(), + service.getDescription()); + // assertEquals("Check vendor name on response after create service", + // expectedService.getVendorName(), service.getVendorName()); + // assertEquals("Check vendor release on response after create service", + // expectedService.getVendorRelease(), service.getVendorRelease()); + assertEquals("Check attContant name on response after create service", + expectedService.getContactId().toLowerCase(), service.getContactId()); + assertEquals("Check icon name on response after create service", expectedService.getIcon(), service.getIcon()); + assertEquals("Check LastUpdaterUserId after create service", updaterUser.getUserId(), + service.getLastUpdaterUserId()); + assertEquals("Check LastUpdaterName after create service", + updaterUser.getFirstName() + " " + updaterUser.getLastName(), service.getLastUpdaterFullName()); + assertEquals("Check CreatorUserId after create service", creatorUser.getUserId(), service.getCreatorUserId()); + assertEquals("Check CreatorName after create service", + creatorUser.getFirstName() + " " + creatorUser.getLastName(), service.getCreatorFullName()); + assertEquals("Check version after create service", expectedService.getVersion(), service.getVersion()); + // assertEquals("Check UniqueId after create service", SERVICE_PREFIX + + // serviceDetails.getServiceName().toLowerCase()+"." + + // serviceBaseVersion, service.getUniqueId()); + assertFalse("Check uuid after create service", service.getUUID().isEmpty()); + + // assertTrue("check creation date after create service", + // service.getCreationDate() != null); + // assertTrue("check update date after create service", + // service.getLastUpdateDate() != null); + + if (lifeCycleState != null) + assertEquals("Check LifecycleState after create service", lifeCycleState, service.getLifecycleState()); + else + assertEquals("Check LifecycleState after create service", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + service.getLifecycleState()); + } + + public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails, + String serviceVersion, User sdncUserDetails) { + + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); + + expectedResourceAuditJavaObject.setAction("Create"); + expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId()); + String userFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName(); + expectedResourceAuditJavaObject.setModifierName(userFirstLastName); + expectedResourceAuditJavaObject.setStatus("200"); + expectedResourceAuditJavaObject.setDesc("OK"); + expectedResourceAuditJavaObject.setResourceName(serviceReqDetails.getName()); + expectedResourceAuditJavaObject.setResourceType("Service"); + expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(serviceVersion) - 0.1f)); + expectedResourceAuditJavaObject.setCurrVersion(serviceVersion); + expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + expectedResourceAuditJavaObject.setComment(null); + + return expectedResourceAuditJavaObject; + + } + + public static void validateDistrubtionStatusValue(RestResponse response, + DistributionStatusEnum expectedDistributionValue) throws Exception { + String actualDistributionValue = ResponseParser.getValueFromJsonResponse(response.getResponse(), + "distributionStatus"); + assertEquals(expectedDistributionValue.name(), actualDistributionValue); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java new file mode 100644 index 0000000000..1fa20c19fd --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java @@ -0,0 +1,279 @@ +/*- + * ============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.ci.tests.utils.validation; + +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.users.AddUserAuditMessageInfo; +import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject; +import org.openecomp.sdc.ci.tests.utils.DbUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class UserValidationUtils { + public static void compareExpectedAndActualUsers(User expected, User actual) { + + String actualFirstName = actual.getFirstName(); + String expectedFirstName = expected.getFirstName(); + assertEquals("check user first name - ", expectedFirstName, actualFirstName); + + String actualLastName = actual.getLastName(); + String expectedLastName = expected.getLastName(); + assertEquals("check user last name - ", expectedLastName, actualLastName); + + String actualUserId = actual.getUserId(); + String expectedUserId = expected.getUserId(); + assertEquals("check user userId - ", expectedUserId, actualUserId); + + String actualEmail = actual.getEmail(); + String expectedEmail = expected.getEmail(); + assertEquals("check user email - ", expectedEmail, actualEmail); + + Long actualLastLoginTime = actual.getLastLoginTime(); + Long expectedLastLoginTime = expected.getLastLoginTime(); + assertEquals("check user last login time - ", expectedLastLoginTime, actualLastLoginTime); + + String actualRole = actual.getRole(); + if (expected.getRole() == null) { + String expectedRole = UserRoleEnum.DESIGNER.name(); + assertEquals("check user role - ", expectedRole, actualRole); + } else { + String expectedRole = expected.getRole(); + assertEquals("check user role - ", expectedRole, actualRole); + } + + UserStatusEnum actualStatus = expected.getStatus(); + UserStatusEnum expectedStatus = expected.getStatus(); + assertEquals("check user status - ", expectedStatus, actualStatus); + } + + public static void validateDeleteUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, + String responseCode, String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo) { + String action = "DeleteUser"; + validateUserAuditMessage(sdncUserDetails, sdncModifierDetails, responseCode, responseMessage, + addUserAuditMessageInfo, action); + + } + + private static void validateUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, String responseCode, + String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo, String expectedAction) { + + assertEquals("check audit action - ", expectedAction, addUserAuditMessageInfo.getACTION()); + + // String expectedModifierFirstLastName = + // sdncModifierDetails.getFirstName() + " " + + // sdncModifierDetails.getLastName(); + // assertEquals("check audit modifier name - ", + // expectedModifierFirstLastName, + // addUserAuditMessageInfo.getMODIFIER_NAME()); + String fullName = sdncModifierDetails.getFullName(); + if (sdncModifierDetails.getFullName().equals(" ")) { + fullName = ""; + } + String expectedModifierId = fullName + "(" + sdncModifierDetails.getUserId() + ")"; + assertEquals("check audit modifier uid - ", expectedModifierId, addUserAuditMessageInfo.getMODIFIER()); + + String expectedUserFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName(); + if (expectedUserFirstLastName.equals("null null")) { + expectedUserFirstLastName = ""; + } + + String email = (sdncUserDetails.getEmail() == null) ? "" : sdncUserDetails.getEmail(); + String role = (sdncUserDetails.getRole() == null) ? "DESIGNER" : sdncUserDetails.getRole(); + + String formatedUser = String.format("%s,%s,%s,%s", sdncUserDetails.getUserId(), expectedUserFirstLastName, + email, role); + + // + // String expectedUserFirstLastName = sdncUserDetails.getFirstName() + " + // " + sdncUserDetails.getLastName(); + // if (expectedUserFirstLastName.equals("null null")) { + // expectedUserFirstLastName = ""; + // } + // + // String expectedUserFirstLastName = ""; + // expectedUserFirstLastName += sdncUserDetails.getFirstName() == null ? + // "" : sdncUserDetails.getFirstName(); + // String lastName = sdncUserDetails.getLastName() == null ? "" : + // sdncUserDetails.getLastName(); + // if (expectedUserFirstLastName.isEmpty()) { + // expectedUserFirstLastName = lastName; + // } else { + // expectedUserFirstLastName += " " + lastName; + // } + + assertEquals("check audit user name - ", formatedUser, addUserAuditMessageInfo.getUSER()); + + // String expectedUserUid = sdncUserDetails.getUserId(); + // assertEquals("check audit user uid - ", expectedUserUid, + // addUserAuditMessageInfo.getUSER_UID()); + // + // String expectedUserEmail = sdncUserDetails.getEmail() == null ? "" : + // sdncUserDetails.getEmail(); + // //TODO: esofer check with Andrey. Audit return "" but in user we have + // null + // assertEquals("check audit user email - ", expectedUserEmail, + // addUserAuditMessageInfo.getUSER_EMAIL()); + // + // String expectedUserRole = sdncUserDetails.getRole(); + // if (expectedUserRole ==null){ + // expectedUserRole = "DESIGNER"; + // assertEquals("check audit user role - ", expectedUserRole, + // addUserAuditMessageInfo.getUSER_ROLE()); + // }else{ + // assertEquals("check audit user role - ", expectedUserRole, + // addUserAuditMessageInfo.getUSER_ROLE()); + // } + + String expectedUserResponseCode = responseCode; + assertEquals("check audit user response code - ", expectedUserResponseCode, + addUserAuditMessageInfo.getSTATUS()); + + String expectedUserResponseMessage = responseMessage; + assertEquals("check audit user response message - ", expectedUserResponseMessage, + addUserAuditMessageInfo.getDESC()); + + } + + public static void validateDataAgainstAuditDB_access(User sdncUserDetails, UserAuditJavaObject auditJavaObject, + RestResponse restResponse, ErrorInfo errorInfo, List variables) { + + validateAuditDataAgainstAuditDbInAccess(sdncUserDetails, auditJavaObject, restResponse, errorInfo, variables); + + } + + public static void validateAuditDataAgainstAuditDbInAccess(User sdncUserDetails, + UserAuditJavaObject auditJavaObject, RestResponse restResponse, ErrorInfo errorInfo, + List variables) { + + String expected; + + expected = "Access"; + assertEquals("ACTION- ", expected, auditJavaObject.getACTION()); + + if (sdncUserDetails.getFirstName() != StringUtils.EMPTY && sdncUserDetails.getLastName() != StringUtils.EMPTY) { + expected = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName(); + } else { + expected = StringUtils.EMPTY; + } + String formatedUser = String.format("%s(%s)", expected, sdncUserDetails.getUserId()); + assertTrue( + "check audit user: expected start with - " + formatedUser + " ,actual - " + auditJavaObject.getUSER(), + auditJavaObject.getUSER().startsWith(formatedUser)); + + expected = restResponse.getErrorCode().toString(); + assertEquals("check audit user status code - ", expected, auditJavaObject.getSTATUS()); + + if (restResponse.getErrorCode() == 200 || restResponse.getErrorCode() == 201) { + expected = errorInfo.getMessage(); + } else { + expected = AuditValidationUtils.buildAuditDescription(errorInfo, variables); + } + + assertEquals("check audit user desc - ", expected, auditJavaObject.getDESC()); + + // expected = sdncUserDetails.getUserId(); + // assertEquals(expected, auditJavaObject.getUSER()); + + } + + public static void validateUserDetailsOnResponse(User sdncUserDetails, String userDetailsOnResponse) { + + String actualFirstName = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "firstName"); + String expectedFirstName = sdncUserDetails.getFirstName(); + assertEquals("check user first name - ", expectedFirstName, actualFirstName); + + String actualLastName = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "lastName"); + String expectedLastName = sdncUserDetails.getLastName(); + assertEquals("check user last name - ", expectedLastName, actualLastName); + + String actualUserId = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "userId"); + String expectedUserId = sdncUserDetails.getUserId(); + assertEquals("check user userId - ", expectedUserId, actualUserId); + + String actualEmail = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "email"); + String expectedEmail = sdncUserDetails.getEmail(); + assertEquals("check user email - ", expectedEmail, actualEmail); + + String actualRole = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "role"); + if (sdncUserDetails.getRole() == null) { + String expectedRole = UserRoleEnum.DESIGNER.name(); + assertEquals("check user role - ", expectedRole, actualRole); + } else { + String expectedRole = sdncUserDetails.getRole(); + assertEquals("check user role - ", expectedRole, actualRole); + } + + String actualStatus = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "status"); + String expectedStatus = sdncUserDetails.getStatus().name(); + assertEquals("check user status - ", expectedStatus, actualStatus); + + } + + public static AddUserAuditMessageInfo getAddUserAuditMessage(String action) throws Exception { + + Gson gson = new Gson(); + String index = "auditingevents*"; + String type = "useradminevent"; + String pattern = "/_search?q=ACTION:\"" + action + "\""; + String auditingMessage = DbUtils.retrieveAuditMessagesByPattern(pattern); + // String auditingMessage = retrieveAuditMessageByIndexType(index, type, + // pattern); + JsonElement jElement = new JsonParser().parse(auditingMessage); + JsonObject jObject = jElement.getAsJsonObject(); + JsonObject hitsObject = (JsonObject) jObject.get("hits"); + JsonArray hitsArray = (JsonArray) hitsObject.get("hits"); + // for (int i = 0; i < hitsArray.size();){ + if (hitsArray != null) { + JsonObject jHitObject = (JsonObject) hitsArray.get(0); + JsonObject jSourceObject = (JsonObject) jHitObject.get("_source"); + AddUserAuditMessageInfo addUserAuditMessageInfo = new AddUserAuditMessageInfo(); + addUserAuditMessageInfo = gson.fromJson(jSourceObject, AddUserAuditMessageInfo.class); + return addUserAuditMessageInfo; + } + return null; + + } + + public static void validateAddUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, String responseCode, + String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo) { + + String action = "AddUser"; + validateUserAuditMessage(sdncUserDetails, sdncModifierDetails, responseCode, responseMessage, + addUserAuditMessageInfo, action); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java new file mode 100644 index 0000000000..0c19627bda --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java @@ -0,0 +1,111 @@ +/*- + * ============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.ci.tests.webSealAccess; + +public class NeoJavaObject { + + String userId; + String firstName; + String lastName; + String email; + String role; + String label; + String elementType; + + public NeoJavaObject(String userId, String firstName, String lastName, String email, String role, String label, + String elementType) { + super(); + this.userId = userId; + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.role = role; + this.label = label; + this.elementType = elementType; + } + + public NeoJavaObject() { + super(); + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getElementType() { + return elementType; + } + + public void setElementType(String elementType) { + this.elementType = elementType; + } + + @Override + public String toString() { + return "QueryUserNeo4jInfo [userId=" + userId + ", firstName=" + firstName + ", lastName=" + lastName + + ", email=" + email + ", role=" + role + ", label=" + label + ", elementType=" + elementType + "]"; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java new file mode 100644 index 0000000000..5ac70bf285 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java @@ -0,0 +1,1146 @@ +/*- + * ============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.externalApis; + +import static java.util.Arrays.asList; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.simple.parser.JSONParser; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +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.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.SearchCriteriaEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +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.AssetRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +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.ResourceRestUtilsExternalAPI; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.google.gson.Gson; + +import fj.data.Either; + +public class AssetLifeCycle extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName()); + protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K"; + protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk"; + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + protected static User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + protected Gson gson = new Gson(); + protected JSONParser jsonParser = new JSONParser(); + + + protected String serviceVersion; + protected ResourceReqDetails resourceDetails; + protected User sdncUserDetails; + protected ServiceReqDetails serviceDetails; + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_CREATED = 201; + public static final int STATUS_CODE_DELETE = 204; + public static final int STATUS_CODE_NOT_FOUND = 404; + public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204; + public static final int STATUS_CODE_SUCCESS_DELETE = 204; + public static final int STATUS_CODE_INVALID_CONTENT = 400; + public static final int STATUS_CODE_MISSING_DATA = 400; + public static final int STATUS_CODE_MISSING_INFORMATION = 403; + public static final int STATUS_CODE_RESTRICTED_ACCESS = 403; + public static final int STATUS_CODE_ALREADY_EXISTS = 409; + public static final int STATUS_CODE_RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT = 400; + public static final int STATUS_CODE_MISSING_COMPONENT_NAME = 400; + public static final int STATUS_CODE_UNSUPPORTED_ERROR = 400; + public static final int STATUS_CODE_IMPORT_SUCCESS = 201; + public static final int STATUS_CODE_UPDATE_SUCCESS = 200; + public static final int RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_GET_SUCCESS = 200; + public static final int COMPONENT_IN_CHECKOUT_STATE = 403; + public static final int COMPONENT_ALREADY_CHECKED_IN = 409; + public static final int COMPONENT_NOT_READY_FOR_CERTIFICATION = 403; + public static final int COMPONENT_SENT_FOR_CERTIFICATION = 403; + public static final int COMPONENT_IN_CERT_IN_PROGRESS_STATE = 403; + public static final int COMPONENT_ALREADY_CERTIFIED = 403; + + + + @Rule + public static TestName name = new TestName(); + + public AssetLifeCycle() { + super(name, AssetLifeCycle.class.getName()); + + } + + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test + public void createResourceCheckInThenCheckOut() throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VF.toString()); + + RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser); + defaultResource.setVersion(String.format("%.1f",0.1)); + ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class); + + restResponse = LifecycleRestUtils.checkInResource(parsedCreatedResponse.getUuid(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_CREATED, "Fail to check in."); + + Component resourceDetails = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, defaultResource.getName(), defaultResource.getVersion()); + Assert.assertEquals(resourceDetails.getLifecycleState().toString(), LifeCycleStatesEnum.CHECKIN.getComponentState().toString(), "Life cycle state not changed."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parsedCreatedResponse.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.RESOURCES); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + restResponse = LifecycleRestUtils.checkOutResource(parsedCreatedResponse.getUuid(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_CREATED, "Fail to check out."); + + resourceDetails = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, defaultResource.getName(), String.format("%.1f", Double.parseDouble(defaultResource.getVersion()) + 0.1)); + Assert.assertEquals(resourceDetails.getLifecycleState().toString(), LifeCycleStatesEnum.CHECKOUT.getComponentState().toString(), "Life cycle state not changed."); + + // auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parsedCreatedResponse.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setCurrVersion("0.2"); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test + public void createServiceCheckInThenCheckOut() throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + + RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_CREATED, "Fail to check in."); + + resourceDetails = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceDetails.getName(), resourceDetails.getVersion()); + Assert.assertEquals(resourceDetails.getLifecycleState().toString(), LifeCycleStatesEnum.CHECKIN.getComponentState().toString(), "Life cycle state not changed."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.SERVICES); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + restResponse = LifecycleRestUtils.checkOutService(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_CREATED, "Fail to check out."); + + resourceDetails = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceDetails.getName(), String.format("%.1f", Double.parseDouble(resourceDetails.getVersion()) + 0.1)); + Assert.assertEquals(resourceDetails.getLifecycleState().toString(), LifeCycleStatesEnum.CHECKOUT.getComponentState().toString(), "Life cycle state not changed."); + + // auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setCurrVersion("0.2"); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + @DataProvider(name="invalidAssetUUID") + public static Object[][] dataProviderInvalidAssetUUID() { + return new Object[][] { + {AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CHECKIN}, + {AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CHECKIN}, + + {AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CHECKOUT}, + {AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CHECKOUT}, + + {AssetTypeEnum.SERVICES, LifeCycleStatesEnum.CERTIFICATIONREQUEST}, + {AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.CERTIFICATIONREQUEST}, + + {AssetTypeEnum.SERVICES, LifeCycleStatesEnum.STARTCERTIFICATION}, + {AssetTypeEnum.RESOURCES, LifeCycleStatesEnum.STARTCERTIFICATION}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidAssetUUID") + public void invalidAssetUUID(AssetTypeEnum assetTypeEnum, LifeCycleStatesEnum lifeCycleStatesEnum) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String assetUUID = "InvalidAssetUUID"; + ErrorInfo errorInfo = null; + + RestResponse restResponse = null; + if(assetTypeEnum.equals(AssetTypeEnum.SERVICES)) { + + if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKIN)) { + restResponse = LifecycleRestUtils.checkInService(assetUUID, defaultUser); + } else if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKOUT)) { + restResponse = LifecycleRestUtils.checkOutService(assetUUID, defaultUser); + } else if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CERTIFICATIONREQUEST)) { + restResponse = LifecycleRestUtils.certificationRequestService(assetUUID, defaultUser); + } else if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.STARTCERTIFICATION)) { + restResponse = LifecycleRestUtils.startTestingService(assetUUID, defaultUser); + } + + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); + } else { + + if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKIN)) { + restResponse = LifecycleRestUtils.checkInResource(assetUUID, defaultUser); + } else if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKOUT)) { + restResponse = LifecycleRestUtils.checkOutResource(assetUUID, defaultUser); + } else if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CERTIFICATIONREQUEST)) { + restResponse = LifecycleRestUtils.certificationRequestResource(assetUUID, defaultUser); + } else if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.STARTCERTIFICATION)) { + restResponse = LifecycleRestUtils.startTestingResource(assetUUID, defaultUser); + } + + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()); + + } + Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_NOT_FOUND, "Asset found."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", assetTypeEnum.getValue().toLowerCase(), assetUUID, lifeCycleStatesEnum.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultInvalidChangeAssetLifeCycleExternalAPI(assetUUID, defaultUser, lifeCycleStatesEnum, assetTypeEnum); + + List variables = asList(assetUUID); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + @DataProvider(name="invalidUserCheckinForCheckedOutService") + public static Object[][] dataProviderInvalidUserCheckinForCheckedOutService() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckinForCheckedOutService") + public void invalidUserCheckinForCheckedOutService(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + + RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckinForCheckedInService") + public static Object[][] dataProviderInvalidUserCheckinForCheckedInService() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckinForCheckedInService") + public void invalidUserCheckinForCheckedInService(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckoutForCheckedOutService") + public static Object[][] dataProviderInvalidUserCheckoutForCheckedOutService() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckoutForCheckedOutService") + public void invalidUserCheckoutForCheckedOutService(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + + RestResponse restResponse = LifecycleRestUtils.checkOutService(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckoutForCheckedInService") + public static Object[][] dataProviderInvalidUserCheckoutForCheckedInService() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckoutForCheckedInService") + public void invalidUserCheckoutForCheckedInService(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + RestResponse restResponse = LifecycleRestUtils.checkOutService(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckinForCheckedOutResource") + public static Object[][] dataProviderInvalidUserCheckinForCheckedOutResource() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckinForCheckedOutResource") + public void invalidUserCheckinForCheckedOutResource(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + + RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckinForCheckedInResource") + public static Object[][] dataProviderInvalidUserCheckinForCheckedInResource() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckinForCheckedInResource") + public void invalidUserCheckinForCheckedInResource(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckoutForCheckedOutResource") + public static Object[][] dataProviderInvalidUserCheckoutForCheckedOutResource() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckoutForCheckedOutResource") + public void invalidUserCheckoutForCheckedOutResource(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + + RestResponse restResponse = LifecycleRestUtils.checkOutResource(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + @DataProvider(name="invalidUserCheckoutForCheckedInResource") + public static Object[][] dataProviderInvalidUserCheckoutForCheckedInResource() { + return new Object[][] { + {ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + // TODO: remove comment after talk with renana if it is defect or not +// {ElementFactory.getDefaultUser(UserRoleEnum.ADMIN)}, + {ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR)}, + {ElementFactory.getDefaultUser(UserRoleEnum.OPS)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1)}, + {ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1)}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidUserCheckoutForCheckedInResource") + public void invalidUserCheckoutForCheckedInResource(User defaultUser) throws Exception { + Component resourceDetails = null; + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + resourceDetails = createdComponent.left().value(); + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + RestResponse restResponse = LifecycleRestUtils.checkOutResource(resourceDetails.getUUID(), defaultUser); + Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setStatus("409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(""); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + + + @DataProvider(name="invalidStatesForService") + public static Object[][] dataProviderInvalidStatesForService() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CHECKED_IN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "409", ActionStatus.COMPONENT_ALREADY_CHECKED_IN, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CHECKOUT_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_IN_CHECKOUT_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_SENT_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, "403", ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, LifeCycleStatesEnum.CERTIFY, RESTRICTED_OPERATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, "409", ActionStatus.RESTRICTED_OPERATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CHECKIN, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidStatesForService") + public void invalidStatesForService(LifeCycleStatesEnum initState, LifeCycleStatesEnum targetState, int errorCode, + LifecycleStateEnum preState, LifecycleStateEnum currState, String status, + ActionStatus actionStatus, User user, User operationUser) throws Exception { + + if(initState.equals(LifeCycleStatesEnum.STARTCERTIFICATION) && targetState.equals(LifeCycleStatesEnum.CHECKIN)){ + throw new SkipException("Open bug DE270217"); + } + + getExtendTest().log(Status.INFO, String.format("initState: %s, targetState: %s, errorCode: %s," + + " preState: %s, currState: %s, status: %s, actionStatus: %s, user: %s, operationUser: %s", initState, targetState, errorCode, preState, + currState, status, actionStatus, user, operationUser)); + + + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, UserRoleEnum.DESIGNER, initState, true).getLeft(); + + RestResponse restResponse = null; + + if(targetState.equals(LifeCycleStatesEnum.CHECKOUT)) { + restResponse = LifecycleRestUtils.checkOutService(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.CHECKIN)) { + restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.CERTIFICATIONREQUEST)) { + restResponse = LifecycleRestUtils.certificationRequestService(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.STARTCERTIFICATION)) { + restResponse = LifecycleRestUtils.startTestingService(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.CERTIFY)) { + restResponse = LifecycleRestUtils.certifyService(resourceDetails.getUUID(), user); + } + + Assert.assertEquals(restResponse.getErrorCode(), (Integer)errorCode, "Expected that response code will be equal."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, user, targetState, AssetTypeEnum.SERVICES); + if(initState.equals(LifeCycleStatesEnum.CERTIFY)) { + expectedResourceAuditJavaObject.setCurrVersion("1.0"); + expectedResourceAuditJavaObject.setPrevVersion("1.0"); + } + expectedResourceAuditJavaObject.setPrevState(preState.toString()); + expectedResourceAuditJavaObject.setCurrState(currState.toString()); + expectedResourceAuditJavaObject.setStatus(status); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + List variables = null; + if(ActionStatus.RESTRICTED_OPERATION.equals(actionStatus)) { + variables = asList(""); + } else if(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION.equals(actionStatus)) { + variables = asList(resourceDetails.getName(), AssetTypeEnum.SERVICES.getCorrespondingComponent().toLowerCase()); + } else { + if(operationUser == null) { + variables = asList(resourceDetails.getName(), AssetTypeEnum.SERVICES.getCorrespondingComponent().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } else { + variables = asList(resourceDetails.getName(), AssetTypeEnum.SERVICES.getCorrespondingComponent().toLowerCase(), operationUser.getFirstName(), operationUser.getLastName(), operationUser.getUserId()); + } + + } + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + + + + + + + + + + + + + + @DataProvider(name="invalidStatesForResource") + public static Object[][] dataProviderInvalidStatesForResource() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CHECKED_IN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "409", ActionStatus.COMPONENT_ALREADY_CHECKED_IN, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CHECKOUT_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_IN_CHECKOUT_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_SENT_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, "403", ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, LifeCycleStatesEnum.CERTIFY, RESTRICTED_OPERATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, "409", ActionStatus.RESTRICTED_OPERATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CHECKIN, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + }; + } + + // US849997 - Story [BE]: External API for asset lifecycle - checkout + @Test(dataProvider="invalidStatesForResource") + public void invalidStatesForResource(LifeCycleStatesEnum initState, LifeCycleStatesEnum targetState, int errorCode, + LifecycleStateEnum preState, LifecycleStateEnum currState, String status, + ActionStatus actionStatus, User user, User operationUser) throws Exception { + getExtendTest().log(Status.INFO, String.format("initState: %s, targetState: %s, errorCode: %s," + + " preState: %s, currState: %s, status: %s, actionStatus: %s, user: %s, operationUser: %s", initState, targetState, errorCode, preState, + currState, status, actionStatus, user, operationUser)); + + if(initState.equals(LifeCycleStatesEnum.STARTCERTIFICATION) && targetState.equals(LifeCycleStatesEnum.CHECKIN)){ + throw new SkipException("Open bug DE270217"); + } + + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, UserRoleEnum.DESIGNER, initState, true).getLeft(); + + RestResponse restResponse = null; + + if(targetState.equals(LifeCycleStatesEnum.CHECKOUT)) { + restResponse = LifecycleRestUtils.checkOutResource(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.CHECKIN)) { + restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.CERTIFICATIONREQUEST)) { + restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.STARTCERTIFICATION)) { + restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), user); + } else if(targetState.equals(LifeCycleStatesEnum.CERTIFY)) { + restResponse = LifecycleRestUtils.certifyResource(resourceDetails.getUUID(), user); + } + + Assert.assertEquals(restResponse.getErrorCode(), (Integer)errorCode, "Expected that response code will be equal."); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, user, targetState, AssetTypeEnum.RESOURCES); + if(initState.equals(LifeCycleStatesEnum.CERTIFY)) { + expectedResourceAuditJavaObject.setCurrVersion("1.0"); + expectedResourceAuditJavaObject.setPrevVersion("1.0"); + } + expectedResourceAuditJavaObject.setPrevState(preState.toString()); + expectedResourceAuditJavaObject.setCurrState(currState.toString()); + expectedResourceAuditJavaObject.setStatus(status); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name()); + List variables = null; + if(ActionStatus.RESTRICTED_OPERATION.equals(actionStatus)) { + variables = asList(""); + } else if(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION.equals(actionStatus)) { + variables = asList(resourceDetails.getName(), AssetTypeEnum.RESOURCES.getCorrespondingComponent().toLowerCase()); + } else { + if(operationUser == null) { + variables = asList(resourceDetails.getName(), AssetTypeEnum.RESOURCES.getCorrespondingComponent().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } else { + variables = asList(resourceDetails.getName(), AssetTypeEnum.RESOURCES.getCorrespondingComponent().toLowerCase(), operationUser.getFirstName(), operationUser.getLastName(), operationUser.getUserId()); + } + + } + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + + + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing + @Test + public void BasicFlowForResourceSubmitForTestingStartTesting() throws Exception { + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Certification request + restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.CERTIFICATIONREQUEST.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CERTIFICATIONREQUEST, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.toString()); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + // Start testing + restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.STARTCERTIFICATION.getState())); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.READY_FOR_CERTIFICATION.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.toString()); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + // US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing + @Test + public void BasicFlowForServiceSubmitForTestingStartTesting() throws Exception { + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Certification request + restResponse = LifecycleRestUtils.certificationRequestService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.SERVICES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.CERTIFICATIONREQUEST.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CERTIFICATIONREQUEST, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.toString()); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + // Start testing + restResponse = LifecycleRestUtils.startTestingService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.SERVICES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.STARTCERTIFICATION.getState())); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.READY_FOR_CERTIFICATION.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.toString()); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + // US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing + @Test + public void specialCaseInvalidFlowForVfcmtSubmitForTesting() throws Exception { + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFCMT, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Certification request + restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.CERTIFICATIONREQUEST.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, defaultUser, LifeCycleStatesEnum.CERTIFICATIONREQUEST, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setStatus("400"); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID.name()); + List variables = asList(LifeCycleStatesEnum.CERTIFICATIONREQUEST.getState()); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + // US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing + @Test + public void specialCaseInvalidFlowForVfcmtStartTesting() throws Exception { + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFCMT, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Certification request + restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.STARTCERTIFICATION.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setStatus("400"); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID.name()); + List variables = asList(LifeCycleStatesEnum.STARTCERTIFICATION.getState()); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + + + // US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing + @Test + public void BasicFlowForResourceCertify() throws Exception { + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Certification request + restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Start testing + restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Certify + restResponse = LifecycleRestUtils.certifyResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.CERTIFY.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString()); + expectedResourceAuditJavaObject.setCurrVersion("1.0"); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + } + + // US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing + @Test + public void BasicFlowForServiceCertify() throws Exception { + Either createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + Component resourceDetails = createdComponent.left().value(); + RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Certification request + restResponse = LifecycleRestUtils.certificationRequestService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + + // Start testing + restResponse = LifecycleRestUtils.startTestingService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Certify + restResponse = LifecycleRestUtils.certifyService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.SERVICES.getValue().toLowerCase(), resourceDetails.getUUID(), LifeCycleStatesEnum.CERTIFY.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY, AssetTypeEnum.SERVICES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString()); + expectedResourceAuditJavaObject.setCurrVersion("1.0"); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + } + + + + + + + + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + @Test + public void theFlow() throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString()); + + // 1. Create VFCMT. + RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser); + BaseRestUtils.checkCreateResponse(restResponse); + ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class); + + // 2. Using search external API with resourceType=VFCMT to retrieve VFCMT. + restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), ResourceTypeEnum.VFCMT.toString()); + BaseRestUtils.checkSuccess(restResponse); + ResourceAssetStructure dataOutOfSearchResponseForResourceName = ResponseParser.getDataOutOfSearchExternalAPIResponseForResourceName(restResponse.getResponse(), parsedCreatedResponse.getName()); + Assert.assertEquals(parsedCreatedResponse.getUuid(), dataOutOfSearchResponseForResourceName.getUuid(), "Created resourceUUID not equal to search retrive resourceUUID."); + + // 3. Use getSpecificMetadata external API to receive full information of the VFCMT. + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, dataOutOfSearchResponseForResourceName.getUuid()); + BaseRestUtils.checkSuccess(assetResponse); + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + Assert.assertEquals(resourceAssetMetadata.getUuid(), parsedCreatedResponse.getUuid(), "Created resourceUUID not equal to getSpecificMetadata resourceUUID."); + + // 4. Upload artifact via upload artifact external API. + Component initComponentVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, parsedCreatedResponse.getName(), parsedCreatedResponse.getVersion()); + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "OTHER", true, false); + RestResponse uploadArtifactRestResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(initComponentVersion, defaultUser, artifactReqDetails); + BaseRestUtils.checkSuccess(uploadArtifactRestResponse); + ArtifactDefinition responseArtifact = ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse()); + initComponentVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, parsedCreatedResponse.getName(), parsedCreatedResponse.getVersion()); + + // 5. Update artifact via external API. + CRUDExternalAPI crudExternalAPI = new CRUDExternalAPI(); + crudExternalAPI.updateArtifactOnAssetViaExternalAPI(initComponentVersion, ComponentTypeEnum.RESOURCE, LifeCycleStatesEnum.CHECKOUT, "OTHER"); + + + // 6. Use external API to checkin the VFCMT. + RestResponse checkInRestResponse = LifecycleRestUtils.checkInResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(checkInRestResponse); + parsedCreatedResponse = gson.fromJson(checkInRestResponse.getResponse(), ResourceAssetStructure.class); + Assert.assertEquals(parsedCreatedResponse.getVersion(), "0.1", "Expect that version will not change."); + Assert.assertEquals(parsedCreatedResponse.getUuid(), initComponentVersion.getUUID(), "Expect that UUID will not change."); + Assert.assertEquals(parsedCreatedResponse.getInvariantUUID(), initComponentVersion.getInvariantUUID(), "Expected that invariantUUID will not change."); + + // Auditing verification + AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, initComponentVersion.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), initComponentVersion.getUUID(), LifeCycleStatesEnum.CHECKIN.getState())); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(initComponentVersion, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.RESOURCES); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + // 7. Then checkout the VFCMT via external API. + RestResponse checkOutRestResponse = LifecycleRestUtils.checkOutResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(checkOutRestResponse); + parsedCreatedResponse = gson.fromJson(checkOutRestResponse.getResponse(), ResourceAssetStructure.class); + Assert.assertEquals(parsedCreatedResponse.getVersion(), "0.2", "Expect that version will change to 0.2."); + Assert.assertEquals(parsedCreatedResponse.getUuid(), initComponentVersion.getUUID(), "Expect that UUID will not change."); + Assert.assertEquals(parsedCreatedResponse.getInvariantUUID(), initComponentVersion.getInvariantUUID(), "Expected that invariantUUID will not change."); + + // Auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, initComponentVersion.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), initComponentVersion.getUUID(), LifeCycleStatesEnum.CHECKOUT.getState())); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(initComponentVersion, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setCurrVersion("0.2"); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + // 8. The minor version must be incremented, the invariantUUID, and UUID must stay the same, the uniqueId should be changed, the artifacts from first version exists on the new version. + Component newComponentVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, parsedCreatedResponse.getName(), String.format("%.1f", Double.parseDouble(parsedCreatedResponse.getVersion()))); + Assert.assertEquals(newComponentVersion.getInvariantUUID(), initComponentVersion.getInvariantUUID(), "Expected that invariantUUID will not change."); + Assert.assertEquals(newComponentVersion.getUUID(), initComponentVersion.getUUID(), "Expected that UUID will not change."); + Assert.assertNotEquals(newComponentVersion.getUniqueId(), initComponentVersion.getUniqueId(), "Expected that uniqueId will change."); + Assert.assertTrue(newComponentVersion.getDeploymentArtifacts().keySet().contains(responseArtifact.getArtifactLabel()), "Expected that artifact from first version exists on the new version."); + + // 9. The previous version remains untouched, the highest version flag on the first version is false, all information (metadata / artifacts) are the same on the first version. + initComponentVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, parsedCreatedResponse.getName(), String.format("%.1f", Double.parseDouble("0.1"))); + Assert.assertEquals(initComponentVersion.isHighestVersion(), (Boolean)false, "Expected that highest version flag on first version is false."); + + // 10. Check in via external API. + checkInRestResponse = LifecycleRestUtils.checkInResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(checkInRestResponse); + parsedCreatedResponse = gson.fromJson(checkInRestResponse.getResponse(), ResourceAssetStructure.class); + Assert.assertEquals(parsedCreatedResponse.getVersion(), "0.2", "Expect that version will not change."); + Assert.assertEquals(parsedCreatedResponse.getUuid(), initComponentVersion.getUUID(), "Expect that UUID will not change."); + Assert.assertEquals(parsedCreatedResponse.getInvariantUUID(), initComponentVersion.getInvariantUUID(), "Expected that invariantUUID will not change."); + + // Auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, initComponentVersion.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), initComponentVersion.getUUID(), LifeCycleStatesEnum.CHECKIN.getState())); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(initComponentVersion, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrVersion("0.2"); + expectedResourceAuditJavaObject.setPrevVersion("0.2"); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + // 11. Certify via external API. + RestResponse certifyRestResponse = LifecycleRestUtils.certifyResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(certifyRestResponse); + parsedCreatedResponse = gson.fromJson(certifyRestResponse.getResponse(), ResourceAssetStructure.class); + Assert.assertEquals(parsedCreatedResponse.getVersion(), "1.0", "Expect that version will change to 1.0"); + Assert.assertEquals(parsedCreatedResponse.getUuid(), initComponentVersion.getUUID(), "Expect that UUID will not change."); + Assert.assertEquals(parsedCreatedResponse.getInvariantUUID(), initComponentVersion.getInvariantUUID(), "Expected that invariantUUID will not change."); + + // Auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, initComponentVersion.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), initComponentVersion.getUUID(), LifeCycleStatesEnum.CERTIFY.getState())); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(initComponentVersion, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFY, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString()); + expectedResourceAuditJavaObject.setCurrVersion("1.0"); + expectedResourceAuditJavaObject.setPrevVersion("0.2"); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + // 12. Check out via external API. + checkOutRestResponse = LifecycleRestUtils.checkOutResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(checkOutRestResponse); + parsedCreatedResponse = gson.fromJson(checkOutRestResponse.getResponse(), ResourceAssetStructure.class); + Assert.assertEquals(parsedCreatedResponse.getVersion(), "1.1", "Expect that version will change to 1.1"); + Assert.assertNotEquals(parsedCreatedResponse.getUuid(), initComponentVersion.getUUID(), "Expect that UUID will change."); + Assert.assertEquals(parsedCreatedResponse.getInvariantUUID(), initComponentVersion.getInvariantUUID(), "Expected that invariantUUID will not change."); + + // Auditing verification + body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, initComponentVersion.getName()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", AssetTypeEnum.RESOURCES.getValue().toLowerCase(), initComponentVersion.getUUID(), LifeCycleStatesEnum.CHECKOUT.getState())); + expectedResourceAuditJavaObject = ElementFactory.getDefaultChangeAssetLifeCycleExternalAPI(initComponentVersion, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT, AssetTypeEnum.RESOURCES); + expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFIED.toString()); + expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString()); + expectedResourceAuditJavaObject.setCurrVersion("1.1"); + expectedResourceAuditJavaObject.setPrevVersion("1.0"); + AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body); + + + } + + + + + + + + + + + + + + +} 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 new file mode 100644 index 0000000000..c3f9a723c2 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java @@ -0,0 +1,3528 @@ +/*- + * ============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.externalApis; + +import static java.util.Arrays.asList; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpResponseException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.util.EntityUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.SerializationConfig.Feature; +import org.codehaus.jackson.map.annotate.JsonSerialize; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +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.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactUiDownloadData; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.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.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +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.DistributionNotificationStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.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.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; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import fj.data.Either; + +public class CRUDExternalAPI extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName()); + protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K"; + protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk"; + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + protected Gson gson = new Gson(); + protected JSONParser jsonParser = new JSONParser(); + + protected String serviceVersion; + protected ResourceReqDetails resourceDetails; + protected User sdncUserDetails; + protected ServiceReqDetails serviceDetails; + + @Rule + public static TestName name = new TestName(); + + public CRUDExternalAPI() { + super(name, CRUDExternalAPI.class.getName()); + } + + @DataProvider(name="uploadArtifactOnVfcVlCpViaExternalAPI" , parallel=true) + public static Object[][] dataProviderUploadArtifactOnVfcVlCpViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP} + }; + } + + // External API + // Upload artifact on VFC, VL, CP via external API - happy flow + @Test(dataProvider="uploadArtifactOnVfcVlCpViaExternalAPI") + public void uploadArtifactOnVfcVlCpViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s, resourceTypeEnum: %s", chosenLifeCycleState, artifactType, resourceTypeEnum)); + uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, chosenLifeCycleState, artifactType, resourceTypeEnum); + } + + @DataProvider(name="uploadArtifactOnVFViaExternalAPI", parallel=true) + public static Object[][] dataProviderUploadArtifactOnVFViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_JSON"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE"}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_JSON"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CHECKIN, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_DOC"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CHECKIN, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE"}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKIN, "OTHER"}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_JSON"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_DOC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"} + }; + } + + // External API + // Upload artifact on VF via external API - happy flow + @Test(dataProvider="uploadArtifactOnVFViaExternalAPI") + public void uploadArtifactOnVFViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, chosenLifeCycleState, artifactType, null); + } + + + @DataProvider(name="uploadArtifactOnServiceViaExternalAPI" , parallel=true) + public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {LifeCycleStatesEnum.CHECKIN, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"} + }; + } + + + @Test(dataProvider="uploadArtifactOnServiceViaExternalAPI") + public void uploadArtifactOnServiceViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.SERVICE, chosenLifeCycleState, artifactType, null); + } + + + @DataProvider(name="uploadArtifactOnServiceViaExternalAPIIncludingDistribution", parallel=true) + public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPIIncludingDistribution() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + }; + } + + @Test(dataProvider="uploadArtifactOnServiceViaExternalAPIIncludingDistribution") + public void uploadArtifactOnServiceViaExternalAPIIncludingDistribution(LifeCycleStatesEnum chosenLifeCycleState, String artifactType) throws Exception { + if(true){ + throw new SkipException("Automated TC need repair."); + } + + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.SERVICE, chosenLifeCycleState, artifactType, null); + + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + if(config.getIsDistributionClientRunning()){ + List distributionStatusList = Arrays.asList(DistributionNotificationStatusEnum.DOWNLOAD_OK.toString(), DistributionNotificationStatusEnum.DEPLOY_OK.toString(), DistributionNotificationStatusEnum.NOTIFIED.toString()); + DistributionValidationUtils.validateDistributedArtifactsByAudit((Service)component, distributionStatusList); + } + } + + + // Happy flow - get chosen life cycle state, artifact type and asset type + // Create asset, upload artifact via external API + check audit & response code + // Download artifact via external API + check audit & response code + protected Component uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + Component component = null; + RestResponse restResponse; + int numberOfArtifact = 0; + + // get artifact data + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, false); + + // 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()); + } + } else { + component = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, chosenLifeCycleState, resourceTypeEnum); + + restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200); + numberOfArtifact = component.getDeploymentArtifacts().size() + 1; + } + + + + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + component = getNewerVersionOfComponent(component, chosenLifeCycleState); + + // Get list of deployment artifact + download them via external API + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact 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; + } + + // 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)); + + // Check response of external API + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API; + + Map 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); + expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName()); + 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; + } + + + + + protected Component getComponentWithResourceInstanceInTargetLifeCycleState(LifeCycleStatesEnum lifeCycleStatesEnum, ResourceTypeEnum resourceTypeEnum) throws Exception { + Component component; + if(resourceTypeEnum == ResourceTypeEnum.VF) { + component = getComponentInTargetLifeCycleState(ComponentTypeEnum.SERVICE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null); + + 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)) { + } + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, component, UserRoleEnum.DESIGNER, true, true).left().value(); + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, lifeCycleStatesEnum, true).getLeft(); + } else { + component = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null); + Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, resourceTypeEnum); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value(); + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, lifeCycleStatesEnum, true).getLeft(); + } + + + return component; + } + + + + + // 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); + + // Check response of external API + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API; + + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase()); + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails); + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body); + + return restResponse; + } + + + + // Check Component version (increase by one if not in checkout) + // Input: component, componentLifeCycleState + // for any LifeCycleState != checkout + // find component of version +0.1 + // 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 { + Component resourceDetails = null; + + if((!lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKOUT)) && (!lifeCycleStatesEnum.equals(LifeCycleStatesEnum.STARTCERTIFICATION))) { + + + String resourceVersion = component.getVersion(); + String resourceUniqueID = component.getUniqueId(); + + if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { + resourceDetails = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), String.format("%.1f", Double.parseDouble(component.getVersion()) + 0.1)); + } else { + resourceDetails = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), String.format("%.1f", Double.parseDouble(component.getVersion()) + 0.1)); + } + + String resourceNewVersion = resourceDetails.getVersion(); + String resourceNewUniqueID = resourceDetails.getUniqueId(); + + System.out.println(resourceNewVersion); + System.out.println("Service UUID: " + resourceDetails.getUUID()); + 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(resourceUniqueID, resourceNewUniqueID, "Expected that resource will have new unique ID."); + } else { + if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { + resourceDetails = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion()); + } else { + resourceDetails = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion()); + } + } + return resourceDetails; + } + + + + + + // 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 { + 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()); + } else { + restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString()); + } + + Integer responseCode = restResponse.getErrorCode(); + Integer expectedCode = 200; + Assert.assertEquals(responseCode,expectedCode, "Response code is not correct."); + + + // For known artifact/payload - verify payload of downloaded artfaict + if (artifactReqDetails != null) { + String response = restResponse.getResponse(); + String payloadData = artifactReqDetails.getPayload(); + String decodedPaypload = org.openecomp.sdc.ci.tests.utils.Decoder.decode(payloadData); + + Assert.assertEquals(response, decodedPaypload, "Response artifact payload not correct."); + } + + //TODO - including body - resourceDetails.getName() +// // Verify audit +// String auditAction = "DownloadArtifact"; +// +// Map body = new HashMap<>(); +// body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString()); +// body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); +// +// ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); +// expectedResourceAuditJavaObject.setAction(auditAction); +// expectedResourceAuditJavaObject.setResourceType(resourceDetails.getComponentType().getValue()); +// expectedResourceAuditJavaObject.setStatus("200"); +// expectedResourceAuditJavaObject.setDesc("OK"); +// expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); +// +// if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) { +// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getComponentInstances().get(0).getName()); +// 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("/sdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID()); +// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url); +// } +// +// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false); + + return restResponse; + + } + + // 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()); + } + + + + + + + + + + @DataProvider(name="uploadArtifactOnRIViaExternalAPI", parallel=true) + public static Object[][] dataProviderUploadArtifactOnRIViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT"}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL"}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP"}, + + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT"}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL"}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP"}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP"} + + }; + } + + + + + + @Test(dataProvider="uploadArtifactOnRIViaExternalAPI") + public void uploadArtifactOnRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState, artifactType, null); + } + + + + @DataProvider(name="uploadArtifactOnVfcVlCpRIViaExternalAPI", parallel=true) + public static Object[][] dataProviderUploadArtifactOnVfcVlCpRIViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP}, + + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP} + + }; + } + + + + + + @Test(dataProvider="uploadArtifactOnVfcVlCpRIViaExternalAPI") + public void uploadArtifactOnVfcVlCpRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState, artifactType, resourceTypeEnum); + } + + + + + @DataProvider(name="uploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI", parallel=true) + public static Object[][] dataProviderUploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI() { + return new Object[][] { + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidTypeToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidTypeToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidTypeEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidTypeEmpty"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidNameToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidNameEmpty"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidLabelToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidLabelEmpty"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidDescriptionToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidDescriptionEmpty"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithInvalidCheckSum"}, + }; + } + + + + + // InvalidArtifact + check audit & response code function + @Test(dataProvider="uploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI") + public void uploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, + ComponentTypeEnum componentTypeEnum, String uploadArtifactTestType) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, componentTypeEnum: %s, uploadArtifactTestType: %s", chosenLifeCycleState, componentTypeEnum, uploadArtifactTestType)); + Component resourceDetails; + ComponentInstance componentResourceInstanceDetails = null; + ArtifactReqDetails artifactReqDetails; + + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.DCAE_INVENTORY_DOC.toString(), true, false); + + resourceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.SERVICE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null); + resourceDetails = getComponentWithResourceInstanceInTargetLifeCycleState(chosenLifeCycleState, null); + componentResourceInstanceDetails = resourceDetails.getComponentInstances().get(0); + } else { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.OTHER.toString(), true, false); + + resourceDetails = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, chosenLifeCycleState, null); + } + + + switch (uploadArtifactTestType) { + case "uploadArtifactWithInvalidTypeToLong": + uploadArtifactWithInvalidTypeToLong(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidTypeEmpty": + uploadArtifactWithInvalidTypeEmpty(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidCheckSum": + uploadArtifactWithInvalidCheckSum(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidNameToLong": + uploadArtifactWithInvalidNameToLong(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidNameEmpty": + uploadArtifactWithInvalidNameEmpty(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidLabelToLong": + uploadArtifactWithInvalidLabelToLong(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidLabelEmpty": + uploadArtifactWithInvalidLabelEmpty(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidDescriptionToLong": + uploadArtifactWithInvalidDescriptionToLong(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithInvalidDescriptionEmpty": + uploadArtifactWithInvalidDescriptionEmpty(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + case "uploadArtifactWithSameLabel": + default: + uploadArtifactWithSameLabel(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + break; + } + } + + // Upload artifact with invalid type via external API - to long type + protected void uploadArtifactWithInvalidTypeToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, + ComponentInstance componentResourceInstanceDetails) throws Exception { + artifactReqDetails.setArtifactType("dsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfds"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name()); + List variables = asList(artifactReqDetails.getArtifactType()); + + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + artifactReqDetails.setArtifactType(""); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name()); + List variables = asList(artifactReqDetails.getArtifactType()); + + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_INVALID_MD5.name()); + List variables = asList(); + uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name()); + List variables = asList("artifact name", "255"); + artifactReqDetails.setArtifactName("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType"); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_ARTIFACT_NAME.name()); + List variables = asList(); + + artifactReqDetails.setArtifactName(""); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name()); + List variables = asList("artifact label", "255"); + artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType"); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + List variables = asList("artifact label"); + artifactReqDetails.setArtifactLabel(""); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name()); + List variables = asList("artifact description", "256"); + artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType"); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, 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, + ComponentInstance componentResourceInstanceDetails) throws Exception { + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + List variables = asList("artifact description"); + artifactReqDetails.setDescription(""); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false); + } + + + + + // Upload artifact with same label via external API + protected void uploadArtifactWithSameLabel(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, + ComponentInstance componentResourceInstanceDetails) throws Exception { + + RestResponse restResponse = null; + if(componentResourceInstanceDetails != null) { + restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + } else { + restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails); + + } + + ArtifactDefinition artifactDefinition = getArtifactDataFromJson(restResponse.getResponse()); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_EXIST.name()); + + List variables = asList(artifactDefinition.getArtifactDisplayName()); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false); + } + + protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, + Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean includeResourceNameInAudit) throws Exception { + RestResponse restResponse; + + if(componentResourceInstanceDetails != null) { + restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, componentResourceInstanceDetails); + } else { + restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails); + + } + + // validate response code + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API; + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.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.setARTIFACT_DATA(null); + Map 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()); + } else { + if(includeResourceNameInAudit) { + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.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()); + } + } + } + + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body); + + return restResponse; + + } + + + + + + + protected RestResponse uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, + Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List variables) throws Exception { + RestResponse restResponse; + + if(componentResourceInstanceDetails != null) { + restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails); + } else { + restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails); + + } + + // validate response code + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + // Check auditing for upload operation +// ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name()); +// = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name()); +// List variables = asList("artifact name", "255"); + + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API; + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.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.setARTIFACT_DATA(null); + Map 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()); + } else { + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + } + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body); + + return restResponse; + + } + + + + + + + + + @DataProvider(name="uploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true) + public static Object[][] dataProviderUploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() { + return new Object[][] { + {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT}, + }; + } + + + // External API + // Upload artifact by diffrent user then creator of asset - Fail + @Test(dataProvider="uploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset") + public void uploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset(ComponentTypeEnum componentTypeEnum, UserRoleEnum userRoleEnum, LifeCycleStatesEnum lifeCycleStatesEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, userRoleEnum: %s, lifeCycleStatesEnum: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum)); + Component resourceDetails; + ComponentInstance componentResourceInstanceDetails = null; + ArtifactReqDetails artifactReqDetails; + + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.DCAE_INVENTORY_DOC.toString(), true, false); + + resourceDetails = getComponentWithResourceInstanceInTargetLifeCycleState(lifeCycleStatesEnum, null); + componentResourceInstanceDetails = resourceDetails.getComponentInstances().get(0); + } else { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.OTHER.toString(), true, false); + + resourceDetails = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, lifeCycleStatesEnum, null); + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(); + + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(userRoleEnum), + artifactReqDetails, 409, componentResourceInstanceDetails, errorInfo, variables, lifeCycleStatesEnum, true); + +// if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKIN)) { +// performeClean(); +// } + } + + + + + + @DataProvider(name="uploadArtifactOnAssetWhichNotExist", parallel=true) + public static Object[][] dataProviderUploadArtifactOnAssetWhichNotExist() { + return new Object[][] { + {ComponentTypeEnum.SERVICE}, + {ComponentTypeEnum.RESOURCE}, + {ComponentTypeEnum.RESOURCE_INSTANCE}, + }; + } + + + // External API + // Upload artifact on VF via external API - happy flow + @Test(dataProvider="uploadArtifactOnAssetWhichNotExist") + public void uploadArtifactOnAssetWhichNotExist(ComponentTypeEnum componentTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s", componentTypeEnum)); + Component resourceDetails; + ComponentInstance componentResourceInstanceDetails = null; + ArtifactReqDetails artifactReqDetails; + + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.DCAE_INVENTORY_DOC.toString(), true, false); + + resourceDetails = getComponentWithResourceInstanceInTargetLifeCycleState(LifeCycleStatesEnum.CHECKIN, null); + componentResourceInstanceDetails = resourceDetails.getComponentInstances().get(0); + + resourceDetails.setUUID("12345"); + componentResourceInstanceDetails.setNormalizedName("12345"); + } else { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", "OTHER", true, false); + + resourceDetails = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, null); + + resourceDetails.setUUID("12345"); + } + + String componentTypeError = ActionStatus.RESOURCE_NOT_FOUND.name(); + if (ComponentTypeEnum.SERVICE == componentTypeEnum){ + componentTypeError = ActionStatus.SERVICE_NOT_FOUND.name(); + } + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(componentTypeError); + List variables = asList(resourceDetails.getUUID()); + + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + artifactReqDetails, 404, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false); + +// performeClean(); + + } + + + @DataProvider(name="uploadArtifactOnAssetWhichInInvalidStateForUploading", parallel=true) + public static Object[][] dataProviderUploadArtifactOnAssetWhichInInvalidStateForUploading() { + return new Object[][] { + {ComponentTypeEnum.SERVICE}, + {ComponentTypeEnum.RESOURCE}, + {ComponentTypeEnum.RESOURCE_INSTANCE}, + }; + } + + + @Test(dataProvider="uploadArtifactOnAssetWhichInInvalidStateForUploading") + public void uploadArtifactOnAssetWhichInInvalidStateForUploading(ComponentTypeEnum componentTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s", componentTypeEnum)); + Component resourceDetails; + ComponentInstance componentResourceInstanceDetails = null; + ArtifactReqDetails artifactReqDetails; + + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.DCAE_INVENTORY_DOC.toString(), true, false); + + resourceDetails = getComponentWithResourceInstanceInTargetLifeCycleState(LifeCycleStatesEnum.STARTCERTIFICATION, null); + componentResourceInstanceDetails = resourceDetails.getComponentInstances().get(0); + } else { + artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.OTHER.toString(), true, false); + + resourceDetails = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, null); + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()); + List variables = asList(resourceDetails.getName(), resourceDetails.getComponentType().toString().toLowerCase(), resourceDetails.getLastUpdaterFullName().split(" ")[0], + resourceDetails.getLastUpdaterFullName().split(" ")[1], resourceDetails.getLastUpdaterUserId()); + + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + artifactReqDetails, 403, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.STARTCERTIFICATION, true); + } + + + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + // Update External API // + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + + @DataProvider(name="updateArtifactForServiceViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateArtifactForServiceViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {LifeCycleStatesEnum.CHECKIN, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"}, + {LifeCycleStatesEnum.CERTIFY, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFY, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFY, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFY, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFY, "OTHER"} + }; + } + + + + + // Update artifact for Service - Success + @Test(dataProvider="updateArtifactForServiceViaExternalAPI") + public void updateArtifactForServiceViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("lifeCycleStatesEnum: %s, artifactType: %s", lifeCycleStatesEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.SERVICE, LifeCycleStatesEnum.CHECKOUT, artifactType, null); + updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.SERVICE, lifeCycleStatesEnum, artifactType); + + // for certify version check that previous version exist, and that it artifact can be download + checksum + if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CERTIFY)) { + // Download the uploaded artifact via external API + downloadResourceDeploymentArtifactExternalAPIAndComparePayLoadOfArtifactType(component, artifactType, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.SERVICE); + } + } + + @DataProvider(name="updateArtifactForVFViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateArtifactForVFViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_JSON"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE"}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_JSON"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CHECKIN, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_DOC"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CHECKIN, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE"}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKIN, "OTHER"}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_JSON"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_DOC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"} + }; + } + + + // Update artifact for VF - Success + @Test(dataProvider="updateArtifactForVFViaExternalAPI") + public void updateArtifactForVFViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("lifeCycleStatesEnum: %s, artifactType: %s", lifeCycleStatesEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, LifeCycleStatesEnum.CHECKOUT, artifactType, null); + updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE, lifeCycleStatesEnum, artifactType); + + // for certify version check that previous version exist, and that it artifact can be download + checksum + if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CERTIFY)) { + // Download the uploaded artifact via external API + downloadResourceDeploymentArtifactExternalAPIAndComparePayLoadOfArtifactType(component, artifactType, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE); + } + } + + @DataProvider(name="updateArtifactForVfcVlCpViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateArtifactForVfcVlCpViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP} + }; + } + + + // Update artifact for VFC/VL/CP - Success + @Test(dataProvider="updateArtifactForVfcVlCpViaExternalAPI") + public void updateArtifactForVfcVlCpViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("lifeCycleStatesEnum: %s, artifactType: %s, resourceTypeEnum: %s", lifeCycleStatesEnum, artifactType, resourceTypeEnum)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, LifeCycleStatesEnum.CHECKOUT, artifactType, resourceTypeEnum); + updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE, lifeCycleStatesEnum, artifactType); + + // for certify version check that previous version exist, and that it artifact can be download + checksum + if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CERTIFY)) { + // Download the uploaded artifact via external API + downloadResourceDeploymentArtifactExternalAPIAndComparePayLoadOfArtifactType(component, artifactType, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE); + } + } + + @DataProvider(name="updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI() { + return new Object[][] { + {ResourceTypeEnum.VFC}, + {ResourceTypeEnum.VL}, + {ResourceTypeEnum.CP} + }; + } + + + // 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 { + getExtendTest().log(Status.INFO, String.format("resourceTypeEnum: %s", resourceTypeEnum)); + + Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, resourceTypeEnum); + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "SNMP_TRAP", true, false); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceInstanceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200); + resourceInstanceDetails = AtomicOperationUtils.changeComponentState(resourceInstanceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + Component component = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value(); + component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()); + Map deploymentArtifacts; + deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE); + String artifactUUID = null; + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci") && StringUtils.isNotEmpty(deploymentArtifacts.get(key).getArtifactUUID())) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + List variables = asList(artifactUUID); + updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", errorInfo, variables, UserRoleEnum.DESIGNER, 404); + + } + + + + + + @DataProvider(name="updateArtifactOnRIViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateArtifactOnRIViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", null}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", null}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VF} + + }; + } + + + + + + @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)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, artifactType, resourceTypeEnum); + updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState, artifactType); + + // for certify version check that previous version exist, and that it artifact can be download + checksum + if(chosenLifeCycleState.equals(LifeCycleStatesEnum.CERTIFY)) { + // Download the uploaded artifact via external API + downloadResourceDeploymentArtifactExternalAPIAndComparePayLoadOfArtifactType(component, artifactType, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE_INSTANCE); + } + } + + + + + + + + @DataProvider(name="updateArtifactOnVfcVlCpRIViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateArtifactOnVfcVlCpRIViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP}, + + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP} + + }; + } + + + + + + @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)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, artifactType, resourceTypeEnum); + updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState, artifactType); + + + // for certify version check that previous version exist, and that it artifact can be download + checksum + if(chosenLifeCycleState.equals(LifeCycleStatesEnum.CERTIFY)) { + // Download the uploaded artifact via external API + downloadResourceDeploymentArtifactExternalAPIAndComparePayLoadOfArtifactType(component, artifactType, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE_INSTANCE); + } + } + + + + + + + + + + + @DataProvider(name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true) + public static Object[][] dataProviderUpdateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() { + return new Object[][] { + {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + }; + } + + + + // External API + // Update artifact by diffrent user then creator of asset - Fail + @Test(dataProvider="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset") + public void updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset(ComponentTypeEnum componentTypeEnum, UserRoleEnum userRoleEnum, LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, userRoleEnum: %s, lifeCycleStatesEnum: %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(); + updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, lifeCycleStatesEnum, artifactType, errorInfo, variables, userRoleEnum, 409); + } + + + @DataProvider(name="updateArtifactOnAssetWhichNotExist", parallel=true) + public static Object[][] dataProviderUpdateArtifactOnAssetWhichNotExist() { + return new Object[][] { + {ComponentTypeEnum.SERVICE, "OTHER", null}, + {ComponentTypeEnum.RESOURCE, "OTHER", null}, + {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF}, + }; + } + + + + // External API + // Upload artifact on VF via external API - happy flow + @Test(dataProvider="updateArtifactOnAssetWhichNotExist") + public void updateArtifactOnAssetWhichNotExist(ComponentTypeEnum componentTypeEnum, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, resourceTypeEnum); + + // get updated artifact data + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + ArtifactReqDetails artifactReqDetails = getUpdatedArtifact(deploymentArtifacts, artifactType); + String artifactUUID = deploymentArtifacts.get(artifactReqDetails.getArtifactLabel()).getArtifactUUID(); + + // Invalid artifactUUID + String invalidArtifactUUID = "12341234-1234-1234-1234-123412341234"; + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()); + List variables = asList(invalidArtifactUUID); + + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, component.getComponentInstances().get(0), artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null, true); + } else { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, null, artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null, true); + + } + + // Invalid componentUUID +// errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()); +// variables = asList("null"); + + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + component.getComponentInstances().get(0).setNormalizedName("invalidNormalizedName"); + + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER.name()); + + variables = asList("invalidNormalizedName", ComponentTypeEnum.RESOURCE_INSTANCE.getValue().toLowerCase(), ComponentTypeEnum.SERVICE.getValue(), component.getName()); + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true); + } else { + component.setUUID("invalidComponentUUID"); + + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()); + variables = asList("null"); + + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, null, artifactReqDetails, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false); + } + + performClean(); + } + + + @DataProvider(name="updateArtifactOnAssetWhichInInvalidStateForUploading", parallel=true) + public static Object[][] dataProviderUpdateProviderDeleteArtifactOnAssetWhichInInvalidStateForUploading() { + return new Object[][] { + {ComponentTypeEnum.SERVICE, "OTHER"}, + {ComponentTypeEnum.RESOURCE, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA"}, + }; + } + + + @Test(dataProvider="updateArtifactOnAssetWhichInInvalidStateForUploading") + public void updateArtifactOnAssetWhichInInvalidStateForUploading(ComponentTypeEnum componentTypeEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()); + List variables = asList(component.getName(), component.getComponentType().toString().toLowerCase(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getFirstName(), + ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getLastName(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId()); + updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, LifeCycleStatesEnum.STARTCERTIFICATION, artifactType, errorInfo, variables, UserRoleEnum.DESIGNER, 403); + + } + + + + + + @DataProvider(name="updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI", parallel=true) + public static Object[][] dataProviderUpdateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidCheckSum"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidCheckSum"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidNameToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidNameToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidNameEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidNameEmpty"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidLabelToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidLabelToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidLabelEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidLabelEmpty"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidDescriptionToLong"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidDescriptionToLong"}, + + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "updateArtifactWithInvalidDescriptionEmpty"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "updateArtifactWithInvalidDescriptionEmpty"}, + }; + } + + + + + // InvalidArtifact + check audit & response code function + @Test(dataProvider="updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI") + public void updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, + ComponentTypeEnum componentTypeEnum, String uploadArtifactTestType) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, componentTypeEnum: %s, uploadArtifactTestType: %s", chosenLifeCycleState, componentTypeEnum, uploadArtifactTestType)); + Component component; + ComponentInstance componentInstance = null; + String artifactType; + + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + artifactType = ArtifactTypeEnum.DCAE_INVENTORY_DOC.toString(); + component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null); + componentInstance = component.getComponentInstances().get(0); + } else { + artifactType = ArtifactTypeEnum.OTHER.toString(); + component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null); + } + + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, chosenLifeCycleState, true).getLeft(); + + switch (uploadArtifactTestType) { + case "updateArtifactWithInvalidCheckSum": + updateArtifactWithInvalidCheckSum(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + case "updateArtifactWithInvalidNameToLong": + updateArtifactWithInvalidNameToLong(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + case "updateArtifactWithInvalidNameEmpty": + updateArtifactWithInvalidNameEmpty(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + case "updateArtifactWithInvalidLabelToLong": + updateArtifactWithInvalidLabelToLong(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + case "updateArtifactWithInvalidLabelEmpty": + updateArtifactWithInvalidLabelEmpty(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + case "updateArtifactWithInvalidDescriptionToLong": + updateArtifactWithInvalidDescriptionToLong(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + case "updateArtifactWithInvalidDescriptionEmpty": + default: + updateArtifactWithInvalidDescriptionEmpty(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactType, componentInstance); + break; + } + +/////////////////////////////////////////////////////////////////////////////// +// // TODO: there is defect when checking invalid type +//// // Upload artifact with invalid type via external API +//// // invalid type +//// String artifactType = artifactReqDetails.getArtifactType(); +//// artifactReqDetails.setArtifactType("invalidType"); +//// restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 400, componentResourceInstanceDetails); +//// // empty type +//// artifactReqDetails.setArtifactType(""); +//// restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 400, componentResourceInstanceDetails); +//// artifactReqDetails.setArtifactType(artifactType); +/////////////////////////////////////////////////////////////////////////////// + } + + // TODO + // Update artifact with invalid checksum via external API + protected void updateArtifactWithInvalidCheckSum(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_INVALID_MD5.name()); + List variables = asList(); +// uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), +// artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables); + } + + + // Update artifact with valid type & invalid name via external API - name to long + protected void updateArtifactWithInvalidNameToLong(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + if(componentInstance != null) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name()); + List variables = asList("artifact name", "255"); + artifactReqDetails.setArtifactName("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType"); + + if(componentInstance != null) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 400, 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); + + } + } + + + // Update artifact with valid type & invalid name via external API - name is empty + protected void updateArtifactWithInvalidNameEmpty(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + if(componentInstance != null) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_ARTIFACT_NAME.name()); + List variables = asList(); + artifactReqDetails.setArtifactName(""); + + if(componentInstance != null) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 400, 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); + + } + } + + + // Update artifact with valid type & invalid label via external API - label to long + protected void updateArtifactWithInvalidLabelToLong(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + if(componentInstance != null) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name()); + List variables = asList(); + artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType"); + + if(componentInstance != null) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 400, 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); + + } + } + + + // Update artifact with valid type & invalid label via external API - label is empty + protected void updateArtifactWithInvalidLabelEmpty(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + if(componentInstance != null) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name()); + List variables = asList("artifact label"); + artifactReqDetails.setArtifactLabel(""); + + if(componentInstance != null) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 400, 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); + + } + } + + + // Update artifact with invalid description via external API - to long description + protected void updateArtifactWithInvalidDescriptionToLong(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + if(componentInstance != null) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name()); + List variables = asList(); + artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType"); + + if(componentInstance != null) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 400, 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); + + } + } + + + // Update artifact with invalid description via external API - empty description + protected void updateArtifactWithInvalidDescriptionEmpty(Component component, User sdncModifierDetails, String artifactType, + ComponentInstance componentInstance) throws Exception { + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + if(componentInstance != null) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name()); + List variables = asList("artifact description"); + artifactReqDetails.setDescription(""); + + if(componentInstance != null) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 400, 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); + + } + } + + + + + + + + + + // Unhappy flow - get chosen life cycle state, artifact type and asset type + // update artifact via external API + check audit & response code + // Download artifact via external API + check audit & response code + // Check artifact version, uuid & checksusm + protected Component updateArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ErrorInfo errorInfo, List variables, UserRoleEnum userRoleEnum, Integer expectedResponseCode) throws Exception { + String componentVersionBeforeUpdate = null; + + // get updated artifact data + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, chosenLifeCycleState, true).getLeft(); + componentVersionBeforeUpdate = component.getVersion(); + + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + ArtifactReqDetails artifactReqDetails = getUpdatedArtifact(deploymentArtifacts, artifactType); + + String artifactName = artifactReqDetails.getArtifactLabel(); + String artifactUUID = deploymentArtifacts.get(artifactName).getArtifactUUID(); + String artifactVersionBeforeUpdate = deploymentArtifacts.get(artifactName).getArtifactVersion(); + int numberOfArtifact = deploymentArtifacts.size(); + + // create component/s & upload artifact via external api + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum), + expectedResponseCode, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true); + } else { + updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum), + expectedResponseCode, null, artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true); + } + + if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { + component = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion()); + } else { + component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion()); + } + + // Get list of deployment artifact + download them via external API + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts(); + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact will be same as before."); + Assert.assertEquals(String.valueOf((Integer.parseInt(artifactVersionBeforeUpdate))), deploymentArtifacts.get(artifactName).getArtifactVersion(), "Expected that aftifact will not change."); + Assert.assertEquals(artifactUUID, deploymentArtifacts.get(artifactName).getArtifactUUID(), "Expected that aftifactUUID will not change."); + Assert.assertEquals(componentVersionBeforeUpdate, component.getVersion(), "Expected that check-out component will not change version number."); + + return component; + } + + protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, + Integer expectedResponseCode, ComponentInstance componentInstance, ArtifactReqDetails artifactReqDetails, String artifactUUID, ErrorInfo errorInfo, List variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception { + RestResponse restResponse; + + if(componentInstance != null) { + restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, componentInstance, artifactUUID); + } else { + restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, artifactUUID); + + } + + // validate response code + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + //TODO + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API; + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.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.setARTIFACT_DATA(""); + expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID); + Map 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()); + } 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()); + } 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()); + } + } + + + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body); + return restResponse; + + } + + + // This function get component, user & if updatedPayload or not + // It will create default payload / updated payload of artifact + // And download artifact of component which starts with ci + protected RestResponse downloadResourceDeploymentArtifactExternalAPIAndComparePayLoadOfArtifactType(Component component, String artifactType, User sdncModifierDetails, ComponentTypeEnum componentTypeEnum) throws IOException, Exception { + // Download the uploaded artifact via external API + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("abcd", artifactType, true, false); + String artifactName = null; + for (String key : component.getDeploymentArtifacts().keySet()) { + if (key.startsWith("ci")) { + artifactName = key; + break; + } + } + return downloadResourceDeploymentArtifactExternalAPI(component, component.getDeploymentArtifacts().get(artifactName), sdncModifierDetails, artifactReqDetails, componentTypeEnum); + } + + // Get deployment artifact of asset + protected Map getDeploymentArtifactsOfAsset(Component component, ComponentTypeEnum componentTypeEnum) { + Map deploymentArtifacts = null; + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + for(ComponentInstance componentInstance: component.getComponentInstances()) { + if(componentInstance.getNormalizedName().startsWith("ci")) { + deploymentArtifacts = componentInstance.getDeploymentArtifacts(); + break; + } + } + } else { + deploymentArtifacts = component.getDeploymentArtifacts(); + } + return deploymentArtifacts; + } + + // get deploymentArtifact of asset and artifactType -> generate new artifact that can be updated on the asset + protected ArtifactReqDetails getUpdatedArtifact(Map deploymentArtifacts, String artifactType) throws IOException, Exception { + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactReqDetails.setArtifactDisplayName(deploymentArtifacts.get(key).getArtifactDisplayName()); + artifactReqDetails.setArtifactName(deploymentArtifacts.get(key).getArtifactName()); + artifactReqDetails.setArtifactLabel(deploymentArtifacts.get(key).getArtifactLabel()); + break; + } + } + + return artifactReqDetails; + } + + // Happy flow - get chosen life cycle state, artifact type and asset type + // update artifact via external API + check audit & response code + // Download artifact via external API + check audit & response code + // Check artifact version, uuid & checksusm + protected Component updateArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState, String artifactType) throws Exception { + RestResponse restResponse = null; + int numberOfArtifact = 0; + String artifactVersionBeforeUpdate = null; + String artifactName = null; + String componentVersionBeforeUpdate = null; + + // get updated artifact data + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true); + String artifactUUID = null; + Map deploymentArtifacts; + deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactName = key; + artifactVersionBeforeUpdate = deploymentArtifacts.get(key).getArtifactVersion(); + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + artifactReqDetails.setArtifactDisplayName(deploymentArtifacts.get(key).getArtifactDisplayName()); + artifactReqDetails.setArtifactName(deploymentArtifacts.get(key).getArtifactName()); + artifactReqDetails.setArtifactLabel(deploymentArtifacts.get(key).getArtifactLabel()); + break; + } + } + + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, chosenLifeCycleState, true).getLeft(); + componentVersionBeforeUpdate = component.getVersion(); + 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); + + // Get list of deployment artifact + download them via external API + deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact will be same as before."); + Assert.assertEquals(String.valueOf((Integer.parseInt(artifactVersionBeforeUpdate) + 1)), deploymentArtifacts.get(artifactName).getArtifactVersion(), "Expected that aftifact version will increase by one."); + + if(chosenLifeCycleState == LifeCycleStatesEnum.CHECKOUT) { + Assert.assertEquals(componentVersionBeforeUpdate, component.getVersion(), "Expected that check-out component will not change version number."); + } else { + Assert.assertEquals(String.format("%.1f", (Double.parseDouble(componentVersionBeforeUpdate) + 0.1)), component.getVersion(), "Expected that non check-out component version will increase by 0.1."); + } + + // Download the uploaded artifact via external API + downloadResourceDeploymentArtifactExternalAPI(component, deploymentArtifacts.get(responseArtifact.getArtifactLabel()), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentTypeEnum); + + return component; + } + + + // 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); + + // Check response of external API + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API; + + Map 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); +// 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); + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body); + + return restResponse; + } + + + // 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); + + // Check response of external API + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API; + + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase()); + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails); + expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID); + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body); + + return restResponse; + } + + + + + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + // Delete External API // + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + @DataProvider(name="deleteArtifactForServiceViaExternalAPI", parallel=true) + public static Object[][] dataProviderDeleteArtifactForServiceViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {LifeCycleStatesEnum.CHECKIN, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"}, + {LifeCycleStatesEnum.CERTIFY, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFY, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFY, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFY, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFY, "OTHER"} + }; + } + + + + + // Delete artifact for Service - Success + @Test(dataProvider="deleteArtifactForServiceViaExternalAPI") + public void deleteArtifactForServiceViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("lifeCycleStatesEnum: %s, artifactType: %s", lifeCycleStatesEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.SERVICE, LifeCycleStatesEnum.CHECKOUT, artifactType, null); + deleteArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.SERVICE, lifeCycleStatesEnum); + } + + @DataProvider(name="deleteArtifactForVFViaExternalAPI", parallel=true) + public static Object[][] dataProviderDeleteArtifactForVFViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_JSON"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC"}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE"}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_JSON"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CHECKIN, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_DOC"}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CHECKIN, "YANG_XML"}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE"}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CHECKIN, "OTHER"}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_JSON"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_POLICY"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_EVENT"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "APPC_CONFIG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_DOC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_TOSCA"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"}, + }; + } + + + // Delete artifact for VF - Success + @Test(dataProvider="deleteArtifactForVFViaExternalAPI") + public void deleteArtifactForVFViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("lifeCycleStatesEnum: %s, artifactType: %s", lifeCycleStatesEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, LifeCycleStatesEnum.CHECKOUT, artifactType, null); + deleteArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE, lifeCycleStatesEnum); + } + + @DataProvider(name="deleteArtifactForVfcVlCpViaExternalAPI", parallel=true) + public static Object[][] dataProviderDeleteArtifactForVfcVlCpViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP} + }; + } + + + // Delete artifact for VFC, VL, CP - Success + @Test(dataProvider="deleteArtifactForVfcVlCpViaExternalAPI") + public void deleteArtifactForVfcVlCpViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("lifeCycleStatesEnum: %s, artifactType: %s, resourceTypeEnum: %s", lifeCycleStatesEnum, artifactType, resourceTypeEnum)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, LifeCycleStatesEnum.CHECKOUT, artifactType, resourceTypeEnum); + deleteArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE, lifeCycleStatesEnum); + } + + @DataProvider(name="deleteArtifactOnRIViaExternalAPI", parallel=true) + public static Object[][] dataProviderDeleteArtifactOnRIViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", null}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", null}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", null}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", null}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VF}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VF} + + }; + } + + + + + + @Test(dataProvider="deleteArtifactOnRIViaExternalAPI") + public void deleteArtifactOnRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, artifactType, resourceTypeEnum); + deleteArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState); + } + + + @DataProvider(name="deleteArtifactOnVfcVlCpRIViaExternalAPI", parallel=true) + public static Object[][] dataProviderDeleteArtifactOnVfcVlCpRIViaExternalAPI() { + return new Object[][] { + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP,}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP}, + + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL}, + + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP}, + {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP} + + }; + } + + + + + + @Test(dataProvider="deleteArtifactOnVfcVlCpRIViaExternalAPI") + public void deleteArtifactOnVfcVlCpRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, artifactType, resourceTypeEnum); + deleteArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState); + } + + + @DataProvider(name="deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true) + public static Object[][] dataProviderDeleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() { + return new Object[][] { + {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, +// + {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"}, + {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"}, + }; + } + + + // External API + // Delete artifact by diffrent 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)); + Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, lifeCycleStatesEnum, artifactType, null); + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + + String artifactUUID = null; + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()); + List variables = asList(); + + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum), + 409, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true); + } else { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum), + 409, null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true); + } + + //TODO +// downloadResourceDeploymentArtifactExternalAPI(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, componentTypeEnum); + } + + + @DataProvider(name="deleteArtifactOnAssetWhichNotExist", parallel=true) + public static Object[][] dataProviderDeleteArtifactOnAssetWhichNotExist() { + return new Object[][] { + {ComponentTypeEnum.SERVICE, "OTHER", null}, + {ComponentTypeEnum.RESOURCE, "OTHER", null}, + {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF}, + }; + } + + + // External API + // Upload artifact on VF via external API - happy flow + @Test(dataProvider="deleteArtifactOnAssetWhichNotExist") + public void deleteArtifactOnAssetWhichNotExist(ComponentTypeEnum componentTypeEnum, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, resourceTypeEnum); + + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + + String artifactUUID = null; + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + // Invalid artifactUUID + String invalidArtifactUUID = "12341234-1234-1234-1234-123412341234"; + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()); + List variables = asList(invalidArtifactUUID); + + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true); + } else { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, null, invalidArtifactUUID, errorInfo, variables, null, true); + + } + + + // Invalid componentUUID + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + component.getComponentInstances().get(0).setNormalizedName("invalidNormalizedName"); + 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); + } else { + component.setUUID("invalidComponentUUID"); + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) { + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()); + } else { + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()); + } + variables = asList("invalidComponentUUID"); + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false); + } + + +// performeClean(); + + } + + @DataProvider(name="deleteArtifactOnAssetWhichInInvalidStateForUploading", parallel=true) + public static Object[][] dataProviderDeleteArtifactOnAssetWhichInInvalidStateForUploading() { + return new Object[][] { + {ComponentTypeEnum.SERVICE, "OTHER"}, + {ComponentTypeEnum.RESOURCE, "OTHER"}, + {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA"}, + }; + } + + + @Test(dataProvider="deleteArtifactOnAssetWhichInInvalidStateForUploading") + public void deleteArtifactOnAssetWhichInInvalidStateForUploading(ComponentTypeEnum componentTypeEnum, String artifactType) throws Exception { + getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType)); + Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKOUT, artifactType, null); + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft(); + + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + String artifactUUID = null; + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + + + // Invalid artifactUUID + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()); + List variables = asList(component.getName(), component.getComponentType().toString().toLowerCase(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getFirstName(), + ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getLastName(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId()); + + if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 403, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true); + } else { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 403, null, artifactUUID, errorInfo, variables, null, true); + + } + + } + + + @DataProvider(name="deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI", parallel=true) + public static Object[][] dataProviderDeleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI() { + return new Object[][] { + {ResourceTypeEnum.VFC}, + {ResourceTypeEnum.VL}, + {ResourceTypeEnum.CP} + }; + } + + + // Verify that it cannot delete VFC/VL/CP artifact on VFCi/VLi/CPi - Failure flow + @Test(dataProvider="deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI") + public void deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI(ResourceTypeEnum resourceTypeEnum) throws Exception { + getExtendTest().log(Status.INFO, String.format("resourceTypeEnum: %s", resourceTypeEnum)); + + Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, resourceTypeEnum); + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "SNMP_TRAP", true, false); + uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceInstanceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200); + resourceInstanceDetails = AtomicOperationUtils.changeComponentState(resourceInstanceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + Component component = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value(); + component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion()); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()); + Map deploymentArtifacts; + deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE); + String artifactUUID = null; + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci")) { + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + break; + } + } + List variables = asList(artifactUUID); + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), + 404, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true); + } + + protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, + Integer expectedResponseCode, ComponentInstance componentInstance, String artifactUUID, ErrorInfo errorInfo, List variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception { + RestResponse restResponse; + + if(componentInstance != null) { + restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, componentInstance, artifactUUID); + } else { + restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactUUID); + + } + + // validate response code + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API; + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.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.setARTIFACT_DATA(null); + expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID); + Map 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()); + } 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()); + } else { + expectedExternalAudit.setRESOURCE_NAME(""); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL()); + } + } else { + if(resourceNameInAudit) { + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + } else { + expectedExternalAudit.setRESOURCE_NAME(""); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL()); + } + } + } + +// getExtendTest().log(LogStatus.INFO, "Audit Action: " + AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName()); +// body.forEach((k,v)->getExtendTest().log(LogStatus.INFO,"key : " + k + " value : " + v)); + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body); + + return restResponse; + + } + + + // Happy flow - get chosen life cycle state, artifact type and asset type + // delete artifact via external API + check audit & response code + protected Component deleteArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState) throws Exception { + String artifactName = null; + component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, chosenLifeCycleState, true).getLeft(); + + // get updated artifact data + String artifactUUID = null; + int moduleTypeArtifact = 0; + Map deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + + for (String key : deploymentArtifacts.keySet()) { + if (key.startsWith("ci") && StringUtils.isNotEmpty(deploymentArtifacts.get(key).getArtifactUUID())) { + artifactName = key; + artifactUUID = deploymentArtifacts.get(key).getArtifactUUID(); + + if (deploymentArtifacts.get(key).getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA)){ + moduleTypeArtifact = 1; + } + break; + } + } + + + String componentVersionBeforeDelete = component.getVersion(); + int numberOfArtifact = deploymentArtifacts.size(); + + + + // create component/s & upload artifact via external api + if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) { + deleteArtifactOfRIIncludingValiditionOfAuditAndResponseCode(component, component.getComponentInstances().get(0), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, 200); + } else { + deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, 200); + } + + component = getNewerVersionOfComponent(component, chosenLifeCycleState); + + // Get list of deployment artifact + download them via external API + deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum); + if(deploymentArtifacts.get(artifactName) != null) { + Assert.assertTrue(false, "Expected that deleted artifact will not appear in deployment artifact list."); + } + if((LifeCycleStatesEnum.CERTIFICATIONREQUEST.equals(chosenLifeCycleState)) && (ComponentTypeEnum.RESOURCE_INSTANCE.equals(componentTypeEnum)) && (!component.getComponentType().toString().equals(ComponentTypeEnum.RESOURCE.toString()))) { + Assert.assertEquals(numberOfArtifact - 1 - moduleTypeArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact (one deleted and one vfmodule) will decrease by two."); + } 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."); + } else { + Assert.assertEquals(String.format("%.1f", (Double.parseDouble(componentVersionBeforeDelete) + 0.1)), component.getVersion(), "Expected that non check-out component version will increase by 0.1."); + } + + downloadResourceDeploymentArtifactExternalAPI(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, componentTypeEnum); + + return component; + } + + // 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); + + // Check response of external API + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API; + + Map 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); +// 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); + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body); + + 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); + + // Check response of external API + Integer responseCode = restResponse.getErrorCode(); + Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct."); + + + // Check auditing for upload operation + ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse()); + + AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API; + + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); + + AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase()); + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails); + expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID); + AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body); + + 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 { + 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()); + } else { + restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString()); + } + + Integer responseCode = restResponse.getErrorCode(); + Integer expectedCode = 404; + Assert.assertEquals(responseCode,expectedCode, "Response code is not correct."); + + + //TODO - including body - resourceDetails.getName() +// // Verify audit +// String auditAction = "DownloadArtifact"; +// +// Map body = new HashMap<>(); +// body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString()); +// body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName()); +// +// ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject(); +// expectedResourceAuditJavaObject.setAction(auditAction); +// expectedResourceAuditJavaObject.setResourceType(resourceDetails.getComponentType().getValue()); +// expectedResourceAuditJavaObject.setStatus("200"); +// expectedResourceAuditJavaObject.setDesc("OK"); +// expectedResourceAuditJavaObject.setCONSUMER_ID("ci"); +// +// if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) { +// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getComponentInstances().get(0).getName()); +// 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("/sdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID()); +// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url); +// } +// +// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false); + + return restResponse; + + } + + + + + public Component getComponentInTargetLifeCycleState(String componentType, UserRoleEnum creatorUser, LifeCycleStatesEnum targetLifeCycleState, ResourceTypeEnum resourceTypeEnum) throws Exception { + Component resourceDetails = null; + + if((componentType.toLowerCase().equals("vf")) || (componentType.toLowerCase().equals("resource"))){ + if(resourceTypeEnum==null) { + resourceTypeEnum = ResourceTypeEnum.VF; + } + Either createdResource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(resourceTypeEnum, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, creatorUser, true); + resourceDetails = createdResource.left().value(); + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, creatorUser, targetLifeCycleState, true).getLeft(); + } else { + Either createdResource = AtomicOperationUtils.createDefaultService(creatorUser, true); + resourceDetails = createdResource.left().value(); + // Add artifact to service if asked for certifcationrequest - must be at least one artifact for the flow + if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == targetLifeCycleState) || (LifeCycleStatesEnum.STARTCERTIFICATION == targetLifeCycleState)) { + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetails, UserRoleEnum.DESIGNER, true, true).left().value(); + } + resourceDetails = AtomicOperationUtils.changeComponentState(resourceDetails, creatorUser, targetLifeCycleState, true).getLeft(); + } + + return resourceDetails; + } + + + + + + protected String createUploadArtifactBodyJson() { + Map jsonBody = new HashMap(); + jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME); + jsonBody.put("artifactDisplayName", "configure"); + jsonBody.put("artifactType", "SHELL"); + jsonBody.put("mandatory", "false"); + jsonBody.put("description", "ff"); + jsonBody.put("payloadData", UPLOAD_ARTIFACT_PAYLOAD); + jsonBody.put("artifactLabel", "configure"); + return gson.toJson(jsonBody); + } + + protected ArtifactDefinition getArtifactDataFromJson(String content) { + JsonObject jsonElement = new JsonObject(); + ArtifactDefinition resourceInfo = null; + + try { + Gson gson = new Gson(); + jsonElement = gson.fromJson(content, jsonElement.getClass()); + JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE_FIELD); + if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) { + String groupValueUpper = artifactGroupValue.getAsString().toUpperCase(); + if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) { + StringBuilder sb = new StringBuilder(); + for (String value : ArtifactGroupTypeEnum.getAllTypes()) { + sb.append(value).append(", "); + } + log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb.toString()); + return null; + } else { + jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD); + jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, groupValueUpper); + } + } + String payload = null; + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + String json = gson.toJson(jsonElement); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); + + resourceInfo = mapper.readValue(json, ArtifactDefinition.class); + resourceInfo.setPayloadData(payload); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update"); + BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return resourceInfo; + } + + protected HttpGet createGetRequest(String url) { + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + httpGet.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + return httpGet; + } + + protected String getArtifactUid(HttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + String artifactId = (String) responseMap.get("uniqueId"); + return artifactId; + } + + protected String getArtifactEsId(HttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + String esId = (String) responseMap.get("EsId"); + return esId; + } + + protected ArtifactDefinition addArtifactDataFromResponse(HttpResponse response, ArtifactDefinition artifact) throws HttpResponseException, IOException, ParseException { + //String responseString = new BasicResponseHandler().handleResponse(response); + HttpEntity entity = response.getEntity(); + String responseString = EntityUtils.toString(entity); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + artifact.setEsId((String)responseMap.get("esId")); + artifact.setUniqueId((String) responseMap.get("uniqueId")); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType((String) responseMap.get("artifactGroupType"))); + artifact.setTimeout(((Long) responseMap.get("timeout")).intValue()); + return artifact; + } + + protected String getLifecycleArtifactUid(CloseableHttpResponse response) throws HttpResponseException, IOException, ParseException { + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseMap = (JSONObject) jsonParser.parse(responseString); + responseMap = (JSONObject) responseMap.get("implementation"); + String artifactId = (String) responseMap.get("uniqueId"); + return artifactId; + } + + protected HttpDelete createDeleteArtifactRequest(String url) { + HttpDelete httpDelete = new HttpDelete(url); + httpDelete.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + httpDelete.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + return httpDelete; + } + + protected HttpPost createPostAddArtifactRequeast(String jsonBody, String url, boolean addMd5Header) throws UnsupportedEncodingException { + HttpPost httppost = new HttpPost(url); + httppost.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (addMd5Header) { + httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody)); + } + StringEntity input = new StringEntity(jsonBody); + input.setContentType("application/json"); + httppost.setEntity(input); + log.debug("Executing request {}" , httppost.getRequestLine()); + return httppost; + } + + protected String createLoadArtifactBody() { + Map json = new HashMap(); + json.put("artifactName", "install_apache2.sh"); + json.put("artifactType", "SHELL"); + json.put("description", "ddd"); + json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz"); + json.put("artifactLabel", "name123"); + + String jsonStr = gson.toJson(json); + return jsonStr; + } + + protected void checkDeleteResponse(RestResponse response) { + BaseRestUtils.checkStatusCode(response, "delete request failed", false, 204, 404); + } + + protected ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + try { + ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, ArtifactUiDownloadData.class); + return artifactUiDownloadData; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/DeploymentValiditaion.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/DeploymentValiditaion.java new file mode 100644 index 0000000000..91a7b12a44 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/DeploymentValiditaion.java @@ -0,0 +1,428 @@ +/*- + * ============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.externalApis; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.io.FileUtils; +import org.junit.Rule; +import org.junit.rules.TestName; +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.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails; +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.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.common.util.ZipUtil; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import org.yaml.snakeyaml.Yaml; + +import com.aventstack.extentreports.Status; + + + + + + + +public class DeploymentValiditaion extends ComponentBaseTest{ + + + + + @Rule + public static TestName name = new TestName(); + + public DeploymentValiditaion() { + super(name, DeploymentValiditaion.class.getName()); + } + + protected final static String categoryFilterKey = "category"; + protected final static String subCategoryFilterKey = "subCategory"; + protected String attVersionStr ; + + + public static List listf(String directoryName) { + File directory = new File(directoryName); + + List resultList = new ArrayList(); + + // get all the files from a directory + File[] fList = directory.listFiles(); + resultList.addAll(Arrays.asList(fList)); + for (File file : fList) { + if (file.isFile()) { + System.out.println(file.getAbsolutePath()); + } else if (file.isDirectory()) { + resultList.addAll(listf(file.getAbsolutePath())); + } + } + //System.out.println(fList); + return resultList; + } + @BeforeTest + public void beforeTest() throws Exception{ + RestResponse attVersion = CatalogRestUtils.getOsVersion(); + attVersionStr = ResponseParser.getVersionFromResponse(attVersion); + } + + + @Test + public void pasrseNormativies() throws Exception{ + + + String path = "//apps//asdc_kits//catalog-be-" + attVersionStr + "//import//tosca//normative-types"; + String path2 = "//apps//asdc_kits//catalog-be-" + attVersionStr + "//import//tosca//heat-types"; + +// String path = "C:\\Git_work\\Git_UGN\\d2-sdnc\\catalog-be\\src\\main\\resources\\import\\tosca\\normative-types"; +// String path2 = "C:\\Git_work\\Git_UGN\\d2-sdnc\\catalog-be\\src\\main\\resources\\import\\tosca\\heat-types"; + + + List yamlList1 = getYamlFilesList(path); + List nodeNamesFromYamlList1 = getNodeNamesFromYamlList(yamlList1); + List yamlList2 = getYamlFilesList(path2); + List nodeNamesFromYamlList2 = getNodeNamesFromYamlList(yamlList2); + + + List expectedList = new ArrayList(); + expectedList.addAll(nodeNamesFromYamlList1); + expectedList.addAll(nodeNamesFromYamlList2); + System.out.println("list of normatives from files:::::::::::"); + expectedList.forEach(System.out::println); + getExtendTest().log(Status.INFO, "list of normatives from files:"); + getExtendTest().log(Status.INFO,expectedList.toString()); + + + String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory(), subCategoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getSubCategory() }; + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES); + Map resourceAssetList = AssetRestUtils.getResourceAssetMap(assetResponse); + Map resourceListFiltteredByWholeVersion = AssetRestUtils.getResourceListFiltteredByWholeVersion(resourceAssetList); + List resourceToscaNamesList = AssetRestUtils.getResourceObjectByNameAndVersionToscaNamesList(resourceListFiltteredByWholeVersion); + System.out.println("list of normatives from APIs:::::::::::"); + resourceToscaNamesList.forEach(System.out::println); + getExtendTest().log(Status.INFO, "list of normatives from APIs:"); + getExtendTest().log(Status.INFO, resourceToscaNamesList.toString()); + + boolean good = true; + List missingNormatives = new ArrayList<>(); + + for (int i = 0; i < expectedList.size(); i ++) { + if (!resourceToscaNamesList.contains(expectedList.get(i))) { + good = false; + missingNormatives.add(expectedList.get(i)); + + + } + } + + System.out.println("<<<<<<<<>>>>>"); + missingNormatives.forEach(System.out::println); + getExtendTest().log(Status.INFO, "MISSING NORMATIVES:"); + getExtendTest().log(Status.INFO, missingNormatives.toString()); + + assertTrue("missing normatives ", good); + + } + + + public List getNodeNamesFromYamlList(List yamlList) throws IOException { + List nodeNameList = new ArrayList(); + + for (File file : yamlList) { + String content = new String(Files.readAllBytes(Paths.get(file.getPath())), StandardCharsets.UTF_8); + Yaml yaml = new Yaml(); + Map load = (Map) yaml.load(content); + Map topology_template = (Map) load.get("node_types"); +// String string = topology_template.keySet().toString().replaceAll("tosca.nodes.", ""); + String string = topology_template.keySet().iterator().next().toString(); + System.out.println(string +" -----> " +file.getPath()); + nodeNameList.add(string); + } + return nodeNameList; + } + + + public List getYamlFilesList(String path) throws IOException { + List yamlList = new ArrayList(); + File dir = new File(path); + String[] extensions = new String[] { "yml" }; + System.out.println("Getting all .yml files in " + dir.getCanonicalPath() + + " including those in subdirectories"); + List files = (List) FileUtils.listFiles(dir, extensions, true); + for (File file : files) { + System.out.println("file: " + file.getCanonicalPath()); + yamlList.add(file); + } + return yamlList; + } + + + + + + + @Test (enabled=false) + public void testYaml() throws IOException{ + + System.out.println(""); + + File file = new File("\\\\Comp-1\\FileIO\\Stop.txt"); + + + //read file + + + Map readZip = null; + Path path = Paths.get("C:\\Users\\ys9693\\Documents\\csar\\attributesWithProporties\\attributesWithProporties.csar"); + byte[] data = Files.readAllBytes(path); + if (data != null && data.length > 0) { + readZip = ZipUtil.readZip(data); + + } + + byte[] artifactsBs = readZip.get("Definitions/VF_RI2_G6.yaml"); + String str = new String(artifactsBs, StandardCharsets.UTF_8); + + + + + Yaml yaml = new Yaml(); + Map load = (Map) yaml.load(str); + Map topology_template = (Map) load.get("topology_template"); + Map node_templates = (Map) topology_template.get("node_templates"); + + Set keySet = node_templates.keySet(); + } + + + + @Test + public void pasrseDataTypes() throws Exception{ + +// String path = "C:\\Git_work\\Git_UGN\\d2-sdnc\\catalog-be\\src\\main\\resources\\import\\tosca\\data-types\\dataTypes.yml"; + String path = "//apps//asdc_kits//catalog-be-" + attVersionStr + "//import//tosca//data-types//dataTypes.yml"; + + String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); + + + Yaml yaml = new Yaml(); + Map load = (Map) yaml.load(content); + List listOfDataTypes = new ArrayList(); + listOfDataTypes.addAll(load.keySet()); + System.out.println("<<<<<<<< List of Data Types >>>>>>>>>"); + listOfDataTypes.forEach(System.out::println); + getExtendTest().log(Status.INFO, "List of Data Types:"); + getExtendTest().log(Status.INFO, listOfDataTypes.toString()); + + Resource resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + PropertyReqDetails defaultProperty = ElementFactory.getDefaultListProperty(); + +// SchemaDefinition schemaDefinition = new SchemaDefinition(); + + + + + defaultProperty.setPropertyDefaultValue(null); +// defaultProperty.setSchema(schemaDefinition); + + +// listOfDataTypes.remove("tosca.datatypes.Root"); + for (String dataType : listOfDataTypes) { +// if (dataType.equals("map") || dataType.equals("list")){ + defaultProperty.setPropertyType(dataType); + defaultProperty.setName(dataType); + System.out.println("Adding proporty with data type: ----> " + dataType); + getExtendTest().log(Status.INFO, "Adding proporty with data type: ----> " + dataType); + AtomicOperationUtils.addCustomPropertyToResource(defaultProperty, resource, UserRoleEnum.DESIGNER, true); +// } + } + + + listOfDataTypes.forEach(System.out::println); + + } + + + + + + + @Test + public void pasrseCategories() throws Exception{ + +// String path = "C:\\Git_work\\Git_UGN\\d2-sdnc\\catalog-be\\src\\main\\resources\\import\\tosca\\categories\\categoryTypes.yml"; + String path = "//apps//asdc_kits//catalog-be-" + attVersionStr + "//import//tosca//categories//categoryTypes.yml"; + + String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); + + List serviceCategories = new ArrayList(); + List resourceCategories = new ArrayList(); + + Yaml yaml = new Yaml(); + Map load = (Map) yaml.load(content); + Map services = (Map) load.get("services"); + Map resources = (Map) load.get("resources"); + + Map> resourcesListFromFile = new HashMap>() ; + + //retrieve subcategories + for ( String resourceCategoryName : resources.keySet()) { + Map subcategory = (Map) resources.get(resourceCategoryName).get("subcategories"); + + resourceCategories = new ArrayList(); + for (String subcategoryName : subcategory.keySet()) { + String name = (String) subcategory.get(subcategoryName).get("name"); +// resourceCategories.add(name.replaceAll("\\s","")); + resourceCategories.add(name); + + } + resourcesListFromFile.put(resources.get(resourceCategoryName).get("name").toString(), resourceCategories); + } + + System.out.println(resourcesListFromFile.toString()); + getExtendTest().log(Status.INFO, "Expected categories:"); + getExtendTest().log(Status.INFO, resourcesListFromFile.toString()); + + //retrieve service categories +// for ( String serviceCategoryName : services.keySet()) { +// String name = (String) services.get(serviceCategoryName).get("name"); +// serviceCategories.add(name); +// } +// serviceCategories.forEach(System.out::println); + + + //retrieve resource list from URL + + Map> categoriesMap = getCategories(); + List resourceSubCategories = categoriesMap.get(ComponentTypeEnum.RESOURCE_PARAM_NAME); + List subcategories; + for (CategoryDefinition categoryDefinition : resourceSubCategories) { + subcategories = categoryDefinition.getSubcategories(); + } +// subcategories.stream().collect(toMap(i -> i, i -> items.get(i))); + +// resourceSubCategories.stream().collect( +// Collectors.groupingBy(CategoryDefinition::getName, Collectors.groupingBy(SubCategoryDefinition::getName))); + +// resourceSubCategories.stream().filter(p->p.getSubcategories()).map(m->m.getName()).collect(Collectors.toList()).collect(Collectors.toMap(CategoryDefinition::getName,m)); + + + Map> resourceMapFromUrl = resourceSubCategories.stream().collect(Collectors.toMap( e -> e.getName() , e -> e.getSubcategories().stream().map(e1 -> e1.getName()).collect(Collectors.toList()))); + + getExtendTest().log(Status.INFO, "Actual categories:"); + getExtendTest().log(Status.INFO, resourceMapFromUrl.toString()); + + + assertTrue("missing categories ", resourceMapFromUrl.keySet().containsAll(resourcesListFromFile.keySet())); + + + + + + + } + + + public Map> getCategories() throws Exception { + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + Map> map = new HashMap>(); + + + RestResponse allResourceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.RESOURCE_PARAM_NAME); + RestResponse allServiceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.SERVICE_PARAM_NAME); + + List parsedResourceCategories = ResponseParser.parseCategories(allResourceCategories); + List parsedServiceCategories = ResponseParser.parseCategories(allServiceCategories); + + map.put(ComponentTypeEnum.RESOURCE_PARAM_NAME, parsedResourceCategories); + map.put(ComponentTypeEnum.SERVICE_PARAM_NAME, parsedServiceCategories); + + return map; + } + + + + @Test (enabled=false) + public void pasrseCategoriesClass2() throws IOException{ + + String path = "C:\\Git_work\\Git_UGN\\d2-sdnc\\catalog-be\\src\\main\\resources\\import\\tosca\\categories\\categoryTypes.yml"; + + FileReader reader = new FileReader(path); + Yaml yaml=new Yaml(); + + + Map map = (Map) yaml.load(reader); + + Collection values = (Collection) map.values(); + for (Map map2 : values) { + Collection values2 = map2.values(); + for (Object object : values2) { + + + } + } + + { + + } + List collect = values.stream().map(e -> e.get("name")).collect(Collectors.toList()); + +// resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) + + + + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java new file mode 100644 index 0000000000..90dd3a47ae --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java @@ -0,0 +1,343 @@ +/*- + * ============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.externalApis; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.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 com.google.gson.Gson; + +public class GetAssetServlet extends ComponentBaseTest { + + protected User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + protected User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + protected ConsumerDataDefinition consumerDataDefinition; + + @Rule + public static TestName name = new TestName(); + + public GetAssetServlet() { + super(name, GetAssetServlet.class.getName()); + } + + Gson gson = new Gson(); + +// @BeforeMethod +// public void setup() throws Exception { +// +// AtomicOperationUtils.createDefaultConsumer(true); +// +// } + + @Test // (enabled = false) + public void getResourceAssetSuccess() throws Exception { + +// CassandraUtils.truncateAllKeyspaces(); + List expectedAssetNamesList = new ArrayList<>(); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); + resourceDetails.setName("ciResource1"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails.setName("ciResource2"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails.setName("ciResource3"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails.setName("ciResource4"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails.setName("ciResource5"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails.setName("ciResource6"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails.setName("ciResource7"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + expectedAssetNamesList.add(resource.getName()); + + System.out.println("7 VF resources were created"); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + AssetRestUtils.checkComponentTypeInObjectList(resourceAssetList, ComponentTypeEnum.RESOURCE); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_ASSET_LIST); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), body); + + } + + @Test // (enabled = false) + public void getServiceAssetSuccess() throws Exception { + +// CassandraUtils.truncateAllKeyspaces(); + List expectedAssetNamesList = new ArrayList<>(); + ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setName("ciService1"); + RestResponse createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + Service service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService2"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + expectedAssetNamesList.add(service.getName()); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService3"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService4"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService5"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService6"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft(); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService7"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + expectedAssetNamesList.add(service.getName()); + expectedAssetNamesList.add(service.getName()); + + System.out.println("7 Services were created"); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES); + BaseRestUtils.checkSuccess(assetResponse); + + List serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_ASSET_LIST); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), body); + + } + + @Test + public void getToscaModelSuccess() throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(); +// resourceDetails.setName("ciResource11"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + HttpResponse assetResponse = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + String artId = resource.getToscaArtifacts().get("assettoscacsar").getEsId(); + String url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), resource.getUniqueId(), artId); + HttpGet httpGet = createGetRequest(url); + HttpResponse response = httpclient.execute(httpGet); + InputStream inputStream = response.getEntity().getContent(); + ArtifactUiDownloadData artifactUiDownloadData = getArtifactUiDownloadData(IOUtils.toString(inputStream)); + assetResponse = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + inputStream = assetResponse.getEntity().getContent(); + int len = (int) assetResponse.getEntity().getContentLength(); + byte[] res = new byte[len]; + inputStream.read(res, 0, len); + byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes(); + assertEquals(Base64.encodeBase64(res), fromUiDownload); + String fileName = assetResponse.getFirstHeader(Constants.CONTENT_DISPOSITION_HEADER).getValue(); + assertEquals(fileName, new StringBuilder().append("attachment; filename=\"") + .append(artifactUiDownloadData.getArtifactName()).append("\"").toString()); + } + + private HttpGet createGetRequest(String url) { + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + return httpGet; + } + + private ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + try { + ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, + ArtifactUiDownloadData.class); + return artifactUiDownloadData; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} 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 new file mode 100644 index 0000000000..6acc54b54c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java @@ -0,0 +1,262 @@ +/*- + * ============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.externalApis; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +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 { + +// protected User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); +// protected User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); +// protected ConsumerDataDefinition consumerDataDefinition; + + @Rule + public static TestName name = new TestName(); + + public GetCSARofVF() { + super(name, GetCSARofVF.class.getName()); + } + +// Gson gson = new Gson(); + + @BeforeMethod + public void setup() throws Exception { + +// AtomicOperationUtils.createDefaultConsumer(true); +// CassandraUtils.truncateAllKeyspaces(); + + + } + + @Test + public void getResourceToscaModelCheckOutState() throws Exception { + + + Resource resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + +// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID()); + + // validate tosca structure + validateCsarContent(resource, toscaModelCsarFile); + + // Validate audit message + validateAudit(resource); + + + + } + + + + @Test + public void getResourceToscaModelCheckInState() throws Exception { + + Resource resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + +// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID()); + + // validate tosca structure + validateCsarContent(resource, toscaModelCsarFile); + + // Validate audit message + validateAudit(resource); + + + + } + + @Test + public void getRsourceToscaModelCertifyState() throws Exception { + + Resource resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + +// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID()); + + // validate tosca structure + validateCsarContent(resource, toscaModelCsarFile); + + // Validate audit message + validateAudit(resource); + + + } + + + @Test + public void getServiceToscaModelCheckOutState() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + +// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID()); + + // validate tosca structure + validateCsarContent(service, toscaModelCsarFile); + + validateAudit(service); + + + + } + + @Test + public void getServiceToscaModelCheckInState() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true); + +// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID()); + + // validate tosca structure + validateCsarContent(service, toscaModelCsarFile); + + validateAudit(service); + + + } + + @Test + public void getServiceToscaModelCertifyState() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, service, UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + +// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID()); + File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID()); + + // validate tosca structure + validateCsarContent(service, toscaModelCsarFile); + + validateAudit(service); + + } + + + + + + + public void validateCsarContent(Component resource, File toscaModelCsarFile) throws ZipException, IOException { + ZipFile zipFile = new ZipFile(toscaModelCsarFile); + Enumeration 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")); + } + } + } + + public void validateAudit(Component resource) throws Exception { + ExpectedExternalAudit expectedAudit = null; + if (resource.getComponentType().equals(ComponentTypeEnum.RESOURCE)){ + expectedAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_TOSCA_MODEL, ("/" + resource.getUUID() + "/toscaModel")); + } + else expectedAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_TOSCA_MODEL, ("/" + resource.getUUID() + "/toscaModel")); + expectedAudit.setRESOURCE_NAME(resource.getName()); + expectedAudit.setSERVICE_INSTANCE_ID(resource.getUUID()); + expectedAudit.setRESOURCE_TYPE(resource.getComponentType().getValue()); +// AuditValidationUtils.validateExternalAudit(expectedAudit, AuditingActionEnum.GET_TOSCA_MODEL.getName(), null); + + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, expectedAudit.getRESOURCE_NAME()); + AuditValidationUtils.validateExternalAudit(expectedAudit, AuditingActionEnum.GET_TOSCA_MODEL.getName(), body); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java new file mode 100644 index 0000000000..008cdbb1a5 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java @@ -0,0 +1,712 @@ +/*- + * ============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.externalApis; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +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.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.expected.ExpectedExternalAudit; +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 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.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.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class GetFilteredAssetServlet extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(GetAssetServlet.class.getName()); + protected final static String categoryFilterKey = "category"; + protected final static String subCategoryFilterKey = "subCategory"; + protected final static String distributionStatusFilterKey = "distributionStatus"; + protected final static String serviceKey = "service"; + protected final static String resourceKey = "resource"; + protected final static String resourceType = "resourceType"; + protected final static String validFilterParameters = "[" + resourceType + ", "+ subCategoryFilterKey + ", " + categoryFilterKey + "]"; + + @Rule + public static TestName name = new TestName(); + + public GetFilteredAssetServlet() { + super(name, GetFilteredAssetServlet.class.getName()); + } + +// @BeforeMethod +// public void setup() throws Exception { +// AtomicOperationUtils.createDefaultConsumer(true); +// } + + // RESOURCE + // Success + + @Test // (enabled = false) + public void getResourceAssetBySpecifiedCategory() throws Exception { + String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory() }; + List expectedAssetNamesList = new ArrayList<>(); + + Resource resource1 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(resource1.getName()); + Resource resource2 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.DATABASE, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(resource2.getName()); + Resource resource3 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_CONNECTIVITY_CON_POINT, UserRoleEnum.DESIGNER, true).left().value(); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + + } + + // 2 resources has the same category and different subcategory + @Test // (enabled = false) + public void getResourceAssetBySpecifiedCategoryAndSubCategory() throws Exception { + String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory(), subCategoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getSubCategory() }; + // String[] filter2 = {categoryFilterKey + "=" + + // ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getCategory(), + // subCategoryFilterKey + "=" + + // ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory()}; + List expectedAssetNamesList = new ArrayList<>(); + + Resource resource1 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(resource1.getName()); + Resource resource2 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.DATABASE, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true).left().value(); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetBySpecifiedSubCategoryAndCategory() throws Exception { + String[] filter = { subCategoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory(), categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), }; + List expectedAssetNamesList = new ArrayList<>(); + + Resource resource1 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.DATABASE, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(resource2.getName()); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + // Failure + @Test // (enabled = false) + public void getResourceAssetCategoryNotExists() throws Exception { + String[] filter = { categoryFilterKey + "=" + "NotExistingCategory" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(resourceKey, categoryFilterKey, "NotExistingCategory"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetSubCategoryNotExists() throws Exception { + String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory(), subCategoryFilterKey + "=" + "NotExistingSubCategory" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList("Resource", "NotExistingSubCategory", ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory()); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetCategoryNotExistsSubCategoryExists() throws Exception { + String[] filter = { subCategoryFilterKey + "=" + ResourceCategoryEnum.NETWORK_L2_3_GETEWAY.getSubCategory(), categoryFilterKey + "=" + "NotExistingCategory" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(resourceKey, categoryFilterKey, "NotExistingCategory"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetInvalidFilterKey() throws Exception { + String[] filter = { subCategoryFilterKey + "1=" + ResourceCategoryEnum.NETWORK_L2_3_GETEWAY.getSubCategory(), categoryFilterKey + "=" + "NotExistingCategory" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FILTER_KEY.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(subCategoryFilterKey + "1", validFilterParameters); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + // --------------------------------------------------------------------------------------------------------- + // SERVICE + // Success + @Test // (enabled = false) + public void getServiceAssetBySpecifiedCategory() throws Exception { + String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue() }; + List expectedAssetNamesList = new ArrayList<>(); + + Service service1 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(service1.getName()); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + BaseRestUtils.checkSuccess(assetResponse); + + List serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetBySpecifiedCategoryAndDistributionStatus() throws Exception { + String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue(), distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED }; + List expectedAssetNamesList = new ArrayList<>(); + ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true); + + Service service1 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(service1.getName()); + Service service2 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service2.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service2 = (Service) AtomicOperationUtils.changeComponentState(service2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + expectedAssetNamesList.add(service2.getName()); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + BaseRestUtils.checkSuccess(assetResponse); + + List serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetByDistributionStatus() throws Exception { + String[] filter = { distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED }; + List expectedAssetNamesList = new ArrayList<>(); + ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true); + + Service service1 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + expectedAssetNamesList.add(service1.getName()); + Service service2 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value(); + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service2.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service2 = (Service) AtomicOperationUtils.changeComponentState(service2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + ServiceRestUtils.approveServiceDistribution(service2.getUniqueId(), UserRoleEnum.GOVERNOR.getUserId()); + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + BaseRestUtils.checkSuccess(assetResponse); + + List serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + // Failure + @Test // (enabled = false) + public void getServiceAssetCategoryNotExists() throws Exception { + String[] filter = { categoryFilterKey + "=" + "NotExistingCategory" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(serviceKey, categoryFilterKey, "NotExistingCategory"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetInvalidDistributionStatus() throws Exception { + String[] filter = { distributionStatusFilterKey + "=" + "NotExistingDistributionStatus" }; + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(serviceKey, distributionStatusFilterKey, "NotExistingDistributionStatus"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetCategoryExitsDistributionStatusInvalid() throws Exception { + String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue(), distributionStatusFilterKey + "=" + "NotExistingDistributionStatus" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(serviceKey, distributionStatusFilterKey, "NotExistingDistributionStatus"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetCategoryNotExistsDistributionStatus() throws Exception { + String[] filter = { distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, categoryFilterKey + "=" + "NotExistingCategory" }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(serviceKey, categoryFilterKey, "NotExistingCategory"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetInvalidFilterKey() throws Exception { + String[] filter = { distributionStatusFilterKey + "1=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue() }; + + RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FILTER_KEY.name()); + + assertNotNull("check response object is not null after create resouce", assetResponse); + assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode()); + assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode()); + + List variables = Arrays.asList(distributionStatusFilterKey + "1", "[" + categoryFilterKey + ", " + distributionStatusFilterKey + "]"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, assetResponse.getResponse()); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST); + expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter)); + expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString()); + expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + + } + + @Test + public void getFilteredResourceAssetCategoryNotFound() throws Exception { + + String query = "category=Application%20L3%2B"; + RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.RESOURCES, query); + BaseRestUtils.checkErrorResponse(assetResponse, ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, "resource", "category", "Application L3+"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getFilteredAssetListAuditCategoryNotFound(AssetTypeEnum.RESOURCES, "?" + query, "Application L3+"); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + + } + + @Test + public void getFilteredResourceAssetSuccess() throws Exception { + + List expectedAssetNamesList = new ArrayList<>(); + + ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_APP_SERVER); +// resourceDetails.setName("ciResource11"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + expectedAssetNamesList.add(resource.getName()); + + resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_BORDER); +// resourceDetails.setName("ciResource22"); + resourceDetails.setResourceType(ResourceTypeEnum.VFC.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE); +// resourceDetails.setName("ciResource33"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_FIREWALL); +// resourceDetails.setName("ciResource44"); + resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); + createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createResource); + resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + expectedAssetNamesList.add(resource.getName()); + + log.debug("4 resources created"); + String query = "category=Application%20L4%2B"; + RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.RESOURCES, query); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + +// Andrey L. This condition can not be checked in case resources list has two or ore different resource types +// AssetRestUtils.checkResourceTypeInObjectList(resourceAssetList, ResourceTypeEnum.VF); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultFilteredAssetListAudit(AssetTypeEnum.RESOURCES, "?" + query); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + + } + + @Test + public void getFilteredServiceAssetInformationalSuccess() throws Exception { + + List expectedAssetNamesList = new ArrayList<>(); + ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true); + artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType()); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setName("ciService111"); + RestResponse createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + Service service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + + serviceDetails.setName("ciService222"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ServiceReqDetails certifyService = new ServiceReqDetails(service); + LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTION_APPROVED); + AtomicOperationUtils.distributeService(service, false); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService333"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + certifyService = new ServiceReqDetails(service); + LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTION_APPROVED); + AtomicOperationUtils.distributeService(service, false); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService444"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + serviceDetails.setName("ciService555"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + String query = "distributionStatus=Distributed"; + RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.SERVICES, query); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultFilteredAssetListAudit(AssetTypeEnum.SERVICES, "?" + query); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + + } + + @Test + public void getFilteredServiceAssetDeploymentSuccess() throws Exception { + + List expectedAssetNamesList = new ArrayList<>(); + ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true); + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + serviceDetails.setName("ciService666"); + RestResponse createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + Service service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + + serviceDetails.setName("ciService777"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ServiceReqDetails certifyService = new ServiceReqDetails(service); + LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTION_APPROVED); + AtomicOperationUtils.distributeService(service, false); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService888"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId()); + BaseRestUtils.checkSuccess(addInformationalArtifactToService); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + certifyService = new ServiceReqDetails(service); + LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTION_APPROVED); + AtomicOperationUtils.distributeService(service, false); + expectedAssetNamesList.add(service.getName()); + + serviceDetails.setName("ciService999"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + serviceDetails.setName("ciService000"); + createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + BaseRestUtils.checkCreateResponse(createService); + service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + String query = "distributionStatus=Distributed"; + RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.SERVICES, query); + BaseRestUtils.checkSuccess(assetResponse); + + List resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse); + List getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList); + Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element"); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultFilteredAssetListAudit(AssetTypeEnum.SERVICES, "?" + query); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java new file mode 100644 index 0000000000..2cb307cdb8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java @@ -0,0 +1,447 @@ +/*- + * ============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.externalApis; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure; +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.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.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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class GetSpecificAssetMetadataServlet extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public GetSpecificAssetMetadataServlet() { + super(name, GetSpecificAssetMetadataServlet.class.getName()); + } + +// @BeforeMethod +// public void setup() throws Exception { +// AtomicOperationUtils.createDefaultConsumer(true); +// } + + // get specific asset metadata + + // Resource + @Test // (enabled = false) + public void getResourceAssetMetadataSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetMetadataWithResourceInstancesSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resourceVF = ResponseParser.parseToObjectUsingMapper(ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory + .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetMetadataWithNonCertifiedResourceInstancesSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + Resource resource3 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource3 = (Resource) AtomicOperationUtils.changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER, true); + + // certify resource2 and add to VF(VF with resource2 0.1, 1.0 and 1.1 + // versions) + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resourceVF = ResponseParser.parseToObjectUsingMapper(ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetMetadataWithResourceInstancesVfInSubmitForTestingSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Resource resource3 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource3 = (Resource) AtomicOperationUtils.changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER, true); + + // certify resource2 and add to VF(VF with resource2 1.0, 2.0 and 3.0 + // versions) + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetMetadataWithResourceInstancesVfInStartCertificationSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Resource resource3 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource3 = (Resource) AtomicOperationUtils.changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER, true); + + // certify resource2 and add to VF(VF with resource2 1.0, 2.0 and 3.0 + // versions) + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft(); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetMetadataWithResourceInstancesCertifiedVFSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Resource resource3 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource3 = (Resource) AtomicOperationUtils.changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER, true); + + // certify resource2 and add to VF(VF with resource2 1.0, 2.0 and 3.0 + // versions) + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getResourceAssetMetadataWithNonCertifiedResourceInstancesAndArtifactsSuccess() throws Exception { + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + Resource resource2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource2 = (Resource) AtomicOperationUtils.changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + Resource resource3 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); + resource3 = (Resource) AtomicOperationUtils.changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER, true); + + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, true, true); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF, UserRoleEnum.DESIGNER, true, true); + resourceVF = ResponseParser.parseToObjectUsingMapper(ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, resourceVF.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse); + AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + // Import CSAR + + // Service + @Test // (enabled = false) + public void getServiceAssetMetadataSuccess() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES, service.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse); + AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetMetadataWithResourceInstancesSuccess() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + service = ResponseParser.parseToObjectUsingMapper(ServiceRestUtils.getService(service.getUniqueId(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)).getResponse(),Service.class); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES, service.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse); + AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + + } + + @Test // (enabled = false) + public void getServiceAssetMetadataWithNonCertifiedResourceInstancesWithArtifactsSuccess() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, true, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF2, UserRoleEnum.DESIGNER, true, true); + resourceVF2 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true); + resourceVF = (Resource) AtomicOperationUtils + .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + + // service with 0.1, 0.1 and 1.0 RIs versions + service = ResponseParser.parseToObjectUsingMapper(ServiceRestUtils.getService(service.getUniqueId(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)).getResponse(), Service.class); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES, service.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse); + AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + + } + + @Test // (enabled = false) + public void getServiceAssetMetadataWithCertifiedResourceInstancesAndArtifactsOnRIsAndServiceSuccess() + throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, true, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF2, UserRoleEnum.DESIGNER, true, true); + resourceVF2 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, resourceVF, UserRoleEnum.DESIGNER, true, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + + // service with resourceVF 1.0(1 art), 2.0(2 art) versions and + // resourceVF2 1.0(1 art), service 1 artifact version + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, service, UserRoleEnum.DESIGNER, true, true); + service = ResponseParser.parseToObjectUsingMapper(ServiceRestUtils.getService(service.getUniqueId(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)).getResponse(), Service.class); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES, service.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse); + AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + + } + + @Test // (enabled = false) + public void getServiceAssetMetadataWithResourceInstancesServiceInSubmitForTestingSuccess() throws Exception { + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + + Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, true, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF2, UserRoleEnum.DESIGNER, true, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, resourceVF, UserRoleEnum.DESIGNER, true, true); + resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true); + + // service with resourceVF 1.0(1 art), 2.0(2 art) versions and + // resourceVF2 1.0(1 art), service 1 artifact version + AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, service, UserRoleEnum.DESIGNER, true, true); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES, service.getUUID()); + BaseRestUtils.checkSuccess(assetResponse); + + ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse); + AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES); + + // Validate audit message + ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL()); + AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body); + } + + @Test // (enabled = false) + public void getServiceAssetMetadataServiceNotFound() throws Exception { + + String serviceUuid = "notExistingServiceUuid"; + RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES, serviceUuid); + + // Validate audit message + ArrayList variables = new ArrayList<>(); + variables.add(serviceUuid); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, assetResponse.getResponse()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/SearchFilterCategoryExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/SearchFilterCategoryExternalAPI.java new file mode 100644 index 0000000000..ca7c5aefb9 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/SearchFilterCategoryExternalAPI.java @@ -0,0 +1,329 @@ +/*- + * ============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.externalApis; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import org.json.simple.parser.JSONParser; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.SearchCriteriaEnum; +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.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.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + +public class SearchFilterCategoryExternalAPI extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName()); + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + protected Gson gson = new Gson(); + protected JSONParser jsonParser = new JSONParser(); + +// @BeforeMethod +// public void init() throws Exception{ +// AtomicOperationUtils.createDefaultConsumer(true); +// } + + ; + @Rule + public static TestName name = new TestName(); + + public SearchFilterCategoryExternalAPI() { + super(name, SearchFilterCategoryExternalAPI.class.getName()); + + } + + // Search for invalid resourceType + @Test + public void searchWithInvalidFilter() throws Exception { + RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "invalid", ResourceTypeEnum.VFC.toString()); + + Integer expectedResponseCode = 400; + Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode); + + List variables = Arrays.asList("resourceTypeinvalid", "[resourceType, subCategory, category]"); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, restResponse.getResponse()); + + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "invalid=" + ResourceTypeEnum.VFC.toString()); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FILTER_KEY.name()); + expectedExternalAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + expectedExternalAudit.setSTATUS("400"); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL()); + AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + @DataProvider(name="searchForResourceTypeNegativeTest", parallel=true) + public static Object[][] dataProviderSearchForResourceTypeNegativeTest() { + return new Object[][] { + {"invalidResourceType"}, + {""} + }; + } + + // Search for invalid resourceType + @Test(dataProvider="searchForResourceTypeNegativeTest") + public void searchForResourceTypeNegativeTest(String resourceType) throws Exception { + RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), resourceType); + + Integer expectedResponseCode = 400; + Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode); + + List variables = Arrays.asList(); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, restResponse.getResponse()); + + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceType); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name()); + expectedExternalAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + expectedExternalAudit.setSTATUS("400"); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL()); + AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + + // Searching for resource filter incorrect resource type using external API + @Test + public void searchingForResouceFilterIncorrectResouceTypeUsingExternalAPI() throws Exception { + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value(); + List createdResoucesName = new ArrayList(); + createdResoucesName.add(resource.getName()); + + for(ResourceTypeEnum resourceTypeEnum: ResourceTypeEnum.values()) { + // Create resource for each type so it will not return 404 + AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(resourceTypeEnum, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value(); + + RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), resourceTypeEnum.toString()); + + Integer expectedResponseCode = 200; + Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode); + if(resourceTypeEnum == ResourceTypeEnum.VF) { + validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true); + } else { + validateJsonContainResource(restResponse.getResponse(), createdResoucesName, false); + } + + + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString()); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL()); + AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + } + + // Searching for several resource types using external API + @Test + public void searchingForSeveralResouceTypesUsingExternalAPI() throws Exception { + performClean(); + for(ResourceTypeEnum resourceTypeEnum: ResourceTypeEnum.values()) { + List createdResoucesName = new ArrayList(); + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(resourceTypeEnum, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value(); + createdResoucesName.add(resource.getName()); + + RestResponse restResponse = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), resourceTypeEnum.toString()); + + Integer expectedResponseCode = 200; + Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode); + validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true); + + ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString()); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL()); + AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body); + } + } + + // Searching for several resources of type VFCMT using external API + @Test + public void searchingForSeveralResourcesOfTypeVFCMTUsingExternalAPI() throws Exception { + performClean(); + Random random = new Random(); + int numberOfResouceToCreate = random.nextInt(5) + 1; + List createdResoucesName = new ArrayList(); + + for(int i=0; i createdResoucesName = new ArrayList(); + createdResoucesName.add(resource.getName()); + + restResponse = ResourceRestUtils.getResourceListFilterByCategory(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), resourceCategoryEnum.getCategory()); + + Integer expectedResponseCode = 200; + Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode); + validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true); + } + + // Verify search filter by sub-category + @Test + public void validateFilterBySubcategory() throws Exception { + ResourceCategoryEnum resourceCategoryEnum = getRandomCategoryFromResourceCategoryEnum(); + + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, resourceCategoryEnum, UserRoleEnum.DESIGNER, true).left().value(); + List createdResoucesName = new ArrayList(); + createdResoucesName.add(resource.getName()); + + RestResponse restResponse = ResourceRestUtils.getResourceListFilterBySubCategory(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), resourceCategoryEnum.getSubCategory()); + + Integer expectedResponseCode = 200; + Assert.assertEquals(restResponse.getErrorCode(), expectedResponseCode); + validateJsonContainResource(restResponse.getResponse(), createdResoucesName, true); + } + + + protected ResourceCategoryEnum getRandomCategoryFromResourceCategoryEnum() throws Exception { + Random random = new Random(); + int randint = random.nextInt(ResourceCategoryEnum.values().length); + int i = 0; + for(ResourceCategoryEnum resourceTypeEnum: ResourceCategoryEnum.values()) { + if(randint == i) { + return resourceTypeEnum; + } + i++; + } + return null; + } + + protected CategoryDefinition getRandomCategory() throws Exception { + Random random = new Random(); + + RestResponse restResponse = CategoryRestUtils.getAllCategories(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "resources"); + Gson gson = new Gson(); + JsonElement jelement = new JsonParser().parse(restResponse.getResponse()); + JsonArray jsonArray = jelement.getAsJsonArray(); + + CategoryDefinition categoryDefinition = gson.fromJson(jsonArray.get(random.nextInt(jsonArray.size())), CategoryDefinition.class); + + return categoryDefinition; + } + + protected void validateJsonContainResource(String json, List resourceNameList, Boolean willBeFound) { + int lenResourceNameList = resourceNameList.size(); + Gson gson = new Gson(); + JsonElement jsonElement = new JsonParser().parse(json); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + for(JsonElement jElement: jsonArray) { + ResourceReqDetails jResource = gson.fromJson(jElement, ResourceReqDetails.class); + + if(resourceNameList.contains(jResource.getName())) { + resourceNameList.remove(jResource.getName()); + } + } + + if(resourceNameList.size() != 0 && willBeFound) { + Assert.assertTrue(false, "Created resource not found on search filtered by category."); + } else if (lenResourceNameList != resourceNameList.size() & !willBeFound) { + Assert.assertTrue(false, "Some of the resources found when expect that no resource will be found."); + } + } + + + + protected void validateJsonContainResourceCategory(String json, ResourceCategoryEnum resourceCategoryEnum) { + Gson gson = new Gson(); + JsonElement jelement = new JsonParser().parse(json); + JsonArray jsonArray = jelement.getAsJsonArray(); + for(JsonElement jsonElement : jsonArray){ + CategoryDefinition categoryDefinition = gson.fromJson(jsonElement, CategoryDefinition.class); + + if(categoryDefinition.getName().equals(resourceCategoryEnum.getCategory())) { + for(SubCategoryDefinition subcategory: categoryDefinition.getSubcategories()) { + if(subcategory.getName().equals(resourceCategoryEnum.getSubCategory())) { + return; + } + } + } + + } + + Assert.assertTrue(false, "Category and subcategory not found in categories list."); + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/UserAPIs.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/UserAPIs.java new file mode 100644 index 0000000000..ceafe204c8 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/UserAPIs.java @@ -0,0 +1,556 @@ +/*- + * ============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.externalApis; + +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +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; +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.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.EcompUserRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +public class UserAPIs extends ComponentBaseTest { + + @Rule + public static TestName name = new TestName(); + + public UserAPIs() { + super(name, UserAPIs.class.getName()); + } + + public User adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + + @Test + public void createUserAllPosibleRolesThenDeactivate() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + + List allRoles = getAllRoles(); + + for (EcompRole ecompRole2 : allRoles) { + try { + + ///get list of users + List allusersList = getAllusersList(); + int sizeBeforeChange = allusersList.size(); + + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) ecompRole2.getId()); + ecompRole.setName(ecompRole2.getName()); + System.out.println(ecompRole2.getName()); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + ///get list of users verify list size changed + allusersList = getAllusersList(); + int sizeAfterChange = allusersList.size(); + + Assert.assertEquals(sizeBeforeChange + 1, sizeAfterChange, "Expected that list will change."); + sizeBeforeChange = sizeAfterChange; + pushUser = EcompUserRestUtils.pushUser(ecompUser); + + //deactivate user + ecompRole = new EcompRole();; + List list= new ArrayList(); + list.add(ecompRole); + + RestResponse deactivateUserResponse = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + BaseRestUtils.checkSuccess(deactivateUserResponse); + + ///get list of users verify list size changed + allusersList = getAllusersList(); + sizeAfterChange = allusersList.size(); + Assert.assertEquals(sizeBeforeChange, sizeAfterChange + 1, "Expected that list will change."); + + } finally { + deleteUser(ecompUser.getLoginId()); + } + + } + + } + + @Test + public void createSameUserTwiceTest() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + try { + + ///get list of users + List allusersList = getAllusersList(); + int sizeBeforeChange = allusersList.size(); + + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + ///get list of users verify list size changed + allusersList = getAllusersList(); + int sizeAfterChange = allusersList.size(); + + assertTrue("List is Equel" , sizeBeforeChange != sizeAfterChange ); + pushUser = EcompUserRestUtils.pushUser(ecompUser); + + } finally { + deleteUser(ecompUser.getLoginId()); + } + + } + + @Test + public void createSameUserTwiceDiffrentDataTest() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + try { + ///get list of users + List allusersList = getAllusersList(); + int sizeBeforeChange = allusersList.size(); + + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + ///get list of users verify list size changed + allusersList = getAllusersList(); + int sizeAfterChange = allusersList.size(); + + assertTrue("List is Equel" , sizeBeforeChange != sizeAfterChange ); + + //update role + ecompRole.setId((long) 2); + ecompRole.setName("DESIGNER"); + setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + + pushUser = EcompUserRestUtils.pushUser(ecompUser); + + } finally { + deleteUser(ecompUser.getLoginId()); + } + + } + + @Test + public void updateUserRoleTest() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + try { + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + List userRolesBefore = getUserRoles(ecompUser); + + //update role + ecompRole = new EcompRole(); + ecompRole.setId((long) 2); + ecompRole.setName("DESIGNER"); + List list= new ArrayList(); + list.add(ecompRole); + + EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + + List userRolesAfter = getUserRoles(ecompUser); + + assertFalse("role wasn't changed", userRolesBefore.equals(userRolesAfter)); + } finally { + deleteUser(ecompUser.getLoginId()); + } + + } + + @Test + public void addUserCreateResource() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + Resource resource = new Resource(); + + try { + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 2); + ecompRole.setName("DESIGNER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + UserRoleEnum.DESIGNER.setUserId(ecompUser.getLoginId()); + resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + + } finally { + ResourceRestUtils.deleteResource(resource.getUniqueId(), adminUser.getUserId()); + deleteUser(ecompUser.getLoginId()); + } + + } + + // First try update to Tester and verify it not success + // Then try to deactivate and verify it not success + @Test + public void changeUserRoleWithCheckOutResourceThenDeactivate() throws Exception { + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + Resource resource = new Resource(); + try { + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 2); + ecompRole.setName("DESIGNER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + UserRoleEnum.DESIGNER.setUserId(ecompUser.getLoginId()); + resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + + int sizeBeforeChange = getAllusersList().size(); + + //update role + ecompRole = new EcompRole(); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + List list= new ArrayList(); + list.add(ecompRole); + + RestResponse pushUserRoles = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + Assert.assertEquals(pushUserRoles.getErrorCode(), (Integer)BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR, "Not correct response code"); + + //deactivate user + ecompRole = new EcompRole();; + list= new ArrayList(); + list.add(ecompRole); + + RestResponse deactivateUserResponse = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + Assert.assertEquals(deactivateUserResponse.getErrorCode(), (Integer)BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR, "Not correct response code"); + + ///get list of users verify list size changed + int sizeAfterChange = getAllusersList().size(); + Assert.assertEquals(sizeBeforeChange, sizeAfterChange, "Expected that list will not change."); + + } finally { + ResourceRestUtils.deleteResource(resource.getUniqueId(), adminUser.getUserId()); + deleteUser(ecompUser.getLoginId()); + } + } + + @Test + public void deactivateUserRoleWithStartTestingResource() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + Resource resource= new Resource(); + + try { + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 2); + ecompRole.setName("DESIGNER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + int sizeBeforeChange = getAllusersList().size(); + UserRoleEnum.DESIGNER.setUserId(ecompUser.getLoginId()); + + resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true); + + + //update role + ecompRole = new EcompRole(); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + List list= new ArrayList(); + list.add(ecompRole); + + RestResponse pushUserRoles = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + BaseRestUtils.checkSuccess(pushUserRoles); + + UserRoleEnum.TESTER.setUserId(ecompUser.getLoginId()); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.TESTER, LifeCycleStatesEnum.STARTCERTIFICATION, true); + + //deactivate user + ecompRole = new EcompRole();; + list= new ArrayList(); + list.add(ecompRole); + + RestResponse deactivateUserResponse = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + Assert.assertEquals(deactivateUserResponse.getErrorCode(), (Integer)BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR, "Not correct response code"); + + ///get list of users verify list size changed + int sizeAfterChange = getAllusersList().size(); + Assert.assertEquals(sizeBeforeChange, sizeAfterChange, "Expected that list will not change."); + + } finally { + ResourceRestUtils.deleteResource(resource.getUniqueId(), adminUser.getUserId()); + deleteUser(ecompUser.getLoginId()); + } + } + + @Test + public void changeUserRoleWithStartTestingResource() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + Resource resource= new Resource(); + + try { + //create user + ecompUser.setLoginId(getUser()); + ecompRole.setId((long) 2); + ecompRole.setName("DESIGNER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + UserRoleEnum.DESIGNER.setUserId(ecompUser.getLoginId()); + + resource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true); + + + //update role + ecompRole = new EcompRole(); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + List list= new ArrayList(); + list.add(ecompRole); + + RestResponse pushUserRoles = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list); + BaseRestUtils.checkSuccess(pushUserRoles); + + } finally { + ResourceRestUtils.deleteResource(resource.getUniqueId(), adminUser.getUserId()); + deleteUser(ecompUser.getLoginId()); + } + } + + @Test + public void fillAllEcompFields() throws Exception { + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + try { + + ///get list of users + List allusersList = getAllusersList(); + int sizeBeforeChange = allusersList.size(); + + //create user + ecompUser.setLoginId(getUser()); + ecompUser.setOrgId((long) 123); + ecompUser.setManagerId("ci4321"); + ecompUser.setFirstName("firstName"); + ecompUser.setMiddleInitial("middleInitial"); + ecompUser.setLastName("lastName"); + ecompUser.setPhone("phone"); + ecompUser.setEmail("email@email.com"); + ecompUser.setHrid("hrid"); + ecompUser.setOrgUserId("orgUserId"); + ecompUser.setOrgCode("orgCode"); + ecompUser.setOrgManagerUserId("ci1234"); + ecompUser.setJobTitle("jobTitle"); + ecompUser.setActive(true); + + + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + ///get list of users verify list size changed + allusersList = getAllusersList(); + int sizeAfterChange = allusersList.size(); + + assertTrue("List is Equel" , sizeBeforeChange != sizeAfterChange ); + + } finally { + + deleteUser(ecompUser.getLoginId()); + } + } + + @Test + public void missingMandatoryFieldRole() throws Exception { + + EcompUser ecompUser = new EcompUser(); + try { + ///get list of users + List allusersList = getAllusersList(); + int sizeBeforeChange = allusersList.size(); + + //create user + ecompUser.setLoginId(getUser()); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + BaseRestUtils.checkSuccess(pushUser); + + ///get list of users verify list size changed + allusersList = getAllusersList(); + int sizeAfterChange = allusersList.size(); + + assertTrue("List is Equel" , sizeBeforeChange != sizeAfterChange ); + + } finally { + deleteUser(ecompUser.getLoginId()); + } + } + + @Test + public void missingMandatoryFieldATTid() throws Exception { + + EcompUser ecompUser = new EcompUser(); + EcompRole ecompRole = new EcompRole(); + try { + + //create user + ecompUser.setLoginId(""); + ecompRole.setId((long) 1); + ecompRole.setName("TESTER"); + Set setRoles = new HashSet(); + setRoles.add(ecompRole); + ecompUser.setRoles(setRoles); + RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser); + assertTrue("wrong response code :" , pushUser.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT); + + } finally { + deleteUser(ecompUser.getLoginId()); + } + + + } + + private List getUserRoles(EcompUser ecompUser) throws IOException { + RestResponse userRoles = EcompUserRestUtils.getUserRoles(ecompUser.getLoginId()); + Type listType = new TypeToken>() {}.getType(); + List roleList = new Gson().fromJson(userRoles.getResponse(), listType); + return roleList; + } + + private void deleteUser(String userId) throws IOException { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + defaultUser.setUserId(userId); + + UserRestUtils.deleteUser(defaultUser, adminUser, true); + } + + private List getAllusersList() throws IOException { + RestResponse allUsers = EcompUserRestUtils.getAllUsers(); + + Type listType = new TypeToken>() {}.getType(); + List usersList = new Gson().fromJson(allUsers.getResponse(), listType); + + return usersList; + } + + private List getAllRoles() throws IOException { + RestResponse allRoles = EcompUserRestUtils.getAllAvailableRoles(); + + Type listType = new TypeToken>() {}.getType(); + List availableRoles = new Gson().fromJson(allRoles.getResponse(), listType); + + return availableRoles; + } + + private String getUser() { + int nextInt = rnd.nextInt(8999) + 1000; +// String returnMe = "ci"+ new BigInteger(getRandomNumber(4)); + String returnMe = "ci"+ nextInt; + System.out.println(returnMe); + + + return returnMe; + } + + private static Random rnd = new Random(); + + public static String getRandomNumber(int digCount) { + StringBuilder sb = new StringBuilder(digCount); + for(int i=1; i <= digCount; i++){ + sb.append((char)('0' + rnd.nextInt(10))); + } + return sb.toString(); + } +} 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 new file mode 100644 index 0000000000..f93958542d --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java @@ -0,0 +1,396 @@ +/*- + * ============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.externalApis; + +import static java.util.Arrays.asList; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.simple.parser.JSONParser; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.dao.api.ActionStatus; +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.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.SearchCriteriaEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +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.AssetRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtilsExternalAPI; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; + +public class VFCMTExternalAPI extends ComponentBaseTest { + + private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName()); + protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K"; + protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk"; + + protected Config config = Config.instance(); + protected String contentTypeHeaderData = "application/json"; + protected String acceptHeaderDate = "application/json"; + + + + protected Gson gson = new Gson(); + protected JSONParser jsonParser = new JSONParser(); + + + protected String serviceVersion; + protected ResourceReqDetails resourceDetails; + protected User sdncUserDetails; + protected ServiceReqDetails serviceDetails; + + +// @BeforeMethod +// public synchronized void init() throws Exception{ +// AtomicOperationUtils.createDefaultConsumer(true); +// } + + + @Rule + public static TestName name = new TestName(); + + public VFCMTExternalAPI() { + super(name, VFCMTExternalAPI.class.getName()); + + } + + // Create VFCMT - validate response + search external api + retrieve metadata via external api - success flow + @Test + public void createVfcmt() throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString()); + + RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser); + ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parsedCreatedResponse.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(parsedCreatedResponse.getName()); + AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body); + + // search for vfcmt via external api - validate created resource exist + RestResponse searchResult = ResourceRestUtils.getResourceListFilterByCriteria(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), AssetTypeEnum.RESOURCES.getValue(), SearchCriteriaEnum.RESOURCE_TYPE.getValue(), ResourceTypeEnum.VFCMT.toString()); + JsonArray listSearchResult = gson.fromJson(searchResult.getResponse(), JsonArray.class); + boolean found = false; + for(JsonElement result: listSearchResult) { + ResourceAssetStructure parsedResult = gson.fromJson(result, ResourceAssetStructure.class); + if(parsedResult.getName().equals(defaultResource.getName())) { + found = true; + } + } + Assert.assertEquals(found, true); + + // get created vfcmt metadata via external api - validate data + RestResponse resourceMetadata = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES, parsedCreatedResponse.getUuid()); + ResourceAssetStructure parsedMetadata = gson.fromJson(resourceMetadata.getResponse(), ResourceAssetStructure.class); + + Assert.assertEquals(parsedCreatedResponse.getUuid(), parsedMetadata.getUuid()); + Assert.assertEquals(parsedCreatedResponse.getInvariantUUID(), parsedMetadata.getInvariantUUID()); + Assert.assertEquals(parsedCreatedResponse.getName(), parsedMetadata.getName()); + Assert.assertEquals(parsedCreatedResponse.getVersion(), parsedMetadata.getVersion()); + Assert.assertEquals(parsedCreatedResponse.getCategory(), parsedMetadata.getCategory()); + Assert.assertEquals(parsedCreatedResponse.getSubCategory(), parsedMetadata.getSubCategory()); + Assert.assertEquals(parsedCreatedResponse.getResourceType(), parsedMetadata.getResourceType()); + Assert.assertEquals(parsedCreatedResponse.getLifecycleState(), parsedMetadata.getLifecycleState()); + Assert.assertEquals(parsedCreatedResponse.getLastUpdaterUserId(), parsedMetadata.getLastUpdaterUserId()); + Assert.assertEquals(parsedCreatedResponse.getLastUpdaterFullName(), parsedMetadata.getLastUpdaterFullName()); + Assert.assertEquals(parsedCreatedResponse.getToscaResourceName(), parsedMetadata.getToscaResourceName()); + } + + + + // Create two VFCMT with same name - validate error + audit - failure flow + @Test + public void createTwoVfcmtWithSameName() throws Exception { + User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString()); + + // create vfcmt + RestResponse firstTryToCreate = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser); + ResourceAssetStructure parsedCreatedResponse = gson.fromJson(firstTryToCreate.getResponse(), ResourceAssetStructure.class); + + // auditing verification + AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API; + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parsedCreatedResponse.getName()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(parsedCreatedResponse.getName()); + AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body); + + // try to create another vfcmt wit same name + RestResponse secondTryToCreate = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser); + Assert.assertEquals((int)secondTryToCreate.getErrorCode(), 409); + + body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "409"); + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name()); + List variables = asList(ComponentTypeEnum.RESOURCE.getValue(), defaultResource.getName()); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + expectedResourceAuditJavaObject.setStatus("409"); + AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body); + } + + + + @DataProvider(name="createVfcmtVariousFailureFlows", parallel=true) + public static Object[][] dataProviderCreateVfcmtVariousFailureFlows() { + return new Object[][] { + {"name_missing"}, + {"name_to_long"}, + {"name_with_invalid_char"}, + {"description_missing"}, + {"description_to_long"}, + {"description_with_invalid_char"}, + {"resource_type_missing"}, + {"resource_type_invalid"}, + {"category_type_missing"}, + {"category_type_invalid"}, + {"subcategory_type_missing"}, + {"subcategory_type_invalid"}, + {"vendor_name_missing"}, + {"vendor_name_to_long"}, + {"vendor_name_with_invalid_char"}, + {"vendor_release_missing"}, + {"vendor_release_to_long"}, + {"vendor_release_with_invalid_char"}, + {"tags_missing"}, + {"tags_to_long"}, + {"tags_invalid"}, + {"icon_missing"}, + {"user_contact_missing"}, + {"user_contact_invalid"}, + }; + } + + // Various failure flows + @Test(dataProvider="createVfcmtVariousFailureFlows") + public void createVfcmtVariousFailureFlows(String flow) throws Exception { + + 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()); + + ErrorInfo errorInfo = null; + List variables = null; + AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API; + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(defaultResource.getName()); + Map body = new HashMap<>(); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, defaultResource.getName()); + + switch (flow) { + case "name_missing": + defaultResource.setName(""); + List resourceTags = defaultResource.getTags(); + resourceTags.add(""); + defaultResource.setTags(resourceTags); + expectedResourceAuditJavaObject.setResourceName(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_COMPONENT_NAME.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + break; + case "name_to_long": + defaultResource.setName("asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1"); + expectedResourceAuditJavaObject.setResourceName("asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue(), "1024"); + + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1"); + break; + case "name_with_invalid_char": + defaultResource.setName("!@#$%^&*("); + expectedResourceAuditJavaObject.setResourceName("!@#$%^&*("); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_COMPONENT_NAME.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "!@#$%^&*("); + break; + case "description_missing": + defaultResource.setDescription(""); + expectedResourceAuditJavaObject.setDesc(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "description_to_long": + defaultResource.setDescription("asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1"); + expectedResourceAuditJavaObject.setDesc("asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue(), "1024"); + break; + case "description_with_invalid_char": + defaultResource.setDescription("\uC2B5"); + expectedResourceAuditJavaObject.setDesc("t"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + // TODO: defect on the flow - need to get error instead create VFC + case "resource_type_missing": + defaultResource.setResourceType(""); + expectedResourceAuditJavaObject.setResourceType(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.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()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "category_type_missing": + defaultResource.setCategory(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + // TODO: not correct response code in this flow - 500 instead 400 + case "category_type_invalid": + defaultResource.setCategory("invalid"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_CATEGORY.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "subcategory_type_missing": + defaultResource.setSubcategory(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_SUBCATEGORY.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + // TODO: not correct error - it not missing it not correct + case "subcategory_type_invalid": + defaultResource.setSubcategory("invalid"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_SUBCATEGORY.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "vendor_name_missing": + defaultResource.setVendorName(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_NAME.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "vendor_name_to_long": + defaultResource.setVendorName("asdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdff"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT.name()); + variables = asList("25"); + break; + case "vendor_name_with_invalid_char": + defaultResource.setVendorName("!@#$*()&*^%$#@"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_VENDOR_NAME.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "vendor_release_missing": + defaultResource.setVendorRelease(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_RELEASE.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "vendor_release_to_long": + defaultResource.setVendorRelease("asdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdff"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT.name()); + variables = asList("25"); + break; + case "vendor_release_with_invalid_char": + defaultResource.setVendorRelease("!@#$*()&*^%$#@"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_VENDOR_RELEASE.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "tags_missing": + defaultResource.setTags(asList("")); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue(), "tag"); + break; + case "tags_to_long": + defaultResource.setTags(asList("asdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdff")); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name()); + variables = asList("1024"); + break; + case "tags_invalid": + defaultResource.setTags(asList("asfdg")); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "icon_missing": + defaultResource.setIcon(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_ICON.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "user_contact_missing": + defaultResource.setContactId(""); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CONTACT.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + case "user_contact_invalid": + default: + defaultResource.setContactId("abcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfdabcderfffdfdfd"); + errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_CONTACT.name()); + variables = asList(ComponentTypeEnum.RESOURCE.getValue()); + break; + } + + // create vfcmt + RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser); + + expectedResourceAuditJavaObject.setStatus("400"); + expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables)); + AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body); + + } + + + + + + + + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java b/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java new file mode 100644 index 0000000000..5e9e02c479 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java @@ -0,0 +1,70 @@ +/*- + * ============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.post; + +import java.io.File; + +import org.openecomp.sdc.be.dao.DAOTitanStrategy; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; + +public class Install { + public static void main(String[] args) { + + if (args == null || args.length == 0) { + System.out.println("Usage: org.openecomp.sdc.post.Install path_to_titan.properties"); + System.exit(1); + } + String titanPropsFile = args[0]; + + if (!isFileExists(titanPropsFile)) { + System.exit(2); + } + + if (!createTitanSchema(titanPropsFile)) { + System.exit(3); + } + + System.exit(0); + } + + private static boolean createTitanSchema(String titanPropsFile) { + TitanGraphClient titanGraphClient = new TitanGraphClient(new DAOTitanStrategy()); + TitanOperationStatus status = titanGraphClient.createGraph(titanPropsFile); + if (TitanOperationStatus.OK == status) { + System.out.println("Titan schema ,indexes and default values created successfully."); + return true; + } else { + System.out.println( + "Problem while creating titan schema ,indexes and default values. (" + status.name() + ")"); + return false; + } + } + + private static boolean isFileExists(String titanPropsFile) { + File f = new File(titanPropsFile); + if (!f.exists()) { + System.out.println(titanPropsFile + " not found"); + return false; + } + return true; + } +} diff --git a/test-apis-ci/src/main/resources/ci/conf/attsdc-packages.yaml b/test-apis-ci/src/main/resources/ci/conf/attsdc-packages.yaml new file mode 100644 index 0000000000..5d1a3e1537 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/attsdc-packages.yaml @@ -0,0 +1,12 @@ +packages: + - org.openecomp.sdc.ci.tests.execute.general + - org.openecomp.sdc.ci.tests.execute.user + - org.openecomp.sdc.ci.tests.execute.property + - org.openecomp.sdc.ci.tests.execute.lifecycle + - org.openecomp.sdc.ci.tests.execute.resource + - org.openecomp.sdc.ci.tests.execute.service + - org.openecomp.sdc.ci.tests.execute.artifacts + - org.openecomp.sdc.ci.tests.execute.imports + - org.openecomp.sdc.ci.tests.execute.category + - org.openecomp.sdc.ci.tests.execute.distribution + - org.openecomp.sdc.ci.tests.execute.product \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml new file mode 100644 index 0000000000..7273344672 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml @@ -0,0 +1,93 @@ +outputFolder: target +reportName: index.html +catalogBeHost: behost +catalogFeHost: fehost +esHost: eshost +disributionClientHost: disClient +catalogFePort: 8181 +catalogBePort: 8080 +disributionClientPort: 8181 +isDistributionClientRunning: true +esPort: 9200 +neoHost: neoHost +neoPort: 7474 +neoDBusername: neo4j +neoDBpassword: 123456 +windowsDownloadDirectory: "c:\\apache-ftpserver-1.1.0\\res\\home" + +resourceConfigDir: src/test/resources/CI/tests +componentsConfigDir: src/test/resources/CI/components +importResourceConfigDir: ../catalog-be/src/main/resources/import/tosca/capability-types +importResourceTestsConfigDir: src/test/resources/CI/importResourceTests +errorConfigurationFile: ../catalog-be/src/main/resources/config/error-configuration.yaml +configurationFile: ../catalog-be/src/main/resources/config/configuration.yaml +importTypesConfigDir: src/test/resources/CI/importTypesTest + + +titanPropertiesFile: src/main/resources/ci/conf/titan.properties +cassandraHost: 127.0.0.1 +cassandraAuthenticate: false +cassandraUsername: koko +cassandraPassword: bobo +cassandraSsl: false +cassandraTruststorePath : /path/path +cassandraTruststorePassword : 123123 +cassandraAuditKeySpace: sdcaudit +cassandraArtifactKeySpace: sdcartifact +url: http://localhost:8181/sdc1/proxy-designer1#/dashboard + + +stopOnClassFailure: false + +#List of non-abstract resources to keep during titan cleanup between tests +#Only 1.0 version will be kept +resourcesNotToDelete: + - Compute + - Database + - ObjectStorage + - BlockStorage + - LoadBalancer + - Port + - Network + - Root + - ContainerApplication + - ContainerRuntime + - DBMS + - SoftwareComponent + - WebApplication + - WebServer + - CinderVolume + - ContrailVirtualNetwork + - NeutronNet + - NeutronPort + - NovaServer + - AbstractSubstitute + - ContrailAbstractSubstitute + - ContrailCompute + - ContrailNetworkRules + - ContrailPort + - ContrailV2NetworkRules + - ContrailV2VirtualMachineInterface + - ContrailV2VirtualNetwork + - ContrailVirtualNetwork + - VL ELINE + - SecurityRules + - VL + +#Resource categories to keep (including all their subcategories) +resourceCategoriesNotToDelete: + - Generic + - Network L2-3 + - Network L4+ + - Application L4+ + - Network Connectivity + - DCAE Component + - Template + - Allotted Resource + +#Service categories to keep +serviceCategoriesNotToDelete: + - Mobility + - Network L1-3 + - Network L4+ + - VoIP Call Control \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/conf/extent-config.xml b/test-apis-ci/src/main/resources/ci/conf/extent-config.xml new file mode 100644 index 0000000000..ab04b2678a --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/extent-config.xml @@ -0,0 +1,51 @@ + + + + + + standard + + + + UTF-8 + + + + https + + + ASDC Automation Report + + + ASDC Automation Report + + + + + + + yyyy-MM-dd + + + + HH:mm:ss + + + + "); + $('.logo-content' ).remove(); + $('.charts div:nth-child(2)').remove(); + }); + ]]> + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/conf/log4j.properties b/test-apis-ci/src/main/resources/ci/conf/log4j.properties new file mode 100644 index 0000000000..d313e92b55 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/log4j.properties @@ -0,0 +1,34 @@ +# Define the root logger with appender file +log4j.rootLogger = INFO, FILE, stdout + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender +log4j.appender.FILE.File=${targetlog}logs/ci-log.out + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%10c] : %m%n + +# Set the maximum file size before rollover +log4j.appender.FILE.maxFileSize=5MB + +# Set the the backup index +log4j.appender.FILE.maxBackupIndex=10 + + +############################################################# + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n + +log4j.logger.org.apache.cassandra.service.StorageProxy=INFO +log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout + +log4j.logger.org.openecomp.sdc.ci.tests.utils=INFO, FILE, stdout +log4j.additivity.org.openecomp.sdc.ci.tests.utils=false + + diff --git a/test-apis-ci/src/main/resources/ci/conf/log4j.xml b/test-apis-ci/src/main/resources/ci/conf/log4j.xml new file mode 100644 index 0000000000..6db233a1da --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/log4j.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/conf/testngLifeCycle.xml b/test-apis-ci/src/main/resources/ci/conf/testngLifeCycle.xml new file mode 100644 index 0000000000..aa390dc213 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/testngLifeCycle.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/conf/titan.properties b/test-apis-ci/src/main/resources/ci/conf/titan.properties new file mode 100644 index 0000000000..42e1998f89 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/titan.properties @@ -0,0 +1,8 @@ +storage.backend=cassandra +#storage.hostname=cassandrahost +storage.hostname=localhost +storage.port=9160 + +cache.db-cache = false + + diff --git a/test-apis-ci/src/main/resources/ci/conf/truststore b/test-apis-ci/src/main/resources/ci/conf/truststore new file mode 100644 index 0000000000..bdec93d862 Binary files /dev/null and b/test-apis-ci/src/main/resources/ci/conf/truststore differ diff --git a/test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh b/test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh new file mode 100644 index 0000000000..0d494d919d --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh @@ -0,0 +1,75 @@ +#!/bin/bash + +function help_usage () +{ + echo "$0 -ip -f " + echo "for example: -ip 127.0.0.1 -f /var/tmp/userToAdd.txt" + exit +} + +function check_file_existance () +{ +echo "check_file_existance $1" +if [ $1 == "" ]; then + echo "Please provide full path to user file" + exit; +elif [ -f $1 ]; then + source $1 + USERS=("${USER_LIST[@]}") + echo "file exist" $1 +else + echo "Provided user file does not exist" + exit +fi +} + +function check_ip_existance () +{ +if [ $1 == "" ]; then + echo "Please provide ip address" + exit; +fi +} + +function addUser () +{ + #for user in "${USER_LIST[@]}"; do + for user in "${USERS[@]}"; do + PING=`ping -c 1 $IP > /var/tmp/ping.log` + pattern1='100% packet loss' + pattern2='Host Unreachable' + COUNT=`egrep -c "$pattern1|$pattern2" /var/tmp/ping.log` + if [ $COUNT -eq 0 ]; then + # curl -i -X post -d '{ "userId" : "kk1123", "role" : "ADMIN" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" http://192.168.111.9:8080/sdc2/rest/v1/user + userId=`echo $user|awk '{print $1}'` + role=`echo $user|awk '{print $2}'` + curl -i -X post -d '{ "userId" : "'${userId}'", "role" : "'${role}'" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" http://${IP}:8080/sdc2/rest/v1/user + else + echo "Host" $IP "Is Unreachable" + fi + done +} + +#main +[ $# -eq 0 ] && help_usage +while [ $# -ne 0 ]; do + case $1 in + "-f") + USER_FILE=$2 + shift 1 + shift 1 + ;; + -ip) + IP=$2 + shift 1 + shift 1 + ;; + *) +# help_usage + ;; + esac +done + +check_file_existance $USER_FILE +check_ip_existance $IP +addUser diff --git a/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh b/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh new file mode 100644 index 0000000000..30094fe235 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh @@ -0,0 +1,66 @@ +#!/bin/bash + +REPORT_NAME=$1 +VERSION=$2 +ENV=$3 +IP=$4 + +if [ -z "$REPORT_NAME" ] + then + source ExtentReport/versions.info + now=$(date -d '+7 hour' "+%Y-%m-%d_%H_%M") + REPORT_NAME="${now}" + VERSION="${osVersion}" + if [[ $env == *"DEV20"* ]] + then + ENV="Nightly" + else + ENV="" + fi + + fi + +/usr/bin/expect << EOF +spawn ssh admin@${IP} mkdir -p -m 775 /home/admin/reports/${ENV}/${VERSION}/APIs/ + +expect { + -re ".*es.*o.*" { + exp_send "yes\r" + exp_continue + } + -re ".*sword.*" { + exp_send "Aa123456\r" + } +} + +expect eof + +spawn scp -r ExtentReport admin@${IP}:/home/admin/reports/${ENV}/${VERSION}/APIs/${REPORT_NAME}/ + +expect { + -re ".*es.*o.*" { + exp_send "yes\r" + exp_continue + } + -re ".*sword.*" { + exp_send "Aa123456\r" + } +} + +expect eof + +spawn ssh admin@${IP} chmod -R 775 /home/admin/reports/${ENV}/${VERSION}/APIs/${REPORT_NAME}/ + +expect { + -re ".*es.*o.*" { + exp_send "yes\r" + exp_continue + } + -re ".*sword.*" { + exp_send "Aa123456\r" + } +} + +expect eof + +EOF diff --git a/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh b/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh new file mode 100644 index 0000000000..4c23a7973e --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +now=$(date +'%Y%-m%d%H%M') + +REPORT_NAME=$1 +VERSION=$2 +ENV=$3 + +RECIPIENTS1="dl-sdcqa@intl.att.com,ml636r@intl.att.com,bl5783intl.att.com,ak314p@intl.att.com,el489u@intl.att.com,hk096q@intl.att.com,bs5719@intl.att.com" +RECIPIENTS2="dl-asdcqa@intl.att.com" + +source ExtentReport/versions.info +if [ -z "$REPORT_NAME" ] + then + now=$(date -d '+7 hour' "+%Y-%m-%d_%H_%M") + REPORT_NAME="${now}" + VERSION="${osVersion}" +fi + +if [[ $env == *"DEV20"* ]] + then + ENV="Nightly" + RECIPIENTS=$RECIPIENTS1 + else + ENV="" + RECIPIENTS=$RECIPIENTS2 +fi + + +#REPORT_ZIP_FILE=ExtentReport_${now}.zip +REPORT_FOLDER='ExtentReport' +REPORT_HTML_FILE=${REPORT_FOLDER}/*Report.html +BODY_MESSAGE='Hello, \n\n Please find automation results on following link: \n\n http://asdc-srv-210-45.tlv.intl.att.com/'${ENV}'/'${VERSION}'/APIs/'${REPORT_NAME}'/SDC_CI_Extent_Report.html \n\nThanks, \nSDC QA Team\n\n ' + +#OLD_FILE=$(find ./ -type f -name ${REPORT_ZIP_FILE} -print) +#if [ ! -z ${OLD_FILE} ] +#then +# rm -f ${REPORT_ZIP_FILE} +# echo "Removing old zip file............" +#fi + +#echo "Creating new zip file" +#zip -r ${REPORT_ZIP_FILE} ./${REPORT_FOLDER} + + +echo -e ${BODY_MESSAGE} | mail -s 'External APIs Automation '$ENV' results - ASDC '$VERSION -r 'ASDC@Automation.team' $RECIPIENTS diff --git a/test-apis-ci/src/main/resources/ci/scripts/startTest.sh b/test-apis-ci/src/main/resources/ci/scripts/startTest.sh new file mode 100644 index 0000000000..d3c15026cd --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/scripts/startTest.sh @@ -0,0 +1,153 @@ +#!/bin/bash +REMOTE_DEBUG=false +RERUN=false +JAVA_OPTION="" +debug_port=8000 +TEST_SUITES=testSuites +fileName=testng-failed.xml + +function help_usage () +{ + echo + echo "$0 ( ) [-r/rerun -d/debug ]" + echo "nohup ./startTest.sh ui-ci-1707.0.5-SNAPSHOT-jar-with-dependencies.jar extendedSanity.xml -r false -d true &" + echo "by default rerun is true and remote debug is false." + echo + exit 2 +} + +function isBoolean () +{ + PARAM_NAME=$1 + VALUE=$2 + if [[ ${VALUE} != "true" ]] && [[ ${VALUE} != "false" ]]; then + echo "Valid parameter" ${PARAM_NAME} "values are: true/false" + help_usage + fi +} + +function prepareFailedXmlFile () +{ + echo "1="$1 "2="$2 "fileName="${fileName} + PATTERN=`grep -w "test name=" ${FULL_PATH}/${TEST_SUITES}/$2 | awk -F'"' '{print $2}'` + sed '/ ${FULL_PATH}/${TEST_SUITES}/${fileName} + sed -i 's/thread-count="[0-9]\+"/thread-count="1"/g' ${FULL_PATH}/${TEST_SUITES}/${fileName} +} + +#main +[ $# -lt 2 ] && help_usage + +JAR_FILE=$1 +SUITE_FILE=$2 + +while [ $# -ne 0 ]; do + case $1 in + -r|rerun) + RERUN=$2 + isBoolean $1 ${RERUN} + shift 1 + shift 1 + ;; + -d|debug) + REMOTE_DEBUG=$2 + isBoolean $1 ${REMOTE_DEBUG} + shift 1 + shift 1 + ;; + *) + shift 1 + ;; + esac +done + +CURRENT_DIR=`pwd` +BASEDIR=$(dirname $0) + +if [ ${BASEDIR:0:1} = "/" ] +then + FULL_PATH=$BASEDIR +else + FULL_PATH=$CURRENT_DIR/$BASEDIR +fi +LOGS_PROP_FILE=file:${FULL_PATH}/conf/log4j.properties +############################################# +TARGET_DIR=${FULL_PATH}/target +CONF_FILE=${FULL_PATH}/conf/attsdc.yaml + +DEBUG=true +MainClass=org.openecomp.sdc.ci.tests.run.StartTest + +TESTS_DIR=/opt/app/sdc/ci/resources/tests +COMPONENTS_DIR=/opt/app/sdc/ci/resources/components + + +TARGET_LOG_DIR="${TARGET_DIR}/" + +######ADD USERS################ + +BE_IP=`cat conf/attsdc.yaml | grep catalogBeHost| awk '{print $2}'` + +ADD_USERS_SCRIPT="addUsersFromList_new.sh" +USER_LIST="userList.txt" +chmod +x ${ADD_USERS_SCRIPT} +echo "add users..." +`./${ADD_USERS_SCRIPT} -ip ${BE_IP} -f ${USER_LIST}` + + + +if [ ${REMOTE_DEBUG} == "true" ]; then + echo "Debug mode, Listen on port $debug_port"; + JAVA_OPTION="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${debug_port}" ; +fi + +cmd="java -Xmx2048m -Xms1024m $JAVA_OPTION -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dfilepath=${FILES_TEST} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass} $SUITE_FILE &" + + +if [ $DEBUG == "true" ] +then + $cmd +else + $cmd >> /dev/null +fi + +if [ ${RERUN} == "true" ]; then + if [ -f ${TARGET_DIR}/${fileName} ]; then + echo "Prepare" ${TARGET_DIR}/${fileName} "file to rerun all failed tests ..."; + prepareFailedXmlFile ${TARGET_DIR}/${fileName} $SUITE_FILE; + SUITE_FILE=${fileName}; + cmd="java -Xmx2048m -Xms1024m $JAVA_OPTION -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dfilepath=${FILES_TEST} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass} $SUITE_FILE &" + $cmd; + fi +fi + +status=`echo $?` + +source ExtentReport/versions.info +now=$(date +'%Y-%m-%d_%H_%M') +REPORT_NAME=${now} +VERSION=${osVersion} + +if [[ $env == *"DEV20"* ]] +then + MYENV="Nightly" +else + MYENV="" +fi + +COPY_REPORT_SCRIPT="copyToStorage.sh" +chmod +x ${COPY_REPORT_SCRIPT} +echo "copy report to storage..." +sh ./${COPY_REPORT_SCRIPT} ${REPORT_NAME} ${VERSION} ${MYENV} + + +MAILING_SCRIPT_NAME="sendMail.sh" +chmod +x ${MAILING_SCRIPT_NAME} +echo "Sending report via mail..." +`./${MAILING_SCRIPT_NAME} ${REPORT_NAME} ${VERSION} ${MYENV}` + + +echo "##################################################" +echo "################# status is ${status} #################" +echo "##################################################" + +exit $status diff --git a/test-apis-ci/src/main/resources/ci/scripts/userList.txt b/test-apis-ci/src/main/resources/ci/scripts/userList.txt new file mode 100644 index 0000000000..a1326599dc --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/scripts/userList.txt @@ -0,0 +1 @@ +export USER_LIST=( "m99121 DESIGNER" "cs0008 DESIGNER" "kb0004 TESTER" "af0006 OPS" "ah0002 GOVERNOR" "m08740 DESIGNER" "m99124 TESTER" "m08743 TESTER" "m99123 OPS" "m08742 OPS" "m99125 GOVERNOR" "m08744 GOVERNOR" "m99122 ADMIN" "m08741 ADMIN" "m99126 PRODUCT_STRATEGIST" "m08745 PRODUCT_STRATEGIST" "m99127 PRODUCT_MANAGER" "m08746 PRODUCT_MANAGER" "md9897 DESIGNER" "m08748 DESIGNER" "m08749 TESTER" "be0695 DESIGNER" "er434w DESIGNER" "ya107f DESIGNER" "ds200p DESIGNER" "ak0333 ADMIN" "th0695 DESIGNER" "al714h DESIGNER" "ys9693 DESIGNER" "ss8214 DESIGNER" "bt750h DESIGNER" "rp955r DESIGNER" "ez6451 DESIGNER" "ia901h DESIGNER" "ah7840 DESIGNER" "ea394r DESIGNER" "ms656r DESIGNER" "ml636r DESIGNER" "it1721 DESIGNER" "sg473v DESIGNER" "sa997j DESIGNER" "az2497 DESIGNER" "ys189e DESIGNER" "ig642y DESIGNER" ) diff --git a/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml b/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml new file mode 100644 index 0000000000..e53da8da8a --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/testSuites/SearchExternalAPI.xml b/test-apis-ci/src/main/resources/ci/testSuites/SearchExternalAPI.xml new file mode 100644 index 0000000000..40c462a4cb --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/SearchExternalAPI.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/testSuites/artifacts.xml b/test-apis-ci/src/main/resources/ci/testSuites/artifacts.xml new file mode 100644 index 0000000000..24229b8586 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/artifacts.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/category.xml b/test-apis-ci/src/main/resources/ci/testSuites/category.xml new file mode 100644 index 0000000000..f2a0b3790c --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/category.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/ciFull.xml b/test-apis-ci/src/main/resources/ci/testSuites/ciFull.xml new file mode 100644 index 0000000000..26a85fd9c6 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/ciFull.xml @@ -0,0 +1,221 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml b/test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml new file mode 100644 index 0000000000..3505dad3c4 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/testSuites/general.xml b/test-apis-ci/src/main/resources/ci/testSuites/general.xml new file mode 100644 index 0000000000..bd7e6b6650 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/general.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/imports.xml b/test-apis-ci/src/main/resources/ci/testSuites/imports.xml new file mode 100644 index 0000000000..ae4a5bc1f8 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/imports.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/product.xml b/test-apis-ci/src/main/resources/ci/testSuites/product.xml new file mode 100644 index 0000000000..4ea495d0d7 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/product.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/productAPIs.xml b/test-apis-ci/src/main/resources/ci/testSuites/productAPIs.xml new file mode 100644 index 0000000000..61950e9de7 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/productAPIs.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/testSuites/property.xml b/test-apis-ci/src/main/resources/ci/testSuites/property.xml new file mode 100644 index 0000000000..f94f89737a --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/property.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/resource.xml b/test-apis-ci/src/main/resources/ci/testSuites/resource.xml new file mode 100644 index 0000000000..803fb01e70 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/resource.xml @@ -0,0 +1,360 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/sanity.xml b/test-apis-ci/src/main/resources/ci/testSuites/sanity.xml new file mode 100644 index 0000000000..f642170b34 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/sanity.xml @@ -0,0 +1,394 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/main/resources/ci/testSuites/service.xml b/test-apis-ci/src/main/resources/ci/testSuites/service.xml new file mode 100644 index 0000000000..18d5630c4e --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/service.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/testngLifeCycle.xml b/test-apis-ci/src/main/resources/ci/testSuites/testngLifeCycle.xml new file mode 100644 index 0000000000..54f1868470 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/testngLifeCycle.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/ci/testSuites/user.xml b/test-apis-ci/src/main/resources/ci/testSuites/user.xml new file mode 100644 index 0000000000..948993c144 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/testSuites/user.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/log4j.properties b/test-apis-ci/src/main/resources/log4j.properties new file mode 100644 index 0000000000..d313e92b55 --- /dev/null +++ b/test-apis-ci/src/main/resources/log4j.properties @@ -0,0 +1,34 @@ +# Define the root logger with appender file +log4j.rootLogger = INFO, FILE, stdout + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender +log4j.appender.FILE.File=${targetlog}logs/ci-log.out + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%10c] : %m%n + +# Set the maximum file size before rollover +log4j.appender.FILE.maxFileSize=5MB + +# Set the the backup index +log4j.appender.FILE.maxBackupIndex=10 + + +############################################################# + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n + +log4j.logger.org.apache.cassandra.service.StorageProxy=INFO +log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout + +log4j.logger.org.openecomp.sdc.ci.tests.utils=INFO, FILE, stdout +log4j.additivity.org.openecomp.sdc.ci.tests.utils=false + + diff --git a/test-apis-ci/src/main/resources/log4j.xml b/test-apis-ci/src/main/resources/log4j.xml new file mode 100644 index 0000000000..6db233a1da --- /dev/null +++ b/test-apis-ci/src/main/resources/log4j.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/src/main/resources/logback.xml b/test-apis-ci/src/main/resources/logback.xml new file mode 100644 index 0000000000..4723bc24cb --- /dev/null +++ b/test-apis-ci/src/main/resources/logback.xml @@ -0,0 +1,25 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n + + + + + logFile.log + true + + %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n + + + + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/ecomp-error-configuration.yaml b/test-apis-ci/src/test/resources/CI/ecomp-error-configuration.yaml new file mode 100644 index 0000000000..9d7cd74a2b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/ecomp-error-configuration.yaml @@ -0,0 +1,383 @@ +########################################### +# Note the conventions of the field values: +# type can be one of: CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM +# severity can be one of: WARN, ERROR, FATAL +# alarmSeverity can be one of: CRITICAL,MAJOR,MINOR,INFORMATIONAL,NONE +# code is a unique integer in range of 3003-9999 (3000-3002 are occupied for internal usage) +# The above enumeration values are out-of-the-box and can be changed in code. +# In case of config and code mismatch, the appropriate error will be printed to log +# +## Range of BE codes - 3010-7999 + +errors: + + BeRestApiGeneralError: { + type: SYSTEM_ERROR, + code: ASDC_4000, + severity: ERROR, + description: "Unexpected error during BE REST API execution", + alarmSeverity: CRITICAL + } + + BeHealthCheckError: { + type: SYSTEM_ERROR, + code: ASDC_3010, + severity: ERROR, + description: "Error during BE Health Check", + alarmSeverity: CRITICAL + } + + BeInitializationError: { + type: SYSTEM_ERROR, + code: ASDC_4019, + severity: ERROR, + description: "Catalog-BE was not initialized properly", + alarmSeverity: CRITICAL + } + + BeResourceMissingError: { + type: SYSTEM_ERROR, + code: ASDC_3011, + severity: ERROR, + description: "Mandatory resource %s cannot be found in repository", + alarmSeverity: MAJOR + } + + BeServiceMissingError: { + type: SYSTEM_ERROR, + code: ASDC_3012, + severity: ERROR, + description: "Mandatory service %s cannot be found in repository", + alarmSeverity: MAJOR + } + + BeFailedAddingResourceInstanceError: { + type: SYSTEM_ERROR, + code: ASDC_3013, + severity: ERROR, + description: "Failed to add resource instance of resource %s to service %s", + alarmSeverity: MAJOR + } + + BeIncorrectServiceError: { + type: SYSTEM_ERROR, + code: ASDC_3014, + severity: ERROR, + description: "Service %s is not valid", + alarmSeverity: MAJOR + } + + BeRepositoryDeleteError: { + type: SYSTEM_ERROR, + code: ASDC_3015, + severity: ERROR, + description: "Failed to delete object %s from repository", + alarmSeverity: CRITICAL + } + + BeRepositoryQueryError: { + type: SYSTEM_ERROR, + code: ASDC_3016, + severity: ERROR, + description: "Failed to fetch from repository %s", + alarmSeverity: MAJOR + } + + BeInvalidConfigurationError: { + type: CONFIG_ERROR, + code: ASDC_3017, + severity: FATAL, + description: "Configuration parameter %s is invalid. Value configured is %s", + alarmSeverity: MAJOR + } + + BeUebConnectionError: { + type: CONNECTION_PROBLEM, + code: ASDC_4001, + severity: ERROR, + description: "Connection problem towards U-EB server. Reason: %s", + alarmSeverity: MAJOR + } + + BeUebSystemError: { + type: SYSTEM_ERROR, + code: ASDC_3019, + severity: ERROR, + description: "Error occured during access to U-EB Server. Operation: %s", + alarmSeverity: MAJOR + } + + BeUebObjectNotFoundError: { + type: DATA_ERROR, + code: ASDC_4005, + severity: ERROR, + description: "Error occured during access to U-EB Server. Data not found: %s", + alarmSeverity: MAJOR + } + + BeDistributionEngineSystemError: { + type: SYSTEM_ERROR, + code: ASDC_3021, + severity: ERROR, + description: "Error occured in Distribution Engine. Failed operation: %s", + alarmSeverity: MAJOR + } + + BeUebAuthenticationError: { + type: AUTHENTICATION_PROBLEM, + code: ASDC_4003, + severity: ERROR, + description: "Authentication problem towards U-EB server. Reason: %s", + alarmSeverity: MAJOR + } + + BeUebUnkownHostError: { + type: CONNECTION_PROBLEM, + code: ASDC_4002, + severity: ERROR, + description: "Connection problem towards U-EB server. Cannot reach host %s", + alarmSeverity: MAJOR + } + + BeDistributionEngineInvalidArtifactType: { + type: DATA_ERROR, + code: ASDC_4006, + severity: WARN, + description: "The artifact type %s does not appear in the list of valid artifacts %s", + alarmSeverity: MAJOR + } + BeInvalidTypeError: { + type: DATA_ERROR, + code: ASDC_4008, + severity: WARN, + description: "The type %s of %s is invalid", + alarmSeverity: MAJOR + } + BeInvalidValueError: { + type: DATA_ERROR, + code: ASDC_3028, + severity: WARN, + description: "The value %s of %s from type %s is invalid", + alarmSeverity: MAJOR + } + + BeFailedDeletingResourceInstanceError: { + type: SYSTEM_ERROR, + code: ASDC_3029, + severity: ERROR, + description: "Failed to delete resource instance %s from service %s", + alarmSeverity: MAJOR + } + + BeMissingConfigurationError: { + type: CONFIG_ERROR, + code: ASDC_3030, + severity: FATAL, + description: "Configuration parameter %s is missing", + alarmSeverity: MAJOR + } + + BeConfigurationInvalidListSizeError: { + type: CONFIG_ERROR, + code: ASDC_3031, + severity: FATAL, + description: "Configuration parameter %s is invalid. At least %s values shall be configured", + alarmSeverity: MAJOR + } + + ErrorConfigFileFormat: { + type: CONFIG_ERROR, + code: ASDC_3032, + severity: ERROR, + description: "Error element not found in YAML name: %s", + alarmSeverity: MAJOR + } + + BeMissingArtifactInformationError: { + type: DATA_ERROR, + code: ASDC_4010, + severity: ERROR, + description: "Artifact uploaded has missing information. Missing %s", + alarmSeverity: MAJOR + } + + BeArtifactMissingError: { + type: DATA_ERROR, + code: ASDC_4011, + severity: ERROR, + description: "Artifact %s requested is not found", + alarmSeverity: MAJOR + } + + BeArtifactPayloadInvalid: { + type: DATA_ERROR, + code: ASDC_4012, + severity: ERROR, + description: "Payload of artifact uploaded is invalid (invalid MD5 or encryption)", + alarmSeverity: MAJOR + } + + BeUserMissingError: { + type: DATA_ERROR, + code: ASDC_4009, + severity: ERROR, + description: "User %s requested is not found", + alarmSeverity: MAJOR + } + + BeArtifactInformationInvalidError: { + type: DATA_ERROR, + code: ASDC_4013, + severity: ERROR, + description: "Input for artifact metadata is invalid", + alarmSeverity: MAJOR + } + BeFailedAddingCapabilityTypeError: { + type: DATA_ERROR, + code: ASDC_4015, + severity: ERROR, + description: "Failed adding capability type", + alarmSeverity: CRITICAL + } + + BeCapabilityTypeMissingError: { + type: DATA_ERROR, + code: ASDC_4016, + severity: ERROR, + description: "Capability Type %s not found", + alarmSeverity: CRITICAL + } + + BeInterfaceMissingError: { + type: DATA_ERROR, + code: ASDC_4020, + severity: ERROR, + description: "Interface %s required is missing", + alarmSeverity: MAJOR + } + + BeDaoSystemError: { + type: SYSTEM_ERROR, + code: ASDC_4014, + severity: ERROR, + description: "Operation towards database failed", + alarmSeverity: CRITICAL + } + + BeSystemError: { + type: SYSTEM_ERROR, + code: ASDC_4017, + severity: ERROR, + description: "Unexpected error during operation", + alarmSeverity: CRITICAL + } + + BeFailedLockObjectError: { + type: SYSTEM_ERROR, + code: ASDC_4007, + severity: WARN, + description: "Failed to lock object for update", + alarmSeverity: CRITICAL + } + + BeInvalidJsonInput: { + type: SYSTEM_ERROR, + code: ASDC_4018, + severity: ERROR, + description: "Failed to convert json input to object", + alarmSeverity: MAJOR + } + + BeDistributionMissingError: { + type: DATA_ERROR, + code: ASDC_4021, + severity: ERROR, + description: "Distribution %s required is missing", + alarmSeverity: MAJOR + } + + BeHealthCheckRecovery: { + type: RECOVERY, + code: ASDC_4022, + severity: INFO, + description: "BE Health Check Recovery", + alarmSeverity: INFORMATIONAL + } + BeFailedCreateNodeError: { + type: DATA_ERROR, + code: ASDC_6000, + severity: ERROR, + description: "Failed to create node %s on graph. status is %s", + alarmSeverity: MAJOR + } + BeFailedUpdateNodeError: { + type: DATA_ERROR, + code: ASDC_6001, + severity: ERROR, + description: "Failed to update node %s on graph. Status is %s", + alarmSeverity: MAJOR + } + + BeFailedDeleteNodeError: { + type: DATA_ERROR, + code: ASDC_6002, + severity: ERROR, + description: "Failed to delete node %s on graph. Status is %s", + alarmSeverity: MAJOR + } + + BeFailedRetrieveNodeError: { + type: DATA_ERROR, + code: ASDC_6003, + severity: ERROR, + description: "Failed to retrieve node %s from graph. Status is %s", + alarmSeverity: MAJOR + } + + BeExecuteRollbackError: { + type: DATA_ERROR, + code: ASDC_6004, + severity: ERROR, + description: "Going to execute rollback on graph.", + alarmSeverity: MAJOR + } + + BeFailedFindParentError: { + type: DATA_ERROR, + code: ASDC_6005, + severity: ERROR, + description: "Failed to find parent node %s on graph. Status is %s", + alarmSeverity: MAJOR + } + + BeFailedFindAllNodesError: { + type: DATA_ERROR, + code: ASDC_6006, + severity: ERROR, + description: "Failed to fetch all nodes with type %s of parent node %s . Status is %s", + alarmSeverity: MAJOR + } + + BeFailedFindAssociationError: { + type: DATA_ERROR, + code: ASDC_6007, + severity: ERROR, + description: "Cannot find node with type %s associated with node %s . Status is %s", + alarmSeverity: MAJOR + } + + BeFailedFindAssociationError: { + type: DATA_ERROR, + code: ASDC_6008, + severity: ERROR, + description: "Cannot find node with type %s associated with node %s . Status is %s", + alarmSeverity: MAJOR + } + BeComponentCleanerSystemError: { + type: SYSTEM_ERROR, + code: ASDC_6009, + severity: ERROR, + description: "Error occured in Component Cleaner Task. Failed operation: %s", + alarmSeverity: MAJOR + } + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/error-configuration.yaml b/test-apis-ci/src/test/resources/CI/error-configuration.yaml new file mode 100644 index 0000000000..ef7a885678 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/error-configuration.yaml @@ -0,0 +1,1778 @@ +# Errors +errors: + OK: { + code: 200, + message: "OK" + } + CREATED: { + code: 201, + message: "OK" + } + NO_CONTENT: { + code: 204, + message: "No Content" + } +#--------POL4050----------------------------- + NOT_ALLOWED: { + code: 405, + message: "Error: Method not allowed.", + messageId: "POL4050" + } +#--------POL5000----------------------------- + GENERAL_ERROR: { + code: 500, + message: "Error: Internal Server Error. Please try again later.", + messageId: "POL5000" + } +#---------POL5001------------------------------ + MISSING_X_ECOMP_INSTANCE_ID: { + code: 400 , + message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.", + messageId: "POL5001" + } +#---------POL5002------------------------------ + AUTH_REQUIRED: { + code: 401 , + message: "Error: Authentication is required to use the API.", + messageId: "POL5002" + } +#---------POL5003------------------------------ + AUTH_FAILED: { + code: 403 , + message: "Error: Not authorized to use the API.", + messageId: "POL5003" + } +#---------POL5004------------------------------ + MISSING_USER_ID: { + code: 400 , + message: "Error: Missing 'USER_ID' HTTP header.", + messageId: "POL5004" + } +#---------SVC4000----------------------------- + INVALID_CONTENT: { + code: 400, + message: "Error: Invalid content.", + messageId: "SVC4000" + } +#---------SVC4002----------------------------- + MISSING_INFORMATION: { + code: 403, + message: "Error: Missing information.", + messageId: "SVC4002" + } +#---------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 + INVALID_EMAIL_ADDRESS: { + code: 400, + message: "Error: Invalid email address '%1'.", + messageId: "SVC4004" + } +#---------SVC4005------------------------------ +# %1 - role + INVALID_ROLE: { + code: 400, + message: "Error: Invalid role '%1'.", + messageId: "SVC4005" + } +#---------SVC4006------------------------------ +# %1 - Users's USER_ID + USER_ALREADY_EXIST: { + code: 409, + message: "Error: User with '%1' ID already exists.", + messageId: "SVC4006" + } +#---------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 + INVALID_USER_ID: { + code: 400, + message: "Error: Invalid userId '%1'.", + messageId: "SVC4008" + } +#---------SVC4049------------------------------ +# %1 - service/resource + COMPONENT_MISSING_CONTACT: { + code: 400, + message: "Error: Invalid Content. Missing %1 contact.", + messageId: "SVC4049" + } +#---------SVC4050----------------------------- +# %1 - Service/Resource/Additional parameter +# %2 - service/resource/label name + COMPONENT_NAME_ALREADY_EXIST: { + code: 409, + message: "Error: %1 with name '%2' already exists.", + messageId: "SVC4050" + } +#---------SVC4051------------------------------ +# %1 - resource/service + COMPONENT_MISSING_CATEGORY: { + code: 400, + message: "Error: Invalid Content. Missing %1 category.", + messageId: "SVC4051" + } + +#---------SVC4052------------------------------ + COMPONENT_MISSING_TAGS: { + code: 400, + message: "Error: Invalid Content. At least one tag has to be specified.", + messageId: "SVC4052" + } + +#---------SVC4053------------------------------ +# %1 - service/resource + COMPONENT_MISSING_DESCRIPTION: { + code: 400, + message: "Error: Invalid Content. Missing %1 description.", + messageId: "SVC4053" + } +#---------SVC4054------------------------------ +# %1 - resource/service + COMPONENT_INVALID_CATEGORY: { + code: 400, + message: "Error: Invalid Content. Invalid %1 category.", + messageId: "SVC4054" + } +#---------SVC4055------------------------------ + MISSING_VENDOR_NAME: { + code: 400, + message: "Error: Invalid Content. Missing vendor name.", + messageId: "SVC4055" + } +#---------SVC4056------------------------------ + MISSING_VENDOR_RELEASE: { + code: 400, + message: "Error: Invalid Content. Missing vendor release.", + messageId: "SVC4056" + } + +#---------SVC4057------------------------------ + MISSING_DERIVED_FROM_TEMPLATE: { + code: 400, + message: "Error: Invalid Content. Missing derived from template specification.", + messageId: "SVC4057" + } + +#---------SVC4058------------------------------ +# %1 - service/resource + COMPONENT_MISSING_ICON: { + code: 400, + message: "Error: Invalid Content. Missing %1 icon.", + messageId: "SVC4058" + } +#---------SVC4059------------------------------ +# %1 - service/resource + COMPONENT_INVALID_ICON: { + code: 400, + message: "Error: Invalid Content. Invalid %1 icon.", + messageId: "SVC4059" + } +#---------SVC4060------------------------------ + PARENT_RESOURCE_NOT_FOUND: { + code: 400, + message: "Error: Invalid Content. Derived from resource template was not found.", + messageId: "SVC4060" + } +#---------SVC4061------------------------------ + MULTIPLE_PARENT_RESOURCE_FOUND: { + code: 400, + message: "Error: Invalid Content. Multiple derived from resource template is not allowed.", + messageId: "SVC4061" + } + +#---------SVC4062------------------------------ +# %1 - service/resource + MISSING_COMPONENT_NAME: { + code: 400, + message: "Error: Invalid Content. Missing %1 name.", + messageId: "SVC4062" + } +#---------SVC4063------------------------------ + #%1  -  resource/service name + RESOURCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' resource was not found.", + messageId: "SVC4063" + } + +#---------SVC4064------------------------------ +# %1 - Service/Resource/Property + COMPONENT_INVALID_DESCRIPTION: { + code: 400, + message: "Error: Invalid Content. %1 description contains non-english characters.", + messageId: "SVC4064" + } +#---------SVC4065------------------------------ +# %1 - Service/Resource/Property +# %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 + COMPONENT_TAGS_EXCEED_LIMIT: { + code: 400, + message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.", + messageId: "SVC4066" + } +#---------SVC4067------------------------------ +# %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 + VENDOR_RELEASE_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.", + messageId: "SVC4068" + } + +#---------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------------------------------ +# %1 - Service/Resource + INVALID_COMPONENT_NAME: { + code: 400, + message: 'Error: Invalid Content. %1 name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.', + messageId: "SVC4070" + } + +#---------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------------------------------ + 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------------------------------ +# %1 - Service/Resource +# %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------------------------------ +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_IN_CHECKOUT_STATE: { + code: 403, + message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).", + messageId: "SVC4080" + } +#---------SVC4081----------------------------- +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_IN_CERT_IN_PROGRESS_STATE: { + code: 403, + message: "Error: Requested '%1' %2 is locked for certification by %3 %4(%5).", + messageId: "SVC4081" + } + +#-----------SVC4082--------------------------- +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_SENT_FOR_CERTIFICATION: { + code: 403, + message: "Error: Requested '%1' %2 is sent for certification by %3 %4(%5).", + messageId: "SVC4082" + } +#-----------SVC4083--------------------------- + COMPONENT_VERSION_ALREADY_EXIST: { + code: 409, + message: "Error: Version of this %1 was already promoted.", + messageId: "SVC4083" + } +#-----------SVC4084--------------------------- +# %1 - resource/service/product name +# %2 - resource/service/product +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_ALREADY_CHECKED_IN: { + code: 409, + message: "Error: The current version of '%1' %2 was already checked-in by %3 %4(%5).", + messageId: "SVC4084" + } +#-----------SVC4085--------------------------- +# %1 - resource/service/product name +# %2 - resource/service/product +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_CHECKOUT_BY_ANOTHER_USER: { + code: 403, + message: "Error: %1 %2 has already been checked out by %3 %4(%5).", + messageId: "SVC4085" + } +#-----------SVC4086--------------------------- +# %1  - resource/service name +# %2  - resource/service + COMPONENT_IN_USE: { + code: 403, + message: "Error: Requested '%1' %2 is in use by another user.", + messageId: "SVC4086" + } +#-----------SVC4087--------------------------- +# %1 - component name +# %2 - resource/service/product + COMPONENT_HAS_NEWER_VERSION: { + code: 409, + message: "Error: Checking out of the requested version of the '%1' %2 is not allowed as a newer version exists.", + messageId: "SVC4087" + } +#-----------SVC4088--------------------------- +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_ALREADY_CERTIFIED: { + code: 403, + message: "Error: Requested %1 %2 has already been certified by %3 %4(%5).", + messageId: "SVC4088" + } +#-----------SVC4089--------------------------- +# %1 - resource/service name +# %2 - resource/service + COMPONENT_NOT_READY_FOR_CERTIFICATION: { + code: 403, + message: "Error: Requested '%1' %2 is not ready for certification.", + messageId: "SVC4089" + } +#-----------SVC4100--------------------------- +#%1 - property name + PROPERTY_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' property was not found.", + messageId: "SVC4100" + } +#-----------SVC4101--------------------------- +#%1 - property name + PROPERTY_ALREADY_EXIST: { + code: 409, + message: "Error: Property with '%1' name already exists.", + messageId: "SVC4101" + } + +#-----------SVC4102--------------------------- +# %1 - capability type name + CAPABILITY_TYPE_ALREADY_EXIST: { + code: 409, + message: "Error: Capability Type with name '%1' already exists.", + messageId: "SVC4102" + } +#-----------SVC4114--------------------------- + AUTH_FAILED_INVALIDE_HEADER: { + code: 400, + message: "Error: Invalid Authorization header.", + messageId: "SVC4114" + } +#-----------SVC4115--------------------------- +# %1 - capability type name + MISSING_CAPABILITY_TYPE: { + code: 400, + message: "Error: Invalid Content. Missing Capability Type '%1'.", + messageId: "SVC4115" + } + RESOURCE_INSTANCE_BAD_REQUEST: { + code: 400, + message: "Error: Invalid Content.", + messageId: "SVC4116" + } +#-----------SVC4117--------------------------- +# %1 - resource instance name +# %2 - resource instance name +# %3 - requirement name + RESOURCE_INSTANCE_MATCH_NOT_FOUND: { + code: 404, + message: "Error: Match not found between resource instance '%1' and resource instance '%2' for requirement '%3'.", + messageId: "SVC4117" + } +#-----------SVC4118--------------------------- +# %1 - resource instance name +# %2 - resource instance name +# %3 - requirement name + RESOURCE_INSTANCE_ALREADY_EXIST: { + code: 409, + message: "Error: Resource instances '%1' and '%2' are already associated with requirement '%3'.", + messageId: "SVC4118" + } +#-----------SVC4119--------------------------- +# %1 - resource instance name +# %2 - resource instance name +# %3 - requirement name + RESOURCE_INSTANCE_RELATION_NOT_FOUND: { + code: 404, + message: "Error: No relation found between resource instances '%1' and '%2' for requirement '%3'.", + messageId: "SVC4119" + } +#-----------SVC4120--------------------------- +# %1 - User's USER_ID + USER_INACTIVE: { + code: 404, + message: "Error: User %1 was not found.", + messageId: "SVC4120" + } +#-----------SVC4121--------------------------- +# %1 - User's USER_ID + USER_HAS_ACTIVE_ELEMENTS: { + code: 403, + message: "Error: User with %1 ID can not be deleted since it has active elements(resources/services/artifacts).", + messageId: "SVC4121" + } +#-----------SVC4122--------------------------- +# %1 - artifact type + ARTIFACT_TYPE_NOT_SUPPORTED: { + code: 400, + message: "Error: Invalid artifact type '%1'.", + messageId: "SVC4122" + } +#-----------SVC4123--------------------------- + ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Artifact logical name cannot be changed.", + messageId: "SVC4123" + } +#-----------SVC4124--------------------------- + MISSING_ARTIFACT_TYPE: { + code: 400, + message: "Error: Missing artifact type.", + messageId: "SVC4124" + } +#-----------SVC4125--------------------------- +# %1-artifact name + ARTIFACT_EXIST: { + code: 400, + message: "Error: Artifact '%1' already exists.", + messageId: "SVC4125" + } +#---------SVC4126------------------------------ +# %1 - resource/service/product/... +# %2 - field (tag, vendor name...) + INVALID_FIELD_FORMAT: { + code: 400, + message: "Error: Invalid %1 %2 format.", + messageId: "SVC4126" + } +#-----------SVC4127--------------------------- + ARTIFACT_INVALID_MD5: { + code: 400, + message: "Error: Invalid artifact checksum.", + messageId: "SVC4127" + } +#-----------SVC4128--------------------------- + MISSING_ARTIFACT_NAME: { + code: 400, + message: "Error: Invalid content. Missing artifact name.", + messageId: "SVC4128" + } +#-----------SVC4129--------------------------- + MISSING_PROJECT_CODE: { + code: 400, + message: "Error: Invalid Content. Missing PROJECT_CODE number.", + messageId: "SVC4129" + } +#-----------SVC4130--------------------------- + INVALID_PROJECT_CODE: { + code: 400, + message: "Error: Invalid Content. PROJECT_CODE must be from 3 up to 50 characters.", + messageId: "SVC4130" + } +#-----------SVC4131--------------------------- +# %1-resource/service +# %2-srtifact/artifacts +# %3-semicolomn separated list of artifact + COMPONENT_MISSING_MANDATORY_ARTIFACTS: { + code: 403, + message: "Error: Missing mandatory informational %1 %2: [%3].", + messageId: "SVC4131" + } +#-----------SVC4132--------------------------- +# %1 - lifecycle type name + LIFECYCLE_TYPE_ALREADY_EXIST: { + code: 409, + message: "Error: Lifecycle Type with name '%1' already exists.", + messageId: "SVC4132" + } +#-----------SVC4133--------------------------- +# %1 - service version +# %2 - service name + SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION: { + code: 403, + message: "Error: Version %1 of '%2' service is not available for distribution.", + messageId: "SVC4133" + } +#-----------SVC4134--------------------------- + MISSING_LIFECYCLE_TYPE: { + code: 400, + message: "Error: Invalid Content. Missing interface life-cycle type.", + messageId: "SVC4134" + } +#---------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 + DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: { + code: 500, + message: "Error: Requested distribution environment '%1' is not available.", + messageId: "SVC4136" + } +#---------SVC4137------------------------------ +# %1 - distribution environment name + DISTRIBUTION_ENVIRONMENT_NOT_FOUND: { + code: 400, + message: "Error: Requested distribution environment '%1' was not found.", + messageId: "SVC4137" + } +#---------SVC4138------------------------------ + DISTRIBUTION_ENVIRONMENT_INVALID: { + code: 400, + message: "Error: Invalid distribution environment.", + messageId: "SVC4138" + } +#---------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------------------------------ +# %1 - Service/Resource +# %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------------------------------ + RESTRICTED_ACCESS: { + code: 403, + message: "Error: Restricted access.", + messageId: "SVC4300" + } +#---------SVC4301------------------------------ + RESTRICTED_OPERATION: { + code: 409, + message: "Error: Restricted operation.", + messageId: "SVC4301" + } +#---------SVC4500------------------------------ + MISSING_BODY: { + code: 400 , + message: "Error: Missing request body.", + messageId: "SVC4500" + } +#---------SVC4501------------------------------ + MISSING_PUBLIC_KEY: { + code: 400 , + message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." , + messageId: "SVC4501" + } +#---------SVC4502------------------------------ + DISTRIBUTION_ENV_DOES_NOT_EXIST: { + code: 400 , + message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." , + messageId: "SVC4502" + } +#-----------SVC4503--------------------------- +# %1 - service name + SERVICE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' service was not found.", + messageId: "SVC4503" + } + +#---------SVC4504------------------------------ +# %1 - Service/Resource +# %2 - service/resource version + COMPONENT_VERSION_NOT_FOUND: { + code: 404, + message: "Error: %1 version %2 was not found.", + messageId: "SVC4504" + } +#-----------SVC4505--------------------------- + #%1-artifact name + + ARTIFACT_NOT_FOUND: { + code: 404, + message: "Error: Artifact '%1' was not found.", + messageId: "SVC4505" + } +#---------SVC4506------------------------------ + MISSING_ENV_NAME: { + code: 400 , + message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.", + messageId: "SVC4506" + } +#---------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------------------------------ + SERVICE_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Service name cannot be changed once the service is certified.", + messageId: "SVC4508" + } + +#---------SVC4509------------------------------ + SERVICE_ICON_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Icon cannot be changed once the service is certified.", + messageId: "SVC4509" + } +#---------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------------------------------ + DISTRIBUTION_REQUESTED_NOT_FOUND: { + code: 404, + message: "Error: Requested distribution was not found.", + messageId: "SVC4511" + } +#---------SVC4512------------------------------ +# %1 - Distribution ID + DISTRIBUTION_REQUESTED_FAILED: { + code: 403, + message: "Error: Requested distribution '%1' failed.", + messageId: "SVC4512" + } +#---------SVC4513------------------------------ + RESOURCE_CATEGORY_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Resource category cannot be changed once the resource is certified.", + messageId: "SVC4513" + } +#---------SVC4514------------------------------ + RESOURCE_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Resource name cannot be changed once the resource is certified.", + messageId: "SVC4514" + } +#---------SVC4515------------------------------ + RESOURCE_ICON_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Icon cannot be changed once the resource is certified.", + messageId: "SVC4515" + } +#---------SVC4516------------------------------ + RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Vendor name cannot be changed once the resource is certified.", + messageId: "SVC4516" + } +#---------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 + COMPONENT_SINGLE_TAG_EXCEED_LIMIT: { + code: 400, + message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.", + messageId: "SVC4518" + } +#---------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 + ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: { + code: 409, + message: "Error: Maximal number of additional %1 parameters was reached.", + messageId: "SVC4520" + } +#---------SVC4521------------------------------ + ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: { + code: 400, + message: "Error: Invalid Content. The Additional information label and value cannot be empty.", + messageId: "SVC4521" + } +#---------SVC4522------------------------------ +# %1 - label/value +# %2 - Maximal length of %1 + ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. Additional information %1 exceeds limit of %2 characters.", + messageId: "SVC4522" + } +#---------SVC4523------------------------------ + ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS: { + code: 400, + message: 'Error: Invalid Content. Additional information label is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.', + messageId: "SVC4523" + } +#---------SVC4524------------------------------ + ADDITIONAL_INFORMATION_NOT_FOUND: { + code: 409, + message: "Error: Requested additional information was not found.", + messageId: "SVC4524" + } +#---------SVC4525------------------------------ + ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: { + code: 400, + message: 'Error: Invalid Content. Additional information contains non-english characters.', + messageId: "SVC4525" + } +#---------SVC4526------------------------------ + RESOURCE_INSTANCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' resource instance was not found.", + messageId: "SVC4526" + } +#---------SVC4527------------------------------ + ASDC_VERSION_NOT_FOUND: { + code: 500, + message: 'Error: ASDC version cannot be displayed.', + messageId: "SVC4527" + } +#---------SVC4528------------------------------ +# %1-artifact url/artifact label/artifact description/VNF Service Indicator + MISSING_DATA: { + code: 400, + message: "Error: Invalid content. Missing %1.", + messageId: "SVC4528" + } +#---------SVC4529------------------------------ +# %1-artifact url/artifact label/artifact description/artifact name +# %2 - Maximal length of %1 + EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. %1 exceeds limit of %2 characters.", + messageId: "SVC4529" + } +#---------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------------------------------ + SERVICE_IS_VNF_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: VNF Indicator cannot be updated for certified service.", + messageId: "SVC4531" + } + #---------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" + WRONG_ARTIFACT_FILE_EXTENSION: { + code: 400, + message: "Error: Invalid file extension for %1 artifact type.", + messageId: "SVC4533" + } + +#---------SVC4534------------------------------ +# %1 - "HEAT"/"HEAT_ENV" + INVALID_YAML: { + code: 400, + message: "Error: Uploaded YAML file for %1 artifact is invalid.", + messageId: "SVC4534" + } + +#---------SVC4535------------------------------ +# %1 - "HEAT" + INVALID_DEPLOYMENT_ARTIFACT_HEAT: { + code: 400, + message: "Error: Invalid %1 artifact.", + messageId: "SVC4535" + } +#---------SVC4536------------------------------ +# %1 - "Resource"/"Service" +# %2 - resource/service name +# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG" +# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG + DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: { + code: 400, + message: "Error: %1 '%2' already has a deployment artifact of %3 type .Please delete or update an existing %4 artifact.", + messageId: "SVC4536" + } + +#---------SVC4537------------------------------ + MISSING_HEAT: { + code: 400, + message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.", + messageId: "SVC4537" + } +#---------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------------------------------ + INVALID_RESOURCE_PAYLOAD: { + code: 400, + message: "Error: Invalid resource payload.", + messageId: "SVC4539" + } +#---------SVC4540------------------------------ + INVALID_TOSCA_FILE_EXTENSION: { + code: 400, + message: "Error: Invalid file extension for TOSCA template.", + messageId: "SVC4540" + } +#---------SVC4541------------------------------ + INVALID_YAML_FILE: { + code: 400, + message: "Error: Invalid YAML file.", + messageId: "SVC4541" + } +#---------SVC4542------------------------------ + INVALID_TOSCA_TEMPLATE: { + code: 400, + message: "Error: Invalid TOSCA template.", + messageId: "SVC4542" + } +#---------SVC4543------------------------------ + NOT_RESOURCE_TOSCA_TEMPLATE: { + code: 400, + message: "Error: Imported Service TOSCA template.", + messageId: "SVC4543" + } +#---------SVC4544------------------------------ + NOT_SINGLE_RESOURCE: { + code: 400, + message: "Error: Imported TOSCA template should contain one resource definition.", + messageId: "SVC4544" + } +#---------SVC4545------------------------------ + INVALID_RESOURCE_NAMESPACE: { + code: 400, + message: "Error: Invalid resource namespace.", + messageId: "SVC4545" + } +#---------SVC4546------------------------------ + RESOURCE_ALREADY_EXISTS: { + code: 400, + message: "Error: Imported resource already exists in ASDC Catalog.", + messageId: "SVC4546" + } +#---------SVC4549------------------------------ + INVALID_RESOURCE_CHECKSUM: { + code: 400, + message: "Error: Invalid resource checksum.", + messageId: "SVC4549" + } +#---------SVC4550------------------------------ + #%1  -  Consumer salt + INVALID_LENGTH: { + code: 400, + message: "Error: Invalid %1 length.", + messageId: "SVC4550" + } + #---------SVC4551------------------------------ + #%1  -  ECOMP User name + ECOMP_USER_NOT_FOUND: { + code: 404, + message: "Error: ECOMP User '%1' was not found.", + messageId: "SVC4551" + } +#---------SVC4552------------------------------ + CONSUMER_ALREADY_EXISTS: { + code: 409, + message: "Error: ECOMP User already exists.", + messageId: "SVC4552" + } +#---------SVC4553----------------------------- + #%1  -  Consumer name / Consumer password/ Consumer salt + INVALID_CONTENT_PARAM: { + code: 400, + message: "Error: %1 is invalid.", + messageId: "SVC4553" + } + #---------SVC4554------------------------------ +# %1 - "Resource"/"Service" + COMPONENT_ARTIFACT_NOT_FOUND: { + code: 404, + message: "Error: Requested artifact doesn't belong to specified %1.", + messageId: "SVC4554" + } +#---------SVC4554------------------------------ +# %1 - "Service name" + SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND: { + code: 403, + message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.", + messageId: "SVC4554" + } +#---------SVC4555------------------------------ +#%1 - "Resource"/"Service"/"Product" +#%2 - "category" + COMPONENT_ELEMENT_INVALID_NAME_LENGTH: { + code: 400, + message: "Error: Invalid %1 %2 name length.", + messageId: "SVC4555" + } +#---------SVC4556------------------------------ +#%1 - "Resource"/"Service"/"Product" +#%2 - "category" + COMPONENT_ELEMENT_INVALID_NAME_FORMAT: { + code: 400, + message: "Error: Invalid %1 %2 name format.", + messageId: "SVC4556" + } +#---------SVC4557------------------------------ +#%1 - "Resource"/"Service"/"Product" +#%2 - "category name" + COMPONENT_CATEGORY_ALREADY_EXISTS: { + code: 409, + message: "Error: %1 category name '%2' already exists.", + messageId: "SVC4557" + } +#---------SVC4558------------------------------ +# %1 - "service"/"VF" +# %2 - "Resource name" + VALIDATED_RESOURCE_NOT_FOUND: { + code: 403, + message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource.", + messageId: "SVC4558" + } +#---------SVC4559------------------------------ +# %1 - "service"/"VF" +# %2 - "Resource name" + FOUND_ALREADY_VALIDATED_RESOURCE: { + code: 403, + message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use already available validated resource version.", + messageId: "SVC4559" + } +#---------SVC4560------------------------------ +# %1 - "service"/"VF" +# %2 - "Resource name" + FOUND_LIST_VALIDATED_RESOURCES: { + 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" +# %3 - "category name" + COMPONENT_CATEGORY_NOT_FOUND: { + code: 404, + message: "Error: Requested %1 %2 '%3' was not found.", + messageId: "SVC4561" + } +#---------SVC4562------------------------------ +# %1 - "Resource"/"Product" +# %2 - "sub-category name" +# %3 - "category name" + COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY: { + code: 409, + message: "Error: %1 sub-category '%2' already exists under '%3' category.", + messageId: "SVC4562" + } +#---------SVC4563------------------------------ +# %1 - "Product" +# %2 - "grouping name" +# %3 - "sub-category name" + COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY: { + code: 409, + message: "Error: %1 grouping '%2' already exists under '%3' sub-category.", + messageId: "SVC4563" + } +#---------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") +# %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") + INVALID_HEAT_PARAMETER_TYPE: { + code: 400, + message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.", + messageId: "SVC4566" + } +#---------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" +# %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" +# %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------------------------------ + UPDATE_USER_ADMIN_CONFLICT: { + code: 409, + message: "Error: An administrator is not allowed to change his/her role.", + messageId: "SVC4570" + } +#---------SVC4571------------------------------ + SERVICE_CANNOT_CONTAIN_SUBCATEGORY: { + code: 400, + message: "Error: Sub category cannot be defined for service", + messageId: "SVC4571" + } +#---------SVC4572------------------------------ +# %1 - "Resource"/"Service" + COMPONENT_TOO_MUCH_CATEGORIES: { + code: 400, + message: "Error: %1 must have only 1 category", + messageId: "SVC4572" + } +#---------SVC4574------------------------------ + RESOURCE_TOO_MUCH_SUBCATEGORIES: { + code: 400, + message: "Error: Resource must have only 1 sub category", + messageId: "SVC4574" + } +#---------SVC4575------------------------------ + COMPONENT_MISSING_SUBCATEGORY: { + code: 400, + message: "Error: Missing sub category", + messageId: "SVC4575" + } + #---------SVC4576------------------------------ +# %1 - "component type" + UNSUPPORTED_ERROR: { + code: 400, + message: "Error : Requested component type %1 is unsupported.", + messageId: "SVC4576" + } + #---------SVC4577------------------------------ +# %1 - "resource type" + RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: { + code: 409, + message: "Error : Resource of type %1 cannot contain resource instances.", + messageId: "SVC4577" + } +#---------SVC4578------------------------------ +# %1 - "Resource"/"Service" +# %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------------------------------ +# %1 - "Category"/"Sub-Category"/"Group" +# %2 - category/sub-category/grouping name. + INVALID_GROUP_ASSOCIATION: { + code: 400, + message: "Error: Invalid group association. %1 '%2' was not found.", + messageId: "SVC4579" + } +#---------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 + INVALID_PRODUCT_CONTACT: { + code: 400, + message: "Error: Invalid content. User '%1' cannot be set as Product Contact.", + messageId: "SVC4581" + } +#---------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" + COMPONENT_PARAMETER_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: %1 cannot be changed once the %2 is certified.", + messageId: "SVC4583" + } +#---------SVC4584------------------------------ +# %1 - service/VF name +# %2 - "service" /"VF" +# %3 - resource instance origin type +# %4 - resource instance name +# %5 - requirement/capability +# %6 - requirement/capability name +# %7 - "fulfilled" (for req)/"consumed (for cap)" + REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION: { + code: 403, + message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.", + messageId: "SVC4584" + } +#---------SVC4585------------------------------ + INVALID_OCCURRENCES: { + code: 400, + message: "Error: Invalid occurrences format.", + messageId: "SVC4585" + } +#---------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 + DATA_TYPE_ALREADY_EXIST: { + code: 409, + message: 'Error: Data type %1 already exists.', + messageId: "SVC4587" + } +#---------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 + 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 +# %2 - Property name + INVALID_PROPERTY_TYPE: { + code: 400, + message: "Error: Invalid Property type %1 in property %2.", + messageId: "SVC4590" + } +#---------SVC4591------------------------------ +# %1 - Property inner type +# %2 - Property name + INVALID_PROPERTY_INNER_TYPE: { + code: 400, + message: "Error: Invalid property inner type %1, in property %2", + messageId: "SVC4591" + } +#---------SVC4592------------------------------ +# %1 - component instance name +# %2 - "resource instance"/"service instance" + COMPONENT_INSTANCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' %2 was not found.", + messageId: "SVC4592" + } +#---------SVC4593------------------------------ +# %1 - component instance name +# %2 - "resource instance"/"service instance" +# %3 - "resource/"service"/"product" +# %4 - container name + COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested '%1' %2 was not found on the %3 '%4'.", + messageId: "SVC4593" + } +#---------SVC4594------------------------------ +#%1 - requirement / capability +#%2 - requirement name + IMPORT_DUPLICATE_REQ_CAP_NAME: { + code: 400, + message: "Error: Imported TOSCA template contains more than one %1 named '%2'.", + messageId: "SVC4594" + } +#---------SVC4595------------------------------ +#%1 - requirement / capability +#%2 - requirement name +#%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------------------------------ +# %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------------------------------ +# %1 - Data type name +# %2 - Property names + DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: { + code: 400, + message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.", + messageId: "SVC4597" + } +#---------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------------------------------ +# %1 - Data type name +# %2 - Property names + DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: { + code: 400, + message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.", + messageId: "SVC4599" + } +#---------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------------------------------ + NOT_TOPOLOGY_TOSCA_TEMPLATE: { + code: 400, + message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.", + messageId: "SVC4601" + } +#---------SVC4602-------------------------------- +# %1 - yaml file name +# %2 - node_template label +# %3 - node_template type + INVALID_NODE_TEMPLATE: { + code: 400, + message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL", + messageId: "SVC4602" + } +#---------SVC4603------------------------------ +# %1 - component type +# %2 - component name +# %3 - state + ILLEGAL_COMPONENT_STATE: { + code: 403, + message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.", + messageId: "SVC4603" + } +#---------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------------------------------ +# %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------------------------------ +# %1 - property name +# %2 - property type +# %3 - property innerType +# %4 - default value is + INVALID_COMPLEX_DEFAULT_VALUE: { + code: 400, + 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------------------------------ +# %1 - csar file name + CSAR_NOT_FOUND: { + code: 400, + message: "Error: TOSCA CSAR '%1' is not found.", + messageId: "SVC4607" + } +#---------SVC4608------------------------------ +# %1 - artifact name +# %2 - component type +# %3 - actual component type + MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE: { + code: 400, + message: "Error: Artifact %1 is only compatible with component of type %2, but component type is %3.", + messageId: "SVC4608" + } + +#---------SVC4609------------------------------ +# %1 - "INVALID_JSON" + INVALID_JSON: { + code: 400, + message: "Error: Uploaded JSON file for %1 artifact is invalid.", + messageId: "SVC4609" + } +#---------SVC4610------------------------------ +# %1 - csar file name +# %2 - missing file name + YAML_NOT_FOUND_IN_CSAR: { + code: 400, + message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.", + messageId: "SVC4610" + } +#---------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 + GROUP_TYPE_ALREADY_EXIST: { + code: 409, + message: 'Error: Group type %1 already exists.', + messageId: "SVC4612" + } +#---------SVC4613------------------------------ +# %1 - group name +# %2 - VF name(component name) +# %3 - actual component type [VF] + GROUP_ALREADY_EXIST: { + code: 409, + message: "Error: Group with name '%1' already exists in %2 %3.", + messageId: "SVC4613" + } +#---------SVC4614------------------------------ +# %1 - group type + GROUP_TYPE_IS_INVALID: { + code: 400, + message: "Error: Invalid content. Group type %1 does not exist", + messageId: "SVC4614" + } +#---------SVC4615------------------------------ +# %1 - group name + GROUP_MISSING_GROUP_TYPE: { + code: 400, + message: "Error: Invalid Content. Missing Group Type for group '%1'", + messageId: "SVC4615" + } +#---------SVC4616------------------------------ +# %1 - member name +# %2 - group name +# %3 - VF name +# %4 - component type [VF ] + GROUP_INVALID_COMPONENT_INSTANCE: { + 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 +# %3 - group type + GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE: { + code: 400, + message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.", + messageId: "SVC4617" + } +#---------SVC4618------------------------------ +# %1 - missing file name +# %2 - csar file name + ARTIFACT_NOT_FOUND_IN_CSAR: { + code: 400, + message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided", + messageId: "SVC4618" + } +#---------SVC4619------------------------------ +# %1 - artifact name +# %2 - artifact type +# %3 - existing artifact type + ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR: { + code: 400, + message: "Error: artifact %1 in type %2 already exists in type %3.", + messageId: "SVC4619" + } +#---------SVC4620------------------------------ + FAILED_RETRIVE_ARTIFACTS_TYPES: { + code: 400, + message: "Error: Failed to retrieve list of suported artifact types.", + messageId: "SVC4620" + } +#---------SVC4621------------------------------ +# %1 - artifact name +# %2 - master + ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: { + code: 400, + message: "Error: artifact %1 already exists in master %2 .", + messageId: "SVC4621" + } +#---------SVC4622------------------------------ +# %1 - artifact name +# %2 - artifact type +# %3 - master name +# %4 - master type + ARTIFACT_NOT_VALID_IN_MASTER: { + code: 400, + message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.", + messageId: "SVC4622" + } +#---------SVC4623------------------------------ +# %1 - artifact name +# %2 - artifact type +# %3 - env name +# %4 - existing env + ARTIFACT_NOT_VALID_ENV: { + code: 400, + message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4", + messageId: "SVC4623" + } +#---------SVC4624------------------------------ +# %1 - groups names +# %2 - VF name +# %3 - component type [VF ] + GROUP_IS_MISSING: { + code: 400, + message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.", + messageId: "SVC4624" + } +#---------SVC4625------------------------------ +# %1 - groups name + GROUP_ARTIFACT_ALREADY_ASSOCIATED: { + code: 400, + message: "Error: Invalid Content. Artifact already associated to group '%1'.", + messageId: "SVC4625" + } +#---------SVC4626------------------------------ +# %1 - groups name + GROUP_ARTIFACT_ALREADY_DISSOCIATED: { + code: 400, + message: "Error: Invalid Content. Artifact already dissociated from group '%1'.", + messageId: "SVC4626" + } +#---------SVC4627------------------------------ +# %1 - property name +# %2 - group name +# %3 - group type name + GROUP_PROPERTY_NOT_FOUND: { + code: 400, + message: "Error: property %1 listed in group %2 is not exist in group type %3.", + messageId: "SVC4627" + } +#---------SVC4628------------------------------ +# %1 - csarUUID +# %2 - VF name + VSP_ALREADY_EXISTS: { + code: 400, + message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.", + messageId: "SVC4628" + } +#---------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------------------------------ +# %1 - VF name +# %2 - new csarUUID +# %3 - old csarUUID + RESOURCE_LINKED_TO_DIFFERENT_VSP: { + code: 400, + 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 + POLICY_TYPE_ALREADY_EXIST: { + code: 409, + message: "Error: Policy type %1 already exists.", + messageId: "SVC4631" + } +#---------SVC4632------------------------------ +# %1 - target name +# %2 - policy type name + TARGETS_NON_VALID: { + code: 400, + message: "Error: target %1 listed in policy type %2 is not a group or resource.", + messageId: "SVC4632" + } +#---------SVC4633------------------------------ +# %1 - policy name + TARGETS_EMPTY: { + code: 400, + message: "Error: Invalid Content. Policy %1 target list was provided but does not have values", + messageId: "SVC4633" + } +#---------SVC4634------------------------------ + DATA_TYPE_CANNOT_BE_EMPTY: { + code: 500, + message: "Error: Data types are empty. Please import the data types.", + messageId: "SVC4634" + } +#---------SVC4635------------------------------ +# %1 - csar uuid + RESOURCE_FROM_CSAR_NOT_FOUND: { + code: 400, + message: "Error: resource from csar uuid %1 not found", + messageId: "SVC4635" + } +#---------SVC4636------------------------------ +# %1 - Data type name + DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: { + code: 400, + message: 'Error: Data type %1 cannot be upgraded. The new data type does not contain old properties or the type of one of the properties has been changed.', + messageId: "SVC4636" + } +#-----------SVC4637--------------------------- +#%1 - attribute name + ATTRIBUTE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' attribute was not found.", + messageId: "SVC4637" + } +#-----------SVC4638--------------------------- +#%1 - attribute name + ATTRIBUTE_ALREADY_EXIST: { + code: 409, + message: "Error: Attribute with '%1' name already exists.", + messageId: "SVC4638" + } +#-----------SVC4639--------------------------- +#%1 - property name + PROPERTY_NAME_ALREADY_EXISTS: { + code: 409, + message: "Error: Property with '%1' name and different type already exists.", + messageId: "SVC4639" + } +#-----------SVC4640--------------------------- +#%1 - property name + INVALID_PROPERTY: { + code: 409, + message: "Error: Invalid property received.", + messageId: "SVC4640" + } +#---------SVC4641----------------------------- +#%1 - invalid filter +#%2 - valid filters + INVALID_FILTER_KEY: { + code: 400, + message: "Error: The filter %1 is not applicable. Please use one of the following filters: %2", + messageId: "SVC4641" + } +#---------SVC4642----------------------------- +#%1 - asset type +#%2 - filter + NO_ASSETS_FOUND: { + code: 404, + message: "No %1 were found to match criteria %2", + messageId: "SVC4642" + } +#---------SVC4643------------------------------ +# %1 - "Resource"/"Product" +# %2 - "sub-category name" +# %3 - "category name" + COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY: { + code: 404, + message: "Error: %1 sub-category '%2' not found under category '%3'.", + messageId: "SVC4643" + } +#---------SVC4644------------------------------ +# %1 - Format + CORRUPTED_FORMAT: { + code: 400, + message: "Error: %1 format is corrupted.", + messageId: "SVC4644" + } +#---------SVC4645------------------------------ +# %1 - "groupType" + INVALID_VF_MODULE_TYPE: { + code: 400, + message: "Error: Invalid group type '%1' (should be VfModule).", + messageId: "SVC4645" + } +#---------SVC4646------------------------------ +# %1 - "groupName" + INVALID_VF_MODULE_NAME: { + code: 400, + message: "Error: Invalid Content. VF Module name '%1' contains invalid characters", + messageId: "SVC4646" + } + +#---------SVC4647------------------------------ +# %1 - "modifiedName" + INVALID_VF_MODULE_NAME_MODIFICATION: { + code: 400, + message: "Error: Invalid VF Module name modification, can not modify '%1'", + messageId: "SVC4647" + } +#---------SVC4648------------------------------ +# %1 - "inputId" +# %2 - "componentId" + INPUT_IS_NOT_CHILD_OF_COMPONENT: { + code: 400, + message: "Error: Input id: '%1' is not child of component id: '%2'", + messageId: "SVC4648" + } +#---------SVC4649------------------------------ +# %1 - "groupName" + GROUP_HAS_CYCLIC_DEPENDENCY: { + code: 400, + message: "Error: The group '%1' has cyclic dependency", + messageId: "SVC4649" + } +#---------SVC4650------------------------------ +# %1 - "Component Type" +# %2 - +# %3 - error description + AAI_ARTIFACT_GENERATION_FAILED: { + code: 500, + message: "Error: %1 %2 automatic generation of artifacts failed. Description: %3", + messageId: "SVC4650" + } +#---------SVC4651------------------------------ + PARENT_RESOURCE_DOES_NOT_EXTEND: { + code: 400, + message: "Error: Once resource is certified, derived_from can be changed only to a sibling", + messageId: "SVC4651" + } +#---------SVC4652------------------------------ +# %1 - resource/service + COMPONENT_INVALID_SUBCATEGORY: { + code: 400, + message: "Error: Invalid Content. Invalid %1 sub category.", + messageId: "SVC4652" + } +#---------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 +# %2 - valid min limit value +# %3 - valid max limit value + INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: { + code: 400, + message: "Error: Value of %1 must be not higher than %2, and not lower than %3.", + messageId: "SVC4654" + } +#---------SVC4655------------------------------ +# %1 - group property name +# %2 - valid min limit value +# %3 - valid max limit value + INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: { + code: 400, + message: "Error: Value of %1 must be between %2 and %3.", + messageId: "SVC4655" + } +#---------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: { + code: 400, + message: "Error - Lifecycle state %1 is not valid for resource of type VFCMT", + messageId: "SVC4657" + } +#---------SVC4658------------------------------ +# %1 – asset type [service / resource ] +# %2 – main asset uuid +# %3 – not found asset type [service / resource] +# %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", + messageId: "SVC4658" + } +#---------SVC4659------------------------------ +# %1 – asset type [service / resource ] +# %2 – main asset uuid +# %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", + 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" + } diff --git a/test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.yml b/test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.yml new file mode 100644 index 0000000000..120f33d5f1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.yml @@ -0,0 +1,23 @@ +services: + Mobility: + name: "Mobility1" + icons: ['mobility'] + Network_L1_3: + name: "Network L1-31" + icons: ['network_l_1-3'] +resources: + NetworkLayer23: + name: "Network Layer 2-31" + subcategories: + Router: + name: "Router" + icons: ['router'] + Gateway: + name: "Gateway" + icons: ['gateway'] + WAN_Connectors: + name: "WAN Connectors" + icons: ['connector'] + LAN_Connectors: + name: "LAN Connectors" + icons: ['connector'] diff --git a/test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.zip b/test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.zip new file mode 100644 index 0000000000..68b7aa9114 Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/importTypesTest/categoryTypesTest.zip differ diff --git a/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml new file mode 100644 index 0000000000..484ed4dff6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml @@ -0,0 +1,13 @@ +org.openecomp.groups.MyHeatStack1: + derived_from: tosca.groups.Root + description: Grouped all heat resources which are in the same heat stack + properties: + heat_files: + type: list + description: Heat files which associate to this group/heat stack + required: true + status: SUPPORTED + entry_schema: + type: string + url_credential: + type: tosca.datatypes.Credential \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip new file mode 100644 index 0000000000..2619853f4b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip differ diff --git a/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml new file mode 100644 index 0000000000..94fbb0451e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml @@ -0,0 +1,14 @@ +org.openecomp.groups.MyHeatStack2: + derived_from: tosca.groups.Root + description: Grouped all heat resources which are in the same heat stack + members: [ tosca.nodes.Compute ] + properties: + heat_files: + type: list + description: Heat files which associate to this group/heat stack + required: true + status: SUPPORTED + entry_schema: + type: string + url_credential: + type: tosca.datatypes.Credential \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip new file mode 100644 index 0000000000..7f43af70eb Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip differ diff --git a/test-apis-ci/src/test/resources/CI/other/mapping.json b/test-apis-ci/src/test/resources/CI/other/mapping.json new file mode 100644 index 0000000000..3310d776b9 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/other/mapping.json @@ -0,0 +1,182 @@ +{ "order": 1, "template": "auditingevents-*", "settings": {}, "mappings": +{ +"distributiondownloadevent": + { "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "RESOURCE_URL": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CONSUMER_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }}, + "_all": { "enabled": true } }, + "auditinggetuebclusterevent": + { "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CONSUMER_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }}, + "_all": { "enabled": true } }, + "distributionstatusevent": + { "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "RESOURCE_URL": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TOPIC_NAME":{ "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CONSUMER_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }}, + "_all": { "enabled": true } }, +"distributionengineevent": + { "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TOPIC_NAME":{ "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ROLE": { "include_in_all": true, "type": "string" }, + "API_KEY": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "D_ENV": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CONSUMER_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }}, + "_all": { "enabled": true } }, + "useraccessevent": { + "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "USER": { "include_in_all": true, "type": "string" }}, + "_all": { "enabled": true }}, +"resourceadminevent": + { "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CURR_VERSION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CURR_STATE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "PREV_VERSION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "PREV_STATE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "RESOURCE_NAME": { "include_in_all": true, "type": "string" }, + "RESOURCE_TYPE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DPREV_STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DCURR_STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TOSCA_NODE_TYPE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "COMMENT": { "include_in_all": true, "type": "string" }, + "ARTIFACT_DATA": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "PREV_ARTIFACT_UUID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CURR_ARTIFACT_UUID": { "include_in_all": true, "index": "not_analyzed", "type": "string" } }, + "_all": { "enabled": true }} , +"useradminevent": + { "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "USER_AFTER": { "include_in_all": true, "type": "string" }, + "USER_BEFORE": { "include_in_all": true, "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }}, + "_all": { "enabled": true } }, +"distributionnotificationevent": + {"properties":{ + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CURR_STATE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CURR_VERSION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "RESOURCE_NAME": { "include_in_all": true, "type": "string" }, + "RESOURCE_TYPE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TOPIC_NAME":{ "include_in_all": true, "index": "not_analyzed", "type": "string" }}, + "_all": { "enabled": true } }, + "categoryevent": + { "properties":{ + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CATEGORY_NAME": { "include_in_all": true, "type": "string" }, + "SUB_CATEGORY_NAME": { "include_in_all": true, "type": "string" }, + "GROUPING_NAME": { "include_in_all": true, "type": "string" }, + "RESOURCE_TYPE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }}, + "_all": { "enabled": true } }, + "authevent": { + "properties": { + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }, + "DESC": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "URL": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "USER": { "include_in_all": true, "type": "string" }, + "AUTH_STATUS": { "include_in_all": true, "index": "not_analyzed","type": "string" } , + "REALM": { "include_in_all": true, "index": "not_analyzed","type": "string" }} , + "_all": { "enabled": true }}, + "consumerevent": + { "properties":{ + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "ECOMP_USER": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }}, + "_all": { "enabled": true } }, + "getuserslistevent": + { "properties":{ + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DETAILS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }}, + "_all": { "enabled": true } }, + "getcategoryhierarchyevent": + { "properties":{ + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DETAILS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }}, + "_all": { "enabled": true } }, + "distributiondeployevent": + { "properties": { + "ACTION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "CURR_VERSION": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "DESC": { "include_in_all": true, "type": "string" }, + "DID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "MODIFIER": { "include_in_all": true, "type": "string" }, + "REQUEST_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "RESOURCE_NAME": { "include_in_all": true, "type": "string" }, + "RESOURCE_TYPE": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "SERVICE_INSTANCE_ID": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "STATUS": { "include_in_all": true, "index": "not_analyzed", "type": "string" }, + "TIMESTAMP": { "include_in_all": true, "ignore_malformed": false, "format": "yyyy-MM-dd HH:mm:ss.SSS z", "precision_step": 4, "type": "date" }}, + "_all": { "enabled": true } }}, + "aliases": { "last_3_months": {}}} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml new file mode 100644 index 0000000000..0415385bd0 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml @@ -0,0 +1,32 @@ + + + + + Lionel Andres Messi + 1987-06-24T00:00:00-00:00 + + + Cristiano Ronaldo + 1985-02-05T00:00:00-00:00 + + + FC Barcelona + + Lionel Andres Messi + Champions League 2014-2015 + 10 + 43 + + + + Real Madrid + + Cristiano Ronaldo + Champions League 2014-2015 + 7 + 48 + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml new file mode 100644 index 0000000000..6835485ca1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml @@ -0,0 +1,787 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + vnf_id: + type: string + description: Unique ID for this VNF instance + default: This_is_ths_SCP_id + + flavor_scp_be_id: + type: string + description: flavor type + default: a1.Small + flavor_scp_fe_id: + type: string + description: flavor type + default: a1.Small + flavor_smp_id: + type: string + description: flavor type + default: a1.Small + flavor_db_id: + type: string + description: flavor type + default: a1.Small + image_scp_be_id: + type: string + description: Image use to boot a server + default: asc_base_image_be + image_scp_fe_id: + type: string + description: Image use to boot a server + default: asc_base_image_fe + image_smp_id: + type: string + description: Image use to boot a server + default: asc_base_image_smp + image_db_id: + type: string + description: Image use to boot a server + default: asc_base_image_db + + int_vscp_fe_cluster_net_id: + type: string + description: LAN2 FE Cluster/KA + int_vscp_fe_cluster_cidr: + type: string + description: Private Network2 Address (CIDR notation) + int_vscp_cluster_net_id: + type: string + description: LAN3 Cluster + int_vscp_cluster_cidr: + type: string + description: Private Network3 Address (CIDR notation) + int_vscp_db_network_net_id: + type: string + description: LAN4 DB + int_vscp_db_network_cidr: + type: string + description: Private Network4 Address (CIDR notation) + SIGNET_vrf_A1_direct_net_id: + type: string + description: Network name for SIGTRAN_A + SIGNET_vrf_B1_direct_net_id: + type: string + description: Network name for SIGTRAN_B + Cricket_OCS_protected_net_id: + type: string + description: Network name for CRICKET_OCS + OAM_direct_net_id: + type: string + description: Network name for OAM + be0_Cricket_OCS_protected_ips: + type: string + label: be0 port 5 OAM ip address + description: be0 port 5 OAM ip address + be1_Cricket_OCS_protected_ips: + type: string + label: be1 port 5 OAM ip address + description: be1 port 5 OAM ip address + be2_Cricket_OCS_protected_ips: + type: string + label: be2 port 5 OAM ip address + description: be2 port 5 OAM ip address + be3_Cricket_OCS_protected_ips: + type: string + label: be3 port 5 OAM ip address + description: be3 port 5 OAM ip address + be4_Cricket_OCS_protected_ips: + type: string + label: be4 port 5 OAM ip address + description: be4 port 5 OAM ip address + be0_OAM_direct_ips: + type: string + label: be0 port 7 OAM ip address + description: be0 port 7 OAM ip address + be1_OAM_direct_ips: + type: string + label: be1 port 7 OAM ip address + description: be1 port 7 OAM ip address + be2_OAM_direct_ips: + type: string + label: be2 port 7 OAM ip address + description: be2 port 7 OAM ip address + be3_OAM_direct_ips: + type: string + label: be3 port 7 OAM ip address + description: be3 port 7 OAM ip address + be4_OAM_direct_ips: + type: string + label: be4 port 7 OAM ip address + description: be4 port 7 OAM ip address + fe0_SIGNET_vrf_A1_direct_ips: + type: string + label: fe0 port 0 SIGTRAN ip address + description: fe0 port 0 SIGTRAN ip address + fe0_OAM_direct_ips: + type: string + label: fe0 port 7 OAM ip address + description: fe0 port 7 OAM ip address + fe1_SIGNET_vrf_B1_direct_ips: + type: string + label: fe1 port 1 SIGTRAN ip address + description: fe1 port 1 SIGTRAN ip address + fe1_OAM_direct_ips: + type: string + label: fe1 port 7 OAM ip address + description: fe1 port 7 OAM ip address + smp0_OAM_direct_ips: + type: string + label: smp0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + smp1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: smp1 port 7 OAM ip address + db0_OAM_direct_ips: + type: string + label: db0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + db1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: db1 port 7 OAM ip address + vm_scp_be0_name: + type: string + default: vSCP_BE0 + description: name of VM + vm_scp_be1_name: + type: string + default: vSCP_BE1 + description: name of VM + vm_scp_be2_name: + type: string + default: vSCP_BE2 + description: name of VM + vm_scp_be3_name: + type: string + default: vSCP_BE3 + description: name of VM + vm_scp_be4_name: + type: string + default: vSCP_BE4 + description: name of VM + vm_scp_fe0_name: + type: string + default: vSCP_FE0 + description: name of VM + vm_scp_fe1_name: + type: string + default: vSCP_FE1 + description: name of VM + vm_smp0_name: + type: string + default: vSMP0 + description: name of VM + vm_smp1_name: + type: string + default: vSMP1 + description: name of VM + vm_db0_name: + type: string + default: vDB0 + description: name of VM + vm_db1_name: + type: string + default: vDB1 + description: name of VM + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip new file mode 100644 index 0000000000..c8a2726421 Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip differ diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml new file mode 100644 index 0000000000..6835485ca1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml @@ -0,0 +1,787 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + vnf_id: + type: string + description: Unique ID for this VNF instance + default: This_is_ths_SCP_id + + flavor_scp_be_id: + type: string + description: flavor type + default: a1.Small + flavor_scp_fe_id: + type: string + description: flavor type + default: a1.Small + flavor_smp_id: + type: string + description: flavor type + default: a1.Small + flavor_db_id: + type: string + description: flavor type + default: a1.Small + image_scp_be_id: + type: string + description: Image use to boot a server + default: asc_base_image_be + image_scp_fe_id: + type: string + description: Image use to boot a server + default: asc_base_image_fe + image_smp_id: + type: string + description: Image use to boot a server + default: asc_base_image_smp + image_db_id: + type: string + description: Image use to boot a server + default: asc_base_image_db + + int_vscp_fe_cluster_net_id: + type: string + description: LAN2 FE Cluster/KA + int_vscp_fe_cluster_cidr: + type: string + description: Private Network2 Address (CIDR notation) + int_vscp_cluster_net_id: + type: string + description: LAN3 Cluster + int_vscp_cluster_cidr: + type: string + description: Private Network3 Address (CIDR notation) + int_vscp_db_network_net_id: + type: string + description: LAN4 DB + int_vscp_db_network_cidr: + type: string + description: Private Network4 Address (CIDR notation) + SIGNET_vrf_A1_direct_net_id: + type: string + description: Network name for SIGTRAN_A + SIGNET_vrf_B1_direct_net_id: + type: string + description: Network name for SIGTRAN_B + Cricket_OCS_protected_net_id: + type: string + description: Network name for CRICKET_OCS + OAM_direct_net_id: + type: string + description: Network name for OAM + be0_Cricket_OCS_protected_ips: + type: string + label: be0 port 5 OAM ip address + description: be0 port 5 OAM ip address + be1_Cricket_OCS_protected_ips: + type: string + label: be1 port 5 OAM ip address + description: be1 port 5 OAM ip address + be2_Cricket_OCS_protected_ips: + type: string + label: be2 port 5 OAM ip address + description: be2 port 5 OAM ip address + be3_Cricket_OCS_protected_ips: + type: string + label: be3 port 5 OAM ip address + description: be3 port 5 OAM ip address + be4_Cricket_OCS_protected_ips: + type: string + label: be4 port 5 OAM ip address + description: be4 port 5 OAM ip address + be0_OAM_direct_ips: + type: string + label: be0 port 7 OAM ip address + description: be0 port 7 OAM ip address + be1_OAM_direct_ips: + type: string + label: be1 port 7 OAM ip address + description: be1 port 7 OAM ip address + be2_OAM_direct_ips: + type: string + label: be2 port 7 OAM ip address + description: be2 port 7 OAM ip address + be3_OAM_direct_ips: + type: string + label: be3 port 7 OAM ip address + description: be3 port 7 OAM ip address + be4_OAM_direct_ips: + type: string + label: be4 port 7 OAM ip address + description: be4 port 7 OAM ip address + fe0_SIGNET_vrf_A1_direct_ips: + type: string + label: fe0 port 0 SIGTRAN ip address + description: fe0 port 0 SIGTRAN ip address + fe0_OAM_direct_ips: + type: string + label: fe0 port 7 OAM ip address + description: fe0 port 7 OAM ip address + fe1_SIGNET_vrf_B1_direct_ips: + type: string + label: fe1 port 1 SIGTRAN ip address + description: fe1 port 1 SIGTRAN ip address + fe1_OAM_direct_ips: + type: string + label: fe1 port 7 OAM ip address + description: fe1 port 7 OAM ip address + smp0_OAM_direct_ips: + type: string + label: smp0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + smp1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: smp1 port 7 OAM ip address + db0_OAM_direct_ips: + type: string + label: db0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + db1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: db1 port 7 OAM ip address + vm_scp_be0_name: + type: string + default: vSCP_BE0 + description: name of VM + vm_scp_be1_name: + type: string + default: vSCP_BE1 + description: name of VM + vm_scp_be2_name: + type: string + default: vSCP_BE2 + description: name of VM + vm_scp_be3_name: + type: string + default: vSCP_BE3 + description: name of VM + vm_scp_be4_name: + type: string + default: vSCP_BE4 + description: name of VM + vm_scp_fe0_name: + type: string + default: vSCP_FE0 + description: name of VM + vm_scp_fe1_name: + type: string + default: vSCP_FE1 + description: name of VM + vm_smp0_name: + type: string + default: vSMP0 + description: name of VM + vm_smp1_name: + type: string + default: vSMP1 + description: name of VM + vm_db0_name: + type: string + default: vDB0 + description: name of VM + vm_db1_name: + type: string + default: vDB1 + description: name of VM + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env new file mode 100644 index 0000000000..6835485ca1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env @@ -0,0 +1,787 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + vnf_id: + type: string + description: Unique ID for this VNF instance + default: This_is_ths_SCP_id + + flavor_scp_be_id: + type: string + description: flavor type + default: a1.Small + flavor_scp_fe_id: + type: string + description: flavor type + default: a1.Small + flavor_smp_id: + type: string + description: flavor type + default: a1.Small + flavor_db_id: + type: string + description: flavor type + default: a1.Small + image_scp_be_id: + type: string + description: Image use to boot a server + default: asc_base_image_be + image_scp_fe_id: + type: string + description: Image use to boot a server + default: asc_base_image_fe + image_smp_id: + type: string + description: Image use to boot a server + default: asc_base_image_smp + image_db_id: + type: string + description: Image use to boot a server + default: asc_base_image_db + + int_vscp_fe_cluster_net_id: + type: string + description: LAN2 FE Cluster/KA + int_vscp_fe_cluster_cidr: + type: string + description: Private Network2 Address (CIDR notation) + int_vscp_cluster_net_id: + type: string + description: LAN3 Cluster + int_vscp_cluster_cidr: + type: string + description: Private Network3 Address (CIDR notation) + int_vscp_db_network_net_id: + type: string + description: LAN4 DB + int_vscp_db_network_cidr: + type: string + description: Private Network4 Address (CIDR notation) + SIGNET_vrf_A1_direct_net_id: + type: string + description: Network name for SIGTRAN_A + SIGNET_vrf_B1_direct_net_id: + type: string + description: Network name for SIGTRAN_B + Cricket_OCS_protected_net_id: + type: string + description: Network name for CRICKET_OCS + OAM_direct_net_id: + type: string + description: Network name for OAM + be0_Cricket_OCS_protected_ips: + type: string + label: be0 port 5 OAM ip address + description: be0 port 5 OAM ip address + be1_Cricket_OCS_protected_ips: + type: string + label: be1 port 5 OAM ip address + description: be1 port 5 OAM ip address + be2_Cricket_OCS_protected_ips: + type: string + label: be2 port 5 OAM ip address + description: be2 port 5 OAM ip address + be3_Cricket_OCS_protected_ips: + type: string + label: be3 port 5 OAM ip address + description: be3 port 5 OAM ip address + be4_Cricket_OCS_protected_ips: + type: string + label: be4 port 5 OAM ip address + description: be4 port 5 OAM ip address + be0_OAM_direct_ips: + type: string + label: be0 port 7 OAM ip address + description: be0 port 7 OAM ip address + be1_OAM_direct_ips: + type: string + label: be1 port 7 OAM ip address + description: be1 port 7 OAM ip address + be2_OAM_direct_ips: + type: string + label: be2 port 7 OAM ip address + description: be2 port 7 OAM ip address + be3_OAM_direct_ips: + type: string + label: be3 port 7 OAM ip address + description: be3 port 7 OAM ip address + be4_OAM_direct_ips: + type: string + label: be4 port 7 OAM ip address + description: be4 port 7 OAM ip address + fe0_SIGNET_vrf_A1_direct_ips: + type: string + label: fe0 port 0 SIGTRAN ip address + description: fe0 port 0 SIGTRAN ip address + fe0_OAM_direct_ips: + type: string + label: fe0 port 7 OAM ip address + description: fe0 port 7 OAM ip address + fe1_SIGNET_vrf_B1_direct_ips: + type: string + label: fe1 port 1 SIGTRAN ip address + description: fe1 port 1 SIGTRAN ip address + fe1_OAM_direct_ips: + type: string + label: fe1 port 7 OAM ip address + description: fe1 port 7 OAM ip address + smp0_OAM_direct_ips: + type: string + label: smp0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + smp1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: smp1 port 7 OAM ip address + db0_OAM_direct_ips: + type: string + label: db0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + db1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: db1 port 7 OAM ip address + vm_scp_be0_name: + type: string + default: vSCP_BE0 + description: name of VM + vm_scp_be1_name: + type: string + default: vSCP_BE1 + description: name of VM + vm_scp_be2_name: + type: string + default: vSCP_BE2 + description: name of VM + vm_scp_be3_name: + type: string + default: vSCP_BE3 + description: name of VM + vm_scp_be4_name: + type: string + default: vSCP_BE4 + description: name of VM + vm_scp_fe0_name: + type: string + default: vSCP_FE0 + description: name of VM + vm_scp_fe1_name: + type: string + default: vSCP_FE1 + description: name of VM + vm_smp0_name: + type: string + default: vSMP0 + description: name of VM + vm_smp1_name: + type: string + default: vSMP1 + description: name of VM + vm_db0_name: + type: string + default: vDB0 + description: name of VM + vm_db1_name: + type: string + default: vDB1 + description: name of VM + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml new file mode 100644 index 0000000000..b70d5a4b0a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml @@ -0,0 +1,9 @@ +heat_template_version: 2013-05-23 + +parameters: + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml new file mode 100644 index 0000000000..a545569129 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml @@ -0,0 +1,13 @@ +heat_template_version: 2013-05-23 + +parameters: + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + +resources: + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json new file mode 100644 index 0000000000..48a3e89deb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json @@ -0,0 +1,11 @@ +{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml new file mode 100644 index 0000000000..5c51039931 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml @@ -0,0 +1,787 @@ + heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + vnf_id: + type: string + description: Unique ID for this VNF instance + default: This_is_ths_SCP_id + + flavor_scp_be_id: + type: string + description: flavor type + default: a1.Small + flavor_scp_fe_id: + type: string + description: flavor type + default: a1.Small + flavor_smp_id: + type: string + description: flavor type + default: a1.Small + flavor_db_id: + type: string + description: flavor type + default: a1.Small + image_scp_be_id: + type: string + description: Image use to boot a server + default: asc_base_image_be + image_scp_fe_id: + type: string + description: Image use to boot a server + default: asc_base_image_fe + image_smp_id: + type: string + description: Image use to boot a server + default: asc_base_image_smp + image_db_id: + type: string + description: Image use to boot a server + default: asc_base_image_db + + int_vscp_fe_cluster_net_id: + type: string + description: LAN2 FE Cluster/KA + int_vscp_fe_cluster_cidr: + type: string + description: Private Network2 Address (CIDR notation) + int_vscp_cluster_net_id: + type: string + description: LAN3 Cluster + int_vscp_cluster_cidr: + type: string + description: Private Network3 Address (CIDR notation) + int_vscp_db_network_net_id: + type: string + description: LAN4 DB + int_vscp_db_network_cidr: + type: string + description: Private Network4 Address (CIDR notation) + SIGNET_vrf_A1_direct_net_id: + type: string + description: Network name for SIGTRAN_A + SIGNET_vrf_B1_direct_net_id: + type: string + description: Network name for SIGTRAN_B + Cricket_OCS_protected_net_id: + type: string + description: Network name for CRICKET_OCS + OAM_direct_net_id: + type: string + description: Network name for OAM + be0_Cricket_OCS_protected_ips: + type: string + label: be0 port 5 OAM ip address + description: be0 port 5 OAM ip address + be1_Cricket_OCS_protected_ips: + type: string + label: be1 port 5 OAM ip address + description: be1 port 5 OAM ip address + be2_Cricket_OCS_protected_ips: + type: string + label: be2 port 5 OAM ip address + description: be2 port 5 OAM ip address + be3_Cricket_OCS_protected_ips: + type: string + label: be3 port 5 OAM ip address + description: be3 port 5 OAM ip address + be4_Cricket_OCS_protected_ips: + type: string + label: be4 port 5 OAM ip address + description: be4 port 5 OAM ip address + be0_OAM_direct_ips: + type: string + label: be0 port 7 OAM ip address + description: be0 port 7 OAM ip address + be1_OAM_direct_ips: + type: string + label: be1 port 7 OAM ip address + description: be1 port 7 OAM ip address + be2_OAM_direct_ips: + type: string + label: be2 port 7 OAM ip address + description: be2 port 7 OAM ip address + be3_OAM_direct_ips: + type: string + label: be3 port 7 OAM ip address + description: be3 port 7 OAM ip address + be4_OAM_direct_ips: + type: string + label: be4 port 7 OAM ip address + description: be4 port 7 OAM ip address + fe0_SIGNET_vrf_A1_direct_ips: + type: string + label: fe0 port 0 SIGTRAN ip address + description: fe0 port 0 SIGTRAN ip address + fe0_OAM_direct_ips: + type: string + label: fe0 port 7 OAM ip address + description: fe0 port 7 OAM ip address + fe1_SIGNET_vrf_B1_direct_ips: + type: string + label: fe1 port 1 SIGTRAN ip address + description: fe1 port 1 SIGTRAN ip address + fe1_OAM_direct_ips: + type: string + label: fe1 port 7 OAM ip address + description: fe1 port 7 OAM ip address + smp0_OAM_direct_ips: + type: string + label: smp0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + smp1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: smp1 port 7 OAM ip address + db0_OAM_direct_ips: + type: string + label: db0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + db1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: db1 port 7 OAM ip address + vm_scp_be0_name: + type: string + default: vSCP_BE0 + description: name of VM + vm_scp_be1_name: + type: string + default: vSCP_BE1 + description: name of VM + vm_scp_be2_name: + type: string + default: vSCP_BE2 + description: name of VM + vm_scp_be3_name: + type: string + default: vSCP_BE3 + description: name of VM + vm_scp_be4_name: + type: string + default: vSCP_BE4 + description: name of VM + vm_scp_fe0_name: + type: string + default: vSCP_FE0 + description: name of VM + vm_scp_fe1_name: + type: string + default: vSCP_FE1 + description: name of VM + vm_smp0_name: + type: string + default: vSMP0 + description: name of VM + vm_smp1_name: + type: string + default: vSMP1 + description: name of VM + vm_db0_name: + type: string + default: vDB0 + description: name of VM + vm_db1_name: + type: string + default: vDB1 + description: name of VM + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml new file mode 100644 index 0000000000..8978e0d5ed --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml @@ -0,0 +1,35 @@ + + + + + Lionel Andr�s Messi + 1987-06-24T00:00:00-00:00 + + + Cristiano Ronaldo + 1985-02-05T00:00:00-00:00 + + + FC Barcelona + + Lionel Andr�s Messi + Champions League 2014/2015 + 10 + 43 + + + + Real Madrid + + Cristiano Ronaldo + Champions League 2014/2015 + 7 + 48 + + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json new file mode 100644 index 0000000000..d5ca56d195 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json @@ -0,0 +1,22 @@ +{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": ["GML", "XML"] + }, + "GlossSee": "markup" + } + } + } + } +} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt new file mode 100644 index 0000000000..5f8f77ca2c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt @@ -0,0 +1,3 @@ +cmd1 +cmd2 +cmd3 \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml new file mode 100644 index 0000000000..10c46b7269 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml @@ -0,0 +1,3 @@ + + dfsfsdfsdf + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx new file mode 100644 index 0000000000..c281f532f8 Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx differ diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf new file mode 100644 index 0000000000..9c478f6ce1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf @@ -0,0 +1,2 @@ +This is sample EMF file +We currently not checking the file content. \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml new file mode 100644 index 0000000000..10c46b7269 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml @@ -0,0 +1,3 @@ + + dfsfsdfsdf + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml new file mode 100644 index 0000000000..10c46b7269 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml @@ -0,0 +1,3 @@ + + dfsfsdfsdf + \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json new file mode 100644 index 0000000000..b749a9e89c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json @@ -0,0 +1,3 @@ +{ + "test": "This is test" +} diff --git a/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml new file mode 100644 index 0000000000..10ccf71d51 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml @@ -0,0 +1,5 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.CP: + derived_from: org.openecomp.resource.cp.root \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml b/test-apis-ci/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml new file mode 100644 index 0000000000..6835485ca1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml @@ -0,0 +1,787 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + vnf_id: + type: string + description: Unique ID for this VNF instance + default: This_is_ths_SCP_id + + flavor_scp_be_id: + type: string + description: flavor type + default: a1.Small + flavor_scp_fe_id: + type: string + description: flavor type + default: a1.Small + flavor_smp_id: + type: string + description: flavor type + default: a1.Small + flavor_db_id: + type: string + description: flavor type + default: a1.Small + image_scp_be_id: + type: string + description: Image use to boot a server + default: asc_base_image_be + image_scp_fe_id: + type: string + description: Image use to boot a server + default: asc_base_image_fe + image_smp_id: + type: string + description: Image use to boot a server + default: asc_base_image_smp + image_db_id: + type: string + description: Image use to boot a server + default: asc_base_image_db + + int_vscp_fe_cluster_net_id: + type: string + description: LAN2 FE Cluster/KA + int_vscp_fe_cluster_cidr: + type: string + description: Private Network2 Address (CIDR notation) + int_vscp_cluster_net_id: + type: string + description: LAN3 Cluster + int_vscp_cluster_cidr: + type: string + description: Private Network3 Address (CIDR notation) + int_vscp_db_network_net_id: + type: string + description: LAN4 DB + int_vscp_db_network_cidr: + type: string + description: Private Network4 Address (CIDR notation) + SIGNET_vrf_A1_direct_net_id: + type: string + description: Network name for SIGTRAN_A + SIGNET_vrf_B1_direct_net_id: + type: string + description: Network name for SIGTRAN_B + Cricket_OCS_protected_net_id: + type: string + description: Network name for CRICKET_OCS + OAM_direct_net_id: + type: string + description: Network name for OAM + be0_Cricket_OCS_protected_ips: + type: string + label: be0 port 5 OAM ip address + description: be0 port 5 OAM ip address + be1_Cricket_OCS_protected_ips: + type: string + label: be1 port 5 OAM ip address + description: be1 port 5 OAM ip address + be2_Cricket_OCS_protected_ips: + type: string + label: be2 port 5 OAM ip address + description: be2 port 5 OAM ip address + be3_Cricket_OCS_protected_ips: + type: string + label: be3 port 5 OAM ip address + description: be3 port 5 OAM ip address + be4_Cricket_OCS_protected_ips: + type: string + label: be4 port 5 OAM ip address + description: be4 port 5 OAM ip address + be0_OAM_direct_ips: + type: string + label: be0 port 7 OAM ip address + description: be0 port 7 OAM ip address + be1_OAM_direct_ips: + type: string + label: be1 port 7 OAM ip address + description: be1 port 7 OAM ip address + be2_OAM_direct_ips: + type: string + label: be2 port 7 OAM ip address + description: be2 port 7 OAM ip address + be3_OAM_direct_ips: + type: string + label: be3 port 7 OAM ip address + description: be3 port 7 OAM ip address + be4_OAM_direct_ips: + type: string + label: be4 port 7 OAM ip address + description: be4 port 7 OAM ip address + fe0_SIGNET_vrf_A1_direct_ips: + type: string + label: fe0 port 0 SIGTRAN ip address + description: fe0 port 0 SIGTRAN ip address + fe0_OAM_direct_ips: + type: string + label: fe0 port 7 OAM ip address + description: fe0 port 7 OAM ip address + fe1_SIGNET_vrf_B1_direct_ips: + type: string + label: fe1 port 1 SIGTRAN ip address + description: fe1 port 1 SIGTRAN ip address + fe1_OAM_direct_ips: + type: string + label: fe1 port 7 OAM ip address + description: fe1 port 7 OAM ip address + smp0_OAM_direct_ips: + type: string + label: smp0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + smp1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: smp1 port 7 OAM ip address + db0_OAM_direct_ips: + type: string + label: db0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + db1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: db1 port 7 OAM ip address + vm_scp_be0_name: + type: string + default: vSCP_BE0 + description: name of VM + vm_scp_be1_name: + type: string + default: vSCP_BE1 + description: name of VM + vm_scp_be2_name: + type: string + default: vSCP_BE2 + description: name of VM + vm_scp_be3_name: + type: string + default: vSCP_BE3 + description: name of VM + vm_scp_be4_name: + type: string + default: vSCP_BE4 + description: name of VM + vm_scp_fe0_name: + type: string + default: vSCP_FE0 + description: name of VM + vm_scp_fe1_name: + type: string + default: vSCP_FE1 + description: name of VM + vm_smp0_name: + type: string + default: vSMP0 + description: name of VM + vm_smp1_name: + type: string + default: vSMP1 + description: name of VM + vm_db0_name: + type: string + default: vDB0 + description: name of VM + vm_db1_name: + type: string + default: vDB1 + description: name of VM + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip b/test-apis-ci/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip new file mode 100644 index 0000000000..0951d5cef8 Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/mysql.yml new file mode 100644 index 0000000000..f512f8071e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getResourceArtifactFileContentTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getResourceArtifactFileContentTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactFileContentTest/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListNoContentTest/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListNoContentTest/mysql.yml new file mode 100644 index 0000000000..180e247ea2 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListNoContentTest/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getResourceArtifactListNoContentTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getResourceArtifactListNoContentTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/mysql.yml new file mode 100644 index 0000000000..b8f9bbdc69 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-GetResourceArtifactListTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-GetResourceArtifactListTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactListTest/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataNoContentTest/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataNoContentTest/mysql.yml new file mode 100644 index 0000000000..72ff4f37e0 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataNoContentTest/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getResourceArtifactMetadataNoContentTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getResourceArtifactMetadataNoContentTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/mysql.yml new file mode 100644 index 0000000000..527e4a0081 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getResourceArtifactMetadataTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getResourceArtifactMetadataTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactMetadataTest/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactPayloadNoContentTest/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactPayloadNoContentTest/mysql.yml new file mode 100644 index 0000000000..7177a65387 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getResourceArtifactPayloadNoContentTest/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getResourceArtifactPayloadNoContentTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getResourceArtifactPayloadNoContentTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/mysql.yml new file mode 100644 index 0000000000..e0a0c6458e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListTest + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListTest: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListTest: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource1/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/mysql.yml new file mode 100644 index 0000000000..dc5ff158c8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListTest2 +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListTest2: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListTest2 + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListTest2: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListTest2: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/install_mysql2.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/install_mysql2.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/install_mysql2.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/start_mysql2.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/start_mysql2.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/resource2/scripts/start_mysql2.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topology.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topology.txt new file mode 100644 index 0000000000..cb3c3e8546 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topology.txt @@ -0,0 +1 @@ +{"id":"6a4b2f9d-7fe1-482d-af11-97f483dff5b7","delegateId":"9c063349-2259-40fe-97f1-7c40e659e1b0","delegateType":"topologytemplate","dependencies":[{"name":"tosca-normative-types-DBMS","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListTest2","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-softwareComponent","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-compute","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-root","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListTest","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-database","version":"1.0.0.wd03-SNAPSHOT"}],"nodeTemplates":[{"key":"Mysql-getServiceArtifactListTest","value":{"type":"alien.nodes.Mysql-getServiceArtifactListTest","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"hostedOnCompute":{"type":"tosca.relationships.HostedOn","target":"Compute","requirementName":"host","requirementType":"tosca.nodes.Compute","targetedCapabilityName":"host"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListTest","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}},{"key":"Compute","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}},{"key":"Mysql-getServiceArtifactListTest2","value":{"type":"alien.nodes.Mysql-getServiceArtifactListTest2","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"hostedOnCompute":{"type":"tosca.relationships.HostedOn","target":"Compute","requirementName":"host","requirementType":"tosca.nodes.Compute","targetedCapabilityName":"host"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListTest2","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}}]} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topologyTemplate.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topologyTemplate.txt new file mode 100644 index 0000000000..f0d0849db8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListInvalidVersionNotFoundTest/topologyTemplate.txt @@ -0,0 +1,2 @@ +{"id":"9c063349-2259-40fe-97f1-7c40e659e1b0","name":"Andrey","description":null,"topologyId":"6a4b2f9d-7fe1-482d-af11-97f483dff5b7"} + diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/mysql.yml new file mode 100644 index 0000000000..4ee2c8ca88 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource1/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListNoContentTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListNoContentTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListNoContentTest: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/mysql.yml new file mode 100644 index 0000000000..b564dd0c4e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/resource2/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListNoContentTest2 +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListNoContentTest2: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest2 + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest2: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListNoContentTest2: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topology.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topology.txt new file mode 100644 index 0000000000..279351879a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topology.txt @@ -0,0 +1 @@ +{"id":"3293c9c8-a162-43fc-b8d1-431399f89cb7","delegateId":"25845cce-05c8-4502-b5fe-abfd6bd6f28e","delegateType":"topologytemplate","dependencies":[{"name":"tosca-normative-types-DBMS","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-softwareComponent","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-compute","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListNoContentTest2","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-root","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-database","version":"1.0.0.wd03-SNAPSHOT"}],"nodeTemplates":[{"key":"Mysql-getServiceArtifactListNoContentTest2","value":{"type":"alien.nodes.Mysql-getServiceArtifactListNoContentTest2","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest2","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}},{"key":"Compute","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":{"dependsOnMysql-getServiceArtifactListNoContentTest2":{"type":"tosca.relationships.DependsOn","target":"Mysql-getServiceArtifactListNoContentTest2","requirementName":"dependency","requirementType":"tosca.capabilities.Root","targetedCapabilityName":"root"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}}]} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topologyTemplate.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topologyTemplate.txt new file mode 100644 index 0000000000..3c342f6cd1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListNoContentTest/topologyTemplate.txt @@ -0,0 +1,2 @@ +{"id":"25845cce-05c8-4502-b5fe-abfd6bd6f28e","name":"ServiceArtListNoContent","description":null,"topologyId":"3293c9c8-a162-43fc-b8d1-431399f89cb7"} + diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/mysql.yml new file mode 100644 index 0000000000..e0a0c6458e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListTest + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListTest: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListTest: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource1/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/mysql.yml new file mode 100644 index 0000000000..dc5ff158c8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListTest2 +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListTest2: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListTest2 + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListTest2: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListTest2: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/install_mysql2.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/install_mysql2.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/install_mysql2.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/start_mysql2.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/start_mysql2.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/resource2/scripts/start_mysql2.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topology.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topology.txt new file mode 100644 index 0000000000..cb3c3e8546 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topology.txt @@ -0,0 +1 @@ +{"id":"6a4b2f9d-7fe1-482d-af11-97f483dff5b7","delegateId":"9c063349-2259-40fe-97f1-7c40e659e1b0","delegateType":"topologytemplate","dependencies":[{"name":"tosca-normative-types-DBMS","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListTest2","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-softwareComponent","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-compute","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-root","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListTest","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-database","version":"1.0.0.wd03-SNAPSHOT"}],"nodeTemplates":[{"key":"Mysql-getServiceArtifactListTest","value":{"type":"alien.nodes.Mysql-getServiceArtifactListTest","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"hostedOnCompute":{"type":"tosca.relationships.HostedOn","target":"Compute","requirementName":"host","requirementType":"tosca.nodes.Compute","targetedCapabilityName":"host"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListTest","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}},{"key":"Compute","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}},{"key":"Mysql-getServiceArtifactListTest2","value":{"type":"alien.nodes.Mysql-getServiceArtifactListTest2","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"hostedOnCompute":{"type":"tosca.relationships.HostedOn","target":"Compute","requirementName":"host","requirementType":"tosca.nodes.Compute","targetedCapabilityName":"host"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListTest2","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}}]} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topologyTemplate.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topologyTemplate.txt new file mode 100644 index 0000000000..f0d0849db8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceArtifactListTest/topologyTemplate.txt @@ -0,0 +1,2 @@ +{"id":"9c063349-2259-40fe-97f1-7c40e659e1b0","name":"Andrey","description":null,"topologyId":"6a4b2f9d-7fe1-482d-af11-97f483dff5b7"} + diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/mysql.yml new file mode 100644 index 0000000000..e0a0c6458e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListTest + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListTest: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListTest: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource1/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/mysql.yml new file mode 100644 index 0000000000..dc5ff158c8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListTest2 +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListTest2: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListTest2 + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListTest2: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListTest2: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/install_mysql2.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/install_mysql2.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/install_mysql2.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/start_mysql2.sh b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/start_mysql2.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/resource2/scripts/start_mysql2.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topology.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topology.txt new file mode 100644 index 0000000000..cb3c3e8546 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topology.txt @@ -0,0 +1 @@ +{"id":"6a4b2f9d-7fe1-482d-af11-97f483dff5b7","delegateId":"9c063349-2259-40fe-97f1-7c40e659e1b0","delegateType":"topologytemplate","dependencies":[{"name":"tosca-normative-types-DBMS","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListTest2","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-softwareComponent","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-compute","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-root","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListTest","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-database","version":"1.0.0.wd03-SNAPSHOT"}],"nodeTemplates":[{"key":"Mysql-getServiceArtifactListTest","value":{"type":"alien.nodes.Mysql-getServiceArtifactListTest","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"hostedOnCompute":{"type":"tosca.relationships.HostedOn","target":"Compute","requirementName":"host","requirementType":"tosca.nodes.Compute","targetedCapabilityName":"host"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListTest","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}},{"key":"Compute","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}},{"key":"Mysql-getServiceArtifactListTest2","value":{"type":"alien.nodes.Mysql-getServiceArtifactListTest2","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"hostedOnCompute":{"type":"tosca.relationships.HostedOn","target":"Compute","requirementName":"host","requirementType":"tosca.nodes.Compute","targetedCapabilityName":"host"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListTest2","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}}]} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topologyTemplate.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topologyTemplate.txt new file mode 100644 index 0000000000..f0d0849db8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service1/topologyTemplate.txt @@ -0,0 +1,2 @@ +{"id":"9c063349-2259-40fe-97f1-7c40e659e1b0","name":"Andrey","description":null,"topologyId":"6a4b2f9d-7fe1-482d-af11-97f483dff5b7"} + diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/mysql.yml new file mode 100644 index 0000000000..4ee2c8ca88 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource1/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListNoContentTest +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListNoContentTest: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListNoContentTest: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/mysql.yml new file mode 100644 index 0000000000..b564dd0c4e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/resource2/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-getServiceArtifactListNoContentTest2 +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-getServiceArtifactListNoContentTest2: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest2 + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest2: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript-getServiceArtifactListNoContentTest2: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topology.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topology.txt new file mode 100644 index 0000000000..279351879a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topology.txt @@ -0,0 +1 @@ +{"id":"3293c9c8-a162-43fc-b8d1-431399f89cb7","delegateId":"25845cce-05c8-4502-b5fe-abfd6bd6f28e","delegateType":"topologytemplate","dependencies":[{"name":"tosca-normative-types-DBMS","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-softwareComponent","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-compute","version":"1.0.0.wd03-SNAPSHOT"},{"name":"mysql-getServiceArtifactListNoContentTest2","version":"1.1.1-SNAPSHOT"},{"name":"tosca-normative-types-root","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-database","version":"1.0.0.wd03-SNAPSHOT"}],"nodeTemplates":[{"key":"Mysql-getServiceArtifactListNoContentTest2","value":{"type":"alien.nodes.Mysql-getServiceArtifactListNoContentTest2","name":null,"properties":{"bind_address":"true","storage_path":"/mountedStorage","db_port":"3306","db_name":"wordpress","db_user":"pass","db_password":"pass"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"database_endpoint":{"type":"tosca.capabilities.DatabaseEndpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.MysqlDatabase-getServiceArtifactListNoContentTest2","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":{"scripts":{"artifactType":"tosca.artifacts.File","artifactRef":"scripts","artifactName":"scripts","artifactRepository":null}}}},{"key":"Compute","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":{"dependsOnMysql-getServiceArtifactListNoContentTest2":{"type":"tosca.relationships.DependsOn","target":"Mysql-getServiceArtifactListNoContentTest2","requirementName":"dependency","requirementType":"tosca.capabilities.Root","targetedCapabilityName":"root"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}}]} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topologyTemplate.txt b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topologyTemplate.txt new file mode 100644 index 0000000000..3c342f6cd1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/getServiceListTest/Service2/topologyTemplate.txt @@ -0,0 +1,2 @@ +{"id":"25845cce-05c8-4502-b5fe-abfd6bd6f28e","name":"ServiceArtListNoContent","description":null,"topologyId":"3293c9c8-a162-43fc-b8d1-431399f89cb7"} + diff --git a/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml new file mode 100644 index 0000000000..6aad589bdb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml @@ -0,0 +1,603 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_missing_default: + type: string + description: Unique name for this VNF instance + label: be4 port 5 OAM ip address + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml new file mode 100644 index 0000000000..d51a20d77f --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml @@ -0,0 +1,603 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_missing_desc: + type: string + default: This_is_the_SCP_name + label: be4 port 5 OAM ip address + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml new file mode 100644 index 0000000000..29527495f7 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml @@ -0,0 +1,603 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_missing_desc: + description: Unique name for this VNF instance + default: This_is_the_SCP_name + label: be4 port 5 OAM ip address + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml new file mode 100644 index 0000000000..6835485ca1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml @@ -0,0 +1,787 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +# availability_zone_smp0: +# type: string +# default: nova +# availability_zone_smp1: +# type: string +# default: nova +# availability_zone_fe0: +# type: string +# default: nova +# availability_zone_fe1: +# type: string +# default: nova +# availability_zone_db0: +# type: string +# default: nova +# availability_zone_db1: +# type: string +# default: nova +# availability_zone_be0: +# type: string +# default: nova +# availability_zone_be1: +# type: string +# default: nova +# availability_zone_be2: +# type: string +# default: nova +# availability_zone_be3: +# type: string +# default: nova +# availability_zone_be4: +# type: string +# default: nova + + vnf_name: + type: string + description: Unique name for this VNF instance + default: This_is_the_SCP_name + vnf_id: + type: string + description: Unique ID for this VNF instance + default: This_is_ths_SCP_id + + flavor_scp_be_id: + type: string + description: flavor type + default: a1.Small + flavor_scp_fe_id: + type: string + description: flavor type + default: a1.Small + flavor_smp_id: + type: string + description: flavor type + default: a1.Small + flavor_db_id: + type: string + description: flavor type + default: a1.Small + image_scp_be_id: + type: string + description: Image use to boot a server + default: asc_base_image_be + image_scp_fe_id: + type: string + description: Image use to boot a server + default: asc_base_image_fe + image_smp_id: + type: string + description: Image use to boot a server + default: asc_base_image_smp + image_db_id: + type: string + description: Image use to boot a server + default: asc_base_image_db + + int_vscp_fe_cluster_net_id: + type: string + description: LAN2 FE Cluster/KA + int_vscp_fe_cluster_cidr: + type: string + description: Private Network2 Address (CIDR notation) + int_vscp_cluster_net_id: + type: string + description: LAN3 Cluster + int_vscp_cluster_cidr: + type: string + description: Private Network3 Address (CIDR notation) + int_vscp_db_network_net_id: + type: string + description: LAN4 DB + int_vscp_db_network_cidr: + type: string + description: Private Network4 Address (CIDR notation) + SIGNET_vrf_A1_direct_net_id: + type: string + description: Network name for SIGTRAN_A + SIGNET_vrf_B1_direct_net_id: + type: string + description: Network name for SIGTRAN_B + Cricket_OCS_protected_net_id: + type: string + description: Network name for CRICKET_OCS + OAM_direct_net_id: + type: string + description: Network name for OAM + be0_Cricket_OCS_protected_ips: + type: string + label: be0 port 5 OAM ip address + description: be0 port 5 OAM ip address + be1_Cricket_OCS_protected_ips: + type: string + label: be1 port 5 OAM ip address + description: be1 port 5 OAM ip address + be2_Cricket_OCS_protected_ips: + type: string + label: be2 port 5 OAM ip address + description: be2 port 5 OAM ip address + be3_Cricket_OCS_protected_ips: + type: string + label: be3 port 5 OAM ip address + description: be3 port 5 OAM ip address + be4_Cricket_OCS_protected_ips: + type: string + label: be4 port 5 OAM ip address + description: be4 port 5 OAM ip address + be0_OAM_direct_ips: + type: string + label: be0 port 7 OAM ip address + description: be0 port 7 OAM ip address + be1_OAM_direct_ips: + type: string + label: be1 port 7 OAM ip address + description: be1 port 7 OAM ip address + be2_OAM_direct_ips: + type: string + label: be2 port 7 OAM ip address + description: be2 port 7 OAM ip address + be3_OAM_direct_ips: + type: string + label: be3 port 7 OAM ip address + description: be3 port 7 OAM ip address + be4_OAM_direct_ips: + type: string + label: be4 port 7 OAM ip address + description: be4 port 7 OAM ip address + fe0_SIGNET_vrf_A1_direct_ips: + type: string + label: fe0 port 0 SIGTRAN ip address + description: fe0 port 0 SIGTRAN ip address + fe0_OAM_direct_ips: + type: string + label: fe0 port 7 OAM ip address + description: fe0 port 7 OAM ip address + fe1_SIGNET_vrf_B1_direct_ips: + type: string + label: fe1 port 1 SIGTRAN ip address + description: fe1 port 1 SIGTRAN ip address + fe1_OAM_direct_ips: + type: string + label: fe1 port 7 OAM ip address + description: fe1 port 7 OAM ip address + smp0_OAM_direct_ips: + type: string + label: smp0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + smp1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: smp1 port 7 OAM ip address + db0_OAM_direct_ips: + type: string + label: db0 port 7 OAM ip address + description: smp0 port 7 OAM ip address + db1_OAM_direct_ips: + type: string + label: smp1 port 7 OAM ip address + description: db1 port 7 OAM ip address + vm_scp_be0_name: + type: string + default: vSCP_BE0 + description: name of VM + vm_scp_be1_name: + type: string + default: vSCP_BE1 + description: name of VM + vm_scp_be2_name: + type: string + default: vSCP_BE2 + description: name of VM + vm_scp_be3_name: + type: string + default: vSCP_BE3 + description: name of VM + vm_scp_be4_name: + type: string + default: vSCP_BE4 + description: name of VM + vm_scp_fe0_name: + type: string + default: vSCP_FE0 + description: name of VM + vm_scp_fe1_name: + type: string + default: vSCP_FE1 + description: name of VM + vm_smp0_name: + type: string + default: vSMP0 + description: name of VM + vm_smp1_name: + type: string + default: vSMP1 + description: name of VM + vm_db0_name: + type: string + default: vDB0 + description: name of VM + vm_db1_name: + type: string + default: vDB1 + description: name of VM + +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_1.yaml b/test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_1.yaml new file mode 100644 index 0000000000..7d4a85c2b6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_1.yaml @@ -0,0 +1,144 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: string + description: city name + default: Hulon + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 + private_building: + type: boolean + description: home_number + default: true +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_2.yaml b/test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_2.yaml new file mode 100644 index 0000000000..2c404f0721 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatEnv/artifact_2.yaml @@ -0,0 +1,469 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: +parameters: + city_name: + type: string + description: city name + default: Hulon + address: + type: string + description: address + default: Narkis + home_number: + type: number + description: home_number + default: 14 + private_building: + type: boolean + description: home_number + default: true +resources: + be0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be0_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be0_Cricket_OCS_protected_ips}}] + + be0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be0_OAM_direct_ips}}] + + server_scp_be1: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be1_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be1 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be1_port_3 } + - port: { get_resource: be1_port_4 } + - port: { get_resource: be1_port_5 } + - port: { get_resource: be1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be1_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be1_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be1_Cricket_OCS_protected_ips}}] + + be1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be1_OAM_direct_ips}}] + + server_scp_be2: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be2_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be2 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be2_port_3 } + - port: { get_resource: be2_port_4 } + - port: { get_resource: be2_port_5 } + - port: { get_resource: be2_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be2_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be2_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be2_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be2_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be2_Cricket_OCS_protected_ips}}] + + be2_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be2_OAM_direct_ips}}] + + server_scp_be3: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be3_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be3 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be3_port_3 } + - port: { get_resource: be3_port_4 } + - port: { get_resource: be3_port_5 } + - port: { get_resource: be3_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be3_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be3_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be3_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be3_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be3_Cricket_OCS_protected_ips}}] + + be3_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be3_OAM_direct_ips}}] + + server_scp_be4: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be4_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be4 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be4_port_3 } + - port: { get_resource: be4_port_4 } + - port: { get_resource: be4_port_5 } + - port: { get_resource: be4_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be4_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } + + be4_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + be4_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + be4_port_5: + type: OS::Neutron::Port + properties: + network: { get_param: Cricket_OCS_protected_net_id } + fixed_ips: [{"ip_address": {get_param: be4_Cricket_OCS_protected_ips}}] + + be4_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: be4_OAM_direct_ips}}] + + server_scp_fe0: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe0_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe0 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe0_port_0 } + - port: { get_resource: fe0_port_2 } + - port: { get_resource: fe0_port_3 } + - port: { get_resource: fe0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe0_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe0_port_0: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_A1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_SIGNET_vrf_A1_direct_ips}}] + + fe0_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe0_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe0_OAM_direct_ips}}] + + server_scp_fe1: + type: OS::Nova::Server +# depends on: scp_be_wait_condition + properties: + name: { get_param: vm_scp_fe1_name } + image: { get_param: image_scp_fe_id } +# availability_zone: { get_param: availability_zone_fe1 } + flavor: { get_param: flavor_scp_fe_id } + scheduler_hints: { group: { get_resource: FE_Affinity } } + networks: + - port: { get_resource: fe1_port_1 } + - port: { get_resource: fe1_port_2 } + - port: { get_resource: fe1_port_3 } + - port: { get_resource: fe1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_fe1_name} +# wc_notify: { get_attr: ['scp_fe_wait_handle', 'curl_cli'] } + + fe1_port_1: + type: OS::Neutron::Port + properties: + network: { get_param: SIGNET_vrf_B1_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_SIGNET_vrf_B1_direct_ips}}] + + fe1_port_2: + type: OS::Neutron::Port + properties: + network_id: { get_resource: FE_Clustering_KA } + + fe1_port_3: + type: OS::Neutron::Port + properties: + network_id: { get_resource: Clustering_Network } + + fe1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: fe1_OAM_direct_ips}}] + + server_smp0: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp0_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp0 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp0_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp0_OAM_direct_ips}}] + + server_smp1: + type: OS::Nova::Server + properties: + name: { get_param: vm_smp1_name } + image: { get_param: image_smp_id } +# availability_zone: { get_param: availability_zone_smp1 } + flavor: { get_param: flavor_smp_id } + scheduler_hints: { group: { get_resource: SMP_Affinity } } + networks: + - port: { get_resource: smp1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_smp1_name} +# wc_notify: { get_attr: ['smp_wait_handle', 'curl_cli'] } + + smp1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: smp1_OAM_direct_ips}}] + + server_db0: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db0_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db0 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db0_port_4 } + - port: { get_resource: db0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db0_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db0_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db0_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db0_OAM_direct_ips}}] + + server_db1: + type: OS::Nova::Server +# depends_on: smp_wait_condition + properties: + name: { get_param: vm_db1_name } + image: { get_param: image_db_id } +# availability_zone: { get_param: availability_zone_db1 } + flavor: { get_param: flavor_db_id } + scheduler_hints: { group: { get_resource: DB_Affinity } } + networks: + - port: { get_resource: db1_port_4 } + - port: { get_resource: db1_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_db1_name} +# wc_notify: { get_attr: ['db_wait_handle', 'curl_cli'] } + + db1_port_4: + type: OS::Neutron::Port + properties: + network_id: { get_resource: DB_Network } + + db1_port_7: + type: OS::Neutron::Port + properties: + network: { get_param: OAM_direct_net_id } + fixed_ips: [{"ip_address": {get_param: db1_OAM_direct_ips}}] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/heatEnv/yuli.yaml b/test-apis-ci/src/test/resources/CI/tests/heatEnv/yuli.yaml new file mode 100644 index 0000000000..7d4a85c2b6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/heatEnv/yuli.yaml @@ -0,0 +1,144 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: string + description: city name + default: Hulon + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 + private_building: + type: boolean + description: home_number + default: true +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml new file mode 100644 index 0000000000..5117247373 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml @@ -0,0 +1,14 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp: + derived_from: tosca.nodes.Root + properties: + type: + type: string + required: false + requirements: + - VirtualBinding: + capability: tosca.capabilities.network.Bindable + relationship: tosca.relationships.network.BindsTo + occurrences: [0, UNBOUNDED] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml new file mode 100644 index 0000000000..8309df24b5 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml @@ -0,0 +1,9 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.CP: + derived_from: tosca.nodes.Compute + properties: + type: + type: string + required: false \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml new file mode 100644 index 0000000000..478e742bc5 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml @@ -0,0 +1,9 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.CP: + derived_from: org.openecomp.resource.MyCompute1 + properties: + type: + type: string + required: false \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml new file mode 100644 index 0000000000..807f7fe630 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml @@ -0,0 +1,56 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.CP: derived_from: tosca.nodes.Root + properties: + type: + type: string + required: false + ip_address: + type: string + required: false + description: Allow the user to set a static IP. + order: + type: integer + required: false + default: 0 + description: The order of the NIC on the compute instance (e.g. eth2). + is_default: + type: boolean + required: false + default: false + description: “If is_default=true this port will be used for the default gateway route. Only one port that is associated to single compute node can set as is_default=true.” + ip_range_start: + type: string + required: false + description: “Defines the starting IP of a range to be allocated for the VFC instances that are associated with this Port.” + ip_range_end: + type: string + required: false + description: “Defines the ending IP of a range to be allocated for the compute instances that are associated with this Port.” + is_tagged: + type: boolean + required: false + default: false + description: + attributes: + private_address: + type: string + default: "Hello" + value: "HelloWord" + public_address: + default: "DefaultValuePublicAddress" + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - virtualLink: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualbinding: + capability: tosca.capabilities.network.Bindable relationship: tosca.relationships.network.BindsTo \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml new file mode 100644 index 0000000000..b9e6c4f9b5 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + capaBility: + type: tosca.capabilities.OperatingSystem diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml new file mode 100644 index 0000000000..230e4fa924 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute2: + derived_from: org.openecomp.resource.MyCompute1 + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + Capability: + type: tosca.capabilities.OperatingSystem diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml new file mode 100644 index 0000000000..0d097a8f20 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - requirEment: + capability: tosca.capabilities.Endpoint + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml new file mode 100644 index 0000000000..9cc1f2737b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute2: + derived_from: org.openecomp.resource.MyCompute1 + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - Requirement: + capability: tosca.capabilities.Endpoint + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml new file mode 100644 index 0000000000..3514acfe9f --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml @@ -0,0 +1,14 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.LAN: + derived_from: org.openecomp.resource.cp.CP + properties: + type: + type: string + required: false + requirements: + - virtualLink: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + occurrences: [0, UNBOUNDED] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml new file mode 100644 index 0000000000..7fbf4ec132 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml @@ -0,0 +1,27 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyChildWebApplication: + derived_from: tosca.nodes.WebApplication + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - diff: + capability: + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + deff: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml new file mode 100644 index 0000000000..fe79bb3af9 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml @@ -0,0 +1,26 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyAsset: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - test: + capability: tosca.capabilities.Scalable + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml new file mode 100644 index 0000000000..798cd5b9cd --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - DependencY: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + FeaTurE: + type: tosca.capabilities.OperatingSystem \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml new file mode 100644 index 0000000000..c72d0ee62a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml @@ -0,0 +1,22 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute2: + derived_from: org.openecomp.resource.MyCompute1 + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - diff: + capability: tosca.capabilities.Container + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml new file mode 100644 index 0000000000..7132ca493a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml @@ -0,0 +1,25 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute3: + derived_from: org.openecomp.resource.MyCompute1 + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - diff: + capability: tosca.capabilities.Container + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + deff: + type: tosca.capabilities.Container diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml new file mode 100644 index 0000000000..e9438bae3c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml @@ -0,0 +1,32 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - test: + capability: tosca.capabilities.Scalable + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml new file mode 100644 index 0000000000..039ab61939 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml @@ -0,0 +1,9 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.CP: + derived_from: tosca.nodes.Root + properties: + type: + type: string + required: false \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml new file mode 100644 index 0000000000..f20a9eb48f --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_boolean: + type: list + description : another description + default: + - false + - true + entry_schema: + description: This is my property + type: booolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml new file mode 100644 index 0000000000..f1af89ca6a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - false + - truee + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml new file mode 100644 index 0000000000..974d96ba5b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - false + - 3 + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml new file mode 100644 index 0000000000..52377e4b02 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - false + - 3.56 + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml new file mode 100644 index 0000000000..c66b4347f6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10000 + - 3.56 + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml new file mode 100644 index 0000000000..79b3c03cdf --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10000 + - aaaa + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml new file mode 100644 index 0000000000..5556e9ddfb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10000 + - true + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml new file mode 100644 index 0000000000..a3b21a64a3 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10.50 + - true + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml new file mode 100644 index 0000000000..dc28591499 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10.50 + - asdc + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml new file mode 100644 index 0000000000..e465448064 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10.50 + - 500 + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml new file mode 100644 index 0000000000..a428b51974 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10.50 + - 500.0@ + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml new file mode 100644 index 0000000000..d840253120 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10000 + - 3# + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml new file mode 100644 index 0000000000..4eb59886e4 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - false + - true% + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml new file mode 100644 index 0000000000..ad263f3d00 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml @@ -0,0 +1,18 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - false + - falsee + - true + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml new file mode 100644 index 0000000000..93e8caa0a3 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml @@ -0,0 +1,19 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: list + description : another description + default: + - 10.5 + - 10.6x + - 20.5 + - 30.5 + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml new file mode 100644 index 0000000000..ed8ea4d70c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_boolean: + type: koko + description : another description + default: + - false + - true + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml new file mode 100644 index 0000000000..c7ff0743f2 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_boolean: + type: map + description : another description + default: + - false + - true + entry_schema: + description: This is my property + type: booolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml new file mode 100644 index 0000000000..d9abb87db8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - false + - truee + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml new file mode 100644 index 0000000000..e8f9b6eaa9 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - false + - 3 + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml new file mode 100644 index 0000000000..d9dc4f955b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - false + - 3.56 + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml new file mode 100644 index 0000000000..aba6ff1992 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10000 + - 3.56 + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml new file mode 100644 index 0000000000..f27904d6e6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10000 + - aaaa + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml new file mode 100644 index 0000000000..ea123f3b1b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10000 + - true + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml new file mode 100644 index 0000000000..87b51fb2de --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10.50 + - true + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml new file mode 100644 index 0000000000..2fc8ded544 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10.50 + - asdc + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml new file mode 100644 index 0000000000..3ab449d72e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10.50 + - 500 + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml new file mode 100644 index 0000000000..e437de822e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10.50 + - 500.0@ + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml new file mode 100644 index 0000000000..f2fbc7c435 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10000 + - 3# + entry_schema: + description: This is my property + type: integer + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml new file mode 100644 index 0000000000..e375aae197 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - false + - true% + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml new file mode 100644 index 0000000000..e087212f1b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml @@ -0,0 +1,18 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - false + - falsee + - true + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml new file mode 100644 index 0000000000..3923ee18d7 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml @@ -0,0 +1,19 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_property: + type: map + description : another description + default: + - 10.5 + - 10.6x + - 20.5 + - 30.5 + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml new file mode 100644 index 0000000000..ed8ea4d70c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_boolean: + type: koko + description : another description + default: + - false + - true + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml new file mode 100644 index 0000000000..dfc564b458 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyFatherCompute: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml new file mode 100644 index 0000000000..533333ee09 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml @@ -0,0 +1,26 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + capabilities: + host: + type: tosca.capabilities.Container + endpoint : + type: tosca.capabilities.Endpoint.Admin + OS: + type: tosca.capabilities.OperatingSystem + BINDING: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml new file mode 100644 index 0000000000..9d8b2d8375 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml @@ -0,0 +1,23 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - LOCAL_STORAGE: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, 1] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml new file mode 100644 index 0000000000..a5413e516f --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml @@ -0,0 +1,23 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute2: + derived_from: org.openecomp.resource.MyCompute1 + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - LOCAL_STORAGE: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, 2] \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml new file mode 100644 index 0000000000..9cea0b9dc8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vfc.vfc3: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + occurrences: [1, 1] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml new file mode 100644 index 0000000000..24efc27711 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vfc.vfc2: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, 1] + capabilities: + host: + type: tosca.capabilities.Container + occurrences: [1, UNBOUNDED] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml new file mode 100644 index 0000000000..237bec1f0c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.DerivedFromMyCompute: + derived_from: org.openecomp.resource.MyCompute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml new file mode 100644 index 0000000000..0679bff4b1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml @@ -0,0 +1,15 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyWebApp: + derived_from: tosca.nodes.WebApplication + properties: + context_root: + type: string + capabilities: + app_endpoint: + type: tosca.capabilities.Endpoint.Admin #derived from WebApplication's tosca.capabilities.Endpoint "app_endpoint" + requirements: + - host: + capability: tosca.capabilities.Container.Docker #derived from WebApplication's tosca.capabilities.Container "host" + node: tosca.nodes.WebServer + relationship: tosca.relationships.HostedOn diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml new file mode 100644 index 0000000000..0fa9a302f2 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml @@ -0,0 +1,53 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyComputeTest: + derived_from: tosca.nodes.Root + properties: + myProp: + type: tosca.datatypes.Credential + descritpion: hey Desc + default: + "protocol" : hey1 + "token_type" : hey2 + "token" : hey3 + "keys" : {"keyA" : "val1" , keyB : val2} + "user" : hey4 + attributes: + private_address: + type: string + status: supported + default: myDefault + public_address: + type: string + networks: + type: map + default: {keyA : val1 , keyB : val2} + entry_schema: + type: string + ports: + type: tosca.datatypes.Credential + description: this is my description + default: + "protocol" : hey1 + "token_type" : hey2 + "token" : hey3 + "keys" : {"keyA" : "val1" , keyB : val2} + "user" : hey4 + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml new file mode 100644 index 0000000000..4d6db6c8c0 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + Binding: #"binding" exists on parent + type: tosca.capabilities.OperatingSystem diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml new file mode 100644 index 0000000000..fcc3952f94 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml @@ -0,0 +1,42 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + - LOCAL_Storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + Scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml new file mode 100644 index 0000000000..7cab3ac590 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml @@ -0,0 +1,40 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + - LOCAL_Storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml new file mode 100644 index 0000000000..a3ff088a35 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.TestResource: + derived_from: tosca.nodes.Root + properties: + my_prop: + type: list + description : another description + default: + - 12 + - true + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml new file mode 100644 index 0000000000..2f864a727e --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_prop: + type: list + description : another description + default: + - false + - true + entry_schema: + description: This is my property + type: string + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml new file mode 100644 index 0000000000..fd52df5f9b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml @@ -0,0 +1,198 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + my_boolean: + type: list + description : another description + default: + - false + - true + entry_schema: + description: This is my property + type: boolean + my_boolean_array: + type: list + description : another description + default: [ true , false ] + entry_schema: + description: This is my property + type: boolean + duplicate_boolean_values: + type: list + description : another description + default: [ true , false , true ] + entry_schema: + description: This is my property + type: boolean + boolean_null_value: + type: list + description : another description + default: + - true + - + - false + entry_schema: + description: This is my property + type: boolean + my_integers: + type: list + description : another description + default: + - 0 + - 1000 + - -1000 + - 50 + entry_schema: + description: This is my property + type: integer + my_integers_array: + type: list + description : another description + default: [ 10 , -1000, 0 ] + entry_schema: + description: This is my property + type: integer + duplicate_integers_values: + type: list + description : another description + default: [ 10 , 10, -1000, 0 ] + entry_schema: + description: This is my property + type: integer + integer_null_value: + type: list + description : another description + default: + - 1000 + - + - 2000 + entry_schema: + description: This is my property + type: integer + my_string: + type: list + description : another description + default: + - asdc + - $?^@ecomp$!#%()_-~@+*^...;;/w# + - uc + entry_schema: + description: This is my property + type: string + my_string_array: + type: list + description : another description + default: [ AAA, ~$~#bbb%^*_-, qwe , 1.3 , 500 , true ] + entry_schema: + description: This is my property + type: string + string_null_value: + type: list + description : another description + default: + - asdc + - + - uc + entry_schema: + description: This is my property + type: string + string_space_value: + type: list + description : another description + default: + - asdc + - + - uc + entry_schema: + description: This is my property + type: string + duplicate_string_values: + type: list + description : another description + default: + - asdc + - asdc + - uc + entry_schema: + description: This is my property + type: string + my_float: + type: list + description : another description + default: + - 6 + - 1000.000001 + - -3.0f + entry_schema: + description: This is my property + type: float + my_float_array: + type: list + description : another description + default: [ 0.01 , -5.0 , 2.1f ] + entry_schema: + description: This is my property + type: float + duplicate_float_values: + type: list + description : another description + default: + - 0.0 + - 0.0 + - 4.555555 + entry_schema: + description: This is my property + type: float + float_no_default_values: + type: list + description : another description + default: + entry_schema: + description: This is my property + type: float + float_null_value: + type: list + description : another description + default: + - 6 + - + - -3.0f + entry_schema: + description: This is my property + type: float + float_space_value: + type: list + description : another description + default: + - 6 + - + - -3.0f + entry_schema: + description: This is my property + type: float + integer_no_default_values: + type: list + description : another description + default: + entry_schema: + description: This is my property + type: integer + string_no_default_values: + type: list + description : another description + default: + entry_schema: + description: This is my property + type: string + boolean_no_default_values: + type: list + description : another description + default: + entry_schema: + description: This is my property + type: boolean + capabilities: + link: + type: tosca.capabilities.network.Linkable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml new file mode 100644 index 0000000000..f856603397 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml @@ -0,0 +1,452 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + string_prop01: + type: map + description : another description + default: {keyA : val1 , keyB : val2} + entry_schema: + description: This is my property + type: string + string_prop02: + type: map + description : another description + default: {keyA : "val1" , keyB : "val2"} + entry_schema: + description: This is my property + type: string + string_prop03: + type: map + description : another description + default: {"keyA" : "val1" , keyB : val2} + entry_schema: + description: This is my property + type: string + string_prop04: + type: map + description : another description + default: {"keyA" : 10 , keyB : true } + entry_schema: + description: This is my property + type: string + string_prop05: + type: map + description : another description + default: {"keyA" : , keyB : "Big" } + entry_schema: + description: This is my property + type: string + string_prop06: + type: map + description : another description + default: {"keyA" : aaaA , keyB : null } + entry_schema: + description: This is my property + type: string + string_prop07: + type: map + description : another description + default: {"keyA" : NULL , keyB : Null } + entry_schema: + description: This is my property + type: string + string_prop08: + type: map + description : another description + default: {"keyA" : "" , keyB : "abcd" } + entry_schema: + description: This is my property + type: string + string_prop09: + type: map + description : another description + default: {"keyA" : " " , keyB : "abcd" } + entry_schema: + description: This is my property + type: string + string_prop10: + type: map + description : another description + default: {"keyA" : " aaaa" , keyB : " bbbb" } + entry_schema: + description: This is my property + type: string + string_prop11: + type: map + description : another description + default: {"keyA" : "aaaa " , keyB : "bbbb " } + entry_schema: + description: This is my property + type: string + string_prop12: + type: map + description : another description + default: {"keyA" : " aaaa " , keyB : " bbbb ccccc " } + entry_schema: + description: This is my property + type: string + string_prop13: + type: map + description : another description + default: + keyA : "aaaa" + entry_schema: + description: This is my property + type: string + string_prop14: + type: map + description : another description + default: + keyA : " aaaa " + entry_schema: + description: This is my property + type: string + string_prop15: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop16: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop17: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop18: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop19: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop20: + type: map + description : another description + default: + keyA : aaaa + keya : aaaa + Keya : Aaaa + KEYA : nnnn + entry_schema: + description: This is my property + type: string + string_prop21: + type: map + description : another description + default: + keyA : NULL + keyB : null + keyC : Null + entry_schema: + description: This is my property + type: string + string_prop22: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: string + integer_prop01: + type: map + description : another description + default: {keyA : 1 , keyB : 1000} + entry_schema: + description: This is my property + type: integer + integer_prop02: + type: map + description : another description + default: {keyA : Null , keyB : NULL ,keyC : null } + entry_schema: + description: This is my property + type: integer + integer_prop03: + type: map + description : another description + default: {keyA : , keyB : -600} + entry_schema: + description: This is my property + type: integer + integer_prop03: + type: map + description : another description + default: {keyA : 800 , keyB : -600} + entry_schema: + description: This is my property + type: integer + integer_prop04: + type: map + description : another description + default: {keyA : , keyB : -600} + entry_schema: + description: This is my property + type: integer + integer_prop05: + type: map + description : another description + default: {keyA : 100 , keyB : 0 } + entry_schema: + description: This is my property + type: integer + integer_prop06: + type: map + description : another description + default: {keyA : 100 , keyB : 00} + entry_schema: + description: This is my property + type: integer + integer_prop07: + type: map + description : another description + default: {keyA : 100 , keyB : 100 } + entry_schema: + description: This is my property + type: integer + integer_prop08: + type: map + description : another description + default: + keyA : 100 + keyB : 200 + entry_schema: + description: This is my property + type: integer + integer_prop09: + type: map + description : another description + default: + keyA : 100 + keyB : 200 + entry_schema: + description: This is my property + type: integer + integer_prop10: + type: map + description : another description + default: + keyA : null + keyA : Null + keyB : 1111 + keyB : 2222 + entry_schema: + description: This is my property + type: integer + integer_prop11: + type: map + description : another description + default: + keyA : null + keyB : Null + keyC : NULL + keyD : + entry_schema: + description: This is my property + type: integer + integer_prop12: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: integer + integer_prop13: + type: map + description : another description + default: {keyA : 100 , keyA : 200} + entry_schema: + description: This is my property + type: integer + boolean_prop01: + type: map + description : another description + default: {keyA : true , keyB : false , keyC : false } + entry_schema: + description: This is my property + type: boolean + boolean_prop02: + type: map + description : another description + default: {keyA : TRUE , keyB : FALSE , keyC : False } + entry_schema: + description: This is my property + type: boolean + boolean_prop03: + type: map + description : another description + default: + keyA : null + keyB : Null + keyC : NULL + keyD : + entry_schema: + description: This is my property + type: boolean + boolean_prop04: + type: map + description : another description + default: {keyA : Null , keyB : NULL ,keyC : null ,keyD : } + entry_schema: + description: This is my property + type: boolean + boolean_prop05: + type: map + description : another description + default: {keyA : true , keyB : false , keyC : false } + entry_schema: + description: This is my property + type: boolean + boolean_prop06: + type: map + description : another description + default: + keyA : true + keyB : true + keyC : false + entry_schema: + description: This is my property + type: boolean + boolean_prop07: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: boolean + boolean_prop08: + type: map + description : another description + default: + keyA : false + keyA : true + keyB : true + keyB : false + entry_schema: + description: This is my property + type: boolean + boolean_prop09: + type: map + description : another description + default: {keyA : true,keyA : false,keyB : false,keyB : true} + entry_schema: + description: This is my property + type: boolean + float_prop01: + type: map + description : another description + default: {keyA : 1.20 , keyB : 3.56f , keyC : 33} + entry_schema: + description: This is my property + type: float + float_prop02: + type: map + description : another description + default: {keyA : 0.00, keyB : 0.0 , keyC : 0 } + entry_schema: + description: This is my property + type: float + float_prop03: + type: map + description : another description + default: {keyA : null, keyB : Null , keyC : NULL , keyD : } + entry_schema: + description: This is my property + type: float + float_prop04: + type: map + description : another description + default: {keyA : 1.20 , keyB : 3.56f , keyC : 33 } + entry_schema: + description: This is my property + type: float + float_prop05: + type: map + description : another description + default: + keyA : 33 + keyB : 1.2000 + keyC : 3.607f + keyD : 0 + entry_schema: + description: This is my property + type: float + float_prop06: + type: map + description : another description + default: + keyA : 33 + keyB : 1.2000 + keyC : 3.607f + entry_schema: + description: This is my property + type: float + float_prop07: + type: map + description : another description + default: + keyA : null + keyB : Null + keyC : NULL + keyD : + entry_schema: + description: This is my property + type: float + float_prop08: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: float + float_prop09: + type: map + description : another description + default: + keyA : 3.5 + keyA : 0.01 + keyB : 3.6 + keyB : + entry_schema: + description: This is my property + type: float + float_prop10: + type: map + description : another description + default: {keyA : 0.0002} + entry_schema: + description: This is my property + type: float + float_prop11: + type: map + description : another description + default: {keyA : 0.000 , keyA : 003.56f, keyB : 33} + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml new file mode 100644 index 0000000000..e4d626fca6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - Local_Storage: + capability: tosca.capabilities.Endpoint + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml new file mode 100644 index 0000000000..7ae9552d6a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute2: + derived_from: org.openecomp.resource.MyCompute1 + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - Local_Storage: + capability: tosca.capabilities.Endpoint + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml new file mode 100644 index 0000000000..301116c985 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml @@ -0,0 +1,37 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +description: Template for vSCP -- connectable to OCS-FW -- temporary model for 1602 demo + +############################ +# The model capture four sub-components (VDUs) and their connectivity to six +# networks. +############################ + +node_types: + +#The node type for vSCP +#used for substitution mapping, or to describe vSCP resource in ASDC studio + org.openecomp.resource.vSCP-03-16: + derived_from: tosca.nodes.Root + requirements: + - sigtran_connection1: + capability: tosca.capabilities.Node + - sigtran_connection2: + capability: tosca.capabilities.Node + - ocs_connection: + capability: tosca.capabilities.Node + - oam_connection: + capability: tosca.capabilities.Node + - firewall: + capability: tosca.capabilities.Node + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: org.openecomp.capabilities.networkInterfaceNotFound \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml new file mode 100644 index 0000000000..d100dafdf9 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml @@ -0,0 +1,25 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +description: Template for vSCP -- connectable to OCS-FW -- temporary model for 1602 demo + +############################ +# The model capture four sub-components (VDUs) and their connectivity to six +# networks. +############################ + +node_types: + +#The node type for vSCP +#used for substitution mapping, or to describe vSCP resource in ASDC studio + org.openecomp.resource.vSCP-03-16: + derived_from: tosca.nodes.Root + requirements: + - sigtran_connection1: + capability: org.openecomp.capabilities.networkInterfaceNotFound + - sigtran_connection2: + capability: tosca.capabilities.Node + - ocs_connection: + capability: tosca.capabilities.Node + - oam_connection: + capability: tosca.capabilities.Node + - firewall: + capability: tosca.capabilities.Node \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml new file mode 100644 index 0000000000..cc5b202bc7 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyChildCompute: + derived_from: org.openecomp.resource.MyFatherCompute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml new file mode 100644 index 0000000000..b7859d4c14 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml @@ -0,0 +1,15 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyChildWebApp: + derived_from: org.openecomp.resource.MyWebApp + properties: + context_root: + type: string + capabilities: + app_endpoint: + type: tosca.capabilities.Endpoint + requirements: + - host: + capability: tosca.capabilities.Container + node: tosca.nodes.WebServer + relationship: tosca.relationships.HostedOn \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml new file mode 100644 index 0000000000..98bf9b7902 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml new file mode 100644 index 0000000000..2b2807395a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.RootNotExists + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml new file mode 100644 index 0000000000..2fa3ad0c08 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: toscaSimpleYaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml new file mode 100644 index 0000000000..d1a613fff2 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource2.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml new file mode 100644 index 0000000000..8084d049db --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml @@ -0,0 +1,34 @@ +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml new file mode 100644 index 0000000000..40ae610c06 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml @@ -0,0 +1,77 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, UNBOUNDED] + - local_storage200: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, 1] + - local_storage300: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, 10] + - local_storage400: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, 10000000] + - local_storage500: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [2, 3] + - local_storageNoOccurrences600: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpointNoOccurrence : + type: tosca.capabilities.Endpoint.Admin + endpoint200 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [1, 2] + endpoint300 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [1, 1] + endpoint400 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [1, 10] + endpoint500 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [1, 10000000] + endpoint600 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [1, UNBOUNDED ] + endpoint700 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [2, 4 ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml new file mode 100644 index 0000000000..b243add14a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requiremens: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilitis: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml new file mode 100644 index 0000000000..43d92d1681 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml @@ -0,0 +1,34 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute1: + derived_from: tosca.nodes.Compute + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - Local_Storage: #"local_storage" exists on parent + capability: tosca.capabilities.Endpoint + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml new file mode 100644 index 0000000000..90e771dab1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.VF.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml new file mode 100644 index 0000000000..73b201eab4 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml @@ -0,0 +1,42 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable + + org.openecomp.resource.example.TransactionSubsystem: + derived_from: tosca.nodes.Root + capabilities: + message_receiver: tosca.capabilities.Endpoint + requirements: + - database_endpoint: tosca.capabilities.Endpoint.Database \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml new file mode 100644 index 0000000000..c451eb2514 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml @@ -0,0 +1,44 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +topology_template: + description: Template of an application connecting to a database. + + node_templates: + web_app: + type: tosca.nodes.WebApplication.MyWebApp + requirements: + - host: web_server + - database_endpoint: db +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml new file mode 100644 index 0000000000..43a9a174f8 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml @@ -0,0 +1,16 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyWebApp: + derived_from: tosca.nodes.WebApplication + properties: + context_root: + type: string + capabilities: + app_endpoint: + type: tosca.capabilities.Endpoint + requirements: + - HOSt: + capability: tosca.capabilities.Container.Docker + node: tosca.nodes.WebServer + relationship: tosca.relationships.HostedOn + occurrences: [ 1, 2 ] diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml new file mode 100644 index 0000000000..7c796d2801 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.MyLink: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml new file mode 100644 index 0000000000..ff255f2394 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.cp.MyPort: + derived_from: org.openecomp.resource.cp.Port + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.network.Bindable + node: org.openecomp.resource.vl.MyLink + relationship: tosca.relationships.BindTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/noContent.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/noContent.yml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml new file mode 100644 index 0000000000..f007a0fed2 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [2, 0] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml new file mode 100644 index 0000000000..0487b63cb3 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [-1, 2] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml new file mode 100644 index 0000000000..7afdffa59d --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [1, -2] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml new file mode 100644 index 0000000000..f8a582f401 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ , 2] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml new file mode 100644 index 0000000000..f1c6a93e1f --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ 1, ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml new file mode 100644 index 0000000000..b0ef54b0eb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ 0 , 0 ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml new file mode 100644 index 0000000000..afd999f575 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ @ , 1 ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml new file mode 100644 index 0000000000..60efc99273 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ 1.0 , 2.0 ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml new file mode 100644 index 0000000000..d6ec7eabe6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ "1" , "2" ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml new file mode 100644 index 0000000000..27de429186 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml new file mode 100644 index 0000000000..5bdae3a5f5 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [ UNBOUNDED , UNBOUNDED ] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml new file mode 100644 index 0000000000..8c3034afce --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ 2, 1] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml new file mode 100644 index 0000000000..4b5eba9110 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ -1, 2] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml new file mode 100644 index 0000000000..9c42e22aa1 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ 1, -2] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml new file mode 100644 index 0000000000..49953b5834 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ , 2] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml new file mode 100644 index 0000000000..8d8985d7f7 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ 1 , ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml new file mode 100644 index 0000000000..12944507f6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ 0 , 0 ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml new file mode 100644 index 0000000000..618c980e16 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ 0 , # ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml new file mode 100644 index 0000000000..d0c4575c83 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ 1.0 , 2.0 ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml new file mode 100644 index 0000000000..024338d380 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ "1" , "2" ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml new file mode 100644 index 0000000000..a4a32ba772 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml new file mode 100644 index 0000000000..c3024a3ee4 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyCompute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage100: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint100 : + type: tosca.capabilities.Endpoint.Admin + occurrences: [ UNBOUNDED, UNBOUNDED ] + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml new file mode 100644 index 0000000000..b9bda183e6 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vfc.vfc4: + derived_from: tosca.nodes.Root + properties: + # domain-specific software component version + component_version: + type: version + required: false + admin_credential: + type: tosca.datatypes.Credential + required: false + requirements: + - host: + capability: tosca.capabilities.Container + relationship: tosca.relationships.HostedOn + occurrences: [1, 1] diff --git a/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml new file mode 100644 index 0000000000..9676bcdb6c --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vfc.vfc1: + derived_from: tosca.nodes.Root + properties: + # domain-specific software component version + component_version: + type: version + required: false + admin_credential: + type: tosca.datatypes.Credential + required: false + requirements: + - host: + capability: tosca.capabilities.Container + relationship: tosca.relationships.HostedOn + occurrences: [1, 2] diff --git a/test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topology.txt b/test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topology.txt new file mode 100644 index 0000000000..f46af26605 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topology.txt @@ -0,0 +1 @@ +{"id":"c25811fc-e03f-401d-93ca-45d9bd312703","delegateId":"17710a88-f3d8-483d-aded-afee2906a8c1","delegateType":"topologytemplate","dependencies":[{"name":"tosca-normative-types-softwareComponent","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-webServer","version":"1.0.0.wd03-SNAPSHOT"},{"name":"apache-type","version":"2.0.0-SNAPSHOT"},{"name":"tosca-normative-types-compute","version":"1.0.0.wd03-SNAPSHOT"},{"name":"tosca-normative-types-root","version":"1.0.0.wd03-SNAPSHOT"}],"nodeTemplates":[{"key":"Compute_2","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}},{"key":"Apache","value":{"type":"alien.nodes.Apache","name":null,"properties":{"port":"80","document_root":"/var/www","version":"2.4"},"attributes":{"tosca_id":null,"tosca_name":null},"relationships":{"attachToCompute_2":{"type":"tosca.relationships.AttachTo","target":"Compute_2","requirementName":"dependency","requirementType":"tosca.capabilities.Root","targetedCapabilityName":"attach"}},"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"host":{"type":"tosca.nodes.Compute","properties":null}},"capabilities":{"secure_endpoint":{"type":"tosca.capabilities.Endpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"app_endpoint":{"type":"tosca.capabilities.Endpoint","properties":{"port":null,"protocol":{"value":"tcp","definition":false},"url_path":null,"secure":{"value":"false","definition":false}}},"host":{"type":"alien.capabilities.ApacheContainer","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null}},"artifacts":null}},{"key":"Compute","value":{"type":"tosca.nodes.Compute","name":null,"properties":{"disk_size":null,"num_cpus":null,"os_distribution":null,"os_arch":null,"mem_size":null,"os_type":null,"os_version":null},"attributes":{"ip_address":null,"tosca_id":null,"tosca_name":null},"relationships":null,"requirements":{"dependency":{"type":"tosca.capabilities.Root","properties":null},"network":{"type":"tosca.capabilities.Connectivity","properties":null}},"capabilities":{"host":{"type":"tosca.capabilities.Container","properties":{"valid_node_types":null}},"root":{"type":"tosca.capabilities.Root","properties":null},"attach":{"type":"tosca.capabilities.Attachment","properties":null},"scalable":{"type":"tosca.capabilities.Scalable","properties":{"max_intances":{"value":"1","definition":false},"default_instances":{"value":"1","definition":false},"min_intances":{"value":"1","definition":false}}}},"artifacts":null}}]} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt b/test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt new file mode 100644 index 0000000000..f3fdf0297b --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt @@ -0,0 +1 @@ +{"id":"17710a88-f3d8-483d-aded-afee2906a8c1","name":"MichaelTest2","description":null,"topologyId":"c25811fc-e03f-401d-93ca-45d9bd312703"} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml new file mode 100644 index 0000000000..b6faadd4f9 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: NO + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml new file mode 100644 index 0000000000..7fb2923b04 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: 0 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml new file mode 100644 index 0000000000..fd451aa3af --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: OFF + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml new file mode 100644 index 0000000000..a253e4c8d7 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: t + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml new file mode 100644 index 0000000000..ce273b3522 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: true + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml new file mode 100644 index 0000000000..4680eb6996 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: on + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml new file mode 100644 index 0000000000..1ed7781831 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: y + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml new file mode 100644 index 0000000000..c0b42e6288 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: yes + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml new file mode 100644 index 0000000000..24b862b751 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: 1 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml new file mode 100644 index 0000000000..7bad8efd6f --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: F + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml new file mode 100644 index 0000000000..8b35e2adf7 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: FALSE + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml new file mode 100644 index 0000000000..2768e0d480 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: N + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml new file mode 100644 index 0000000000..fc7f84ca81 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: number + description: city name + default: 12 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml new file mode 100644 index 0000000000..28ec3358be --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: number + description: city name + default: 12.12 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/uploadComponent/images/mysql.png b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/images/mysql.png new file mode 100644 index 0000000000..8e02f49b7b Binary files /dev/null and b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/images/mysql.png differ diff --git a/test-apis-ci/src/test/resources/CI/tests/uploadComponent/mysql.yml b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/mysql.yml new file mode 100644 index 0000000000..a2eb4d423a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/mysql.yml @@ -0,0 +1,85 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-uploadComponent +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-database:1.0.0.wd03-SNAPSHOT" + - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql-uploadComponent: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/install_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/install_mysql.sh new file mode 100644 index 0000000000..400bcf40cb --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/install_mysql.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Debian based MYSQL install 5..." +LOCK="/tmp/lockaptget" + +while true; do + if mkdir "${LOCK}" &>/dev/null; then + echo "MySQL take the lock" + break; + fi + echo "Waiting the end of one of our recipes..." + sleep 0.5 +done + +while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do + echo "Waiting for other software managers to finish..." + sleep 0.5 +done +sudo rm -f /var/lib/dpkg/lock + +sudo apt-get update || (sleep 15; sudo apt-get update || exit ${1}) +sudo DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-5.5 pwgen || exit ${1} +rm -rf "${LOCK}" + +sudo /etc/init.d/mysql stop +sudo rm -rf /var/lib/apt/lists/* +sudo rm -rf /var/lib/mysql/* +echo "MySQL Installation complete." \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/start_mysql.sh b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/start_mysql.sh new file mode 100644 index 0000000000..648bd45756 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/uploadComponent/scripts/start_mysql.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +echo "------------------------ ENV ------------------------" +echo "ENV VAR USED VOLUME_HOME : $VOLUME_HOME" +echo "ENV VAR USED PORT : $PORT" +echo "ENV VAR USED DB_NAME : $DB_NAME" +echo "ENV VAR USED DB_USER : $DB_USER" +echo "ENV VAR USED DB_PASSWORD : $DB_PASSWORD" +echo "---------------------------- ------------------------" + +CURRENT_PATH=`dirname "$0"` + +function StartMySQL { + echo "Starting MYSQL..." + sudo /etc/init.d/mysql stop + sudo /usr/bin/mysqld_safe > /dev/null 2>&1 & + RET=1 + while [[ RET -ne 0 ]]; do + echo "=> Waiting for confirmation of MySQL service startup" + sleep 5 + sudo mysql -uroot -e "status" > /dev/null 2>&1 + RET=$? + done +} + +function AllowFileSystemToMySQL { + MYSQL_DATA_DIR=$VOLUME_HOME/data + MYSQL_LOG=$VOLUME_HOME/logs + + echo "Setting data directory to $MYSQL_DATA_DIR an logs to $MYSQL_LOG ..." + if sudo test ! -d $MYSQL_DATA_DIR; then + echo "Creating DATA dir > $MYSQL_DATA_DIR ..." + sudo mkdir -p $MYSQL_DATA_DIR + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_DATA_DIR + fi + if sudo test ! -d $MYSQL_LOG; then + echo "Creating LOG dir > $MYSQL_LOG ..." + sudo mkdir -p $MYSQL_LOG + # mysql as owner and group owner + sudo chown -R mysql:mysql $MYSQL_LOG + fi + + # edit app mysql permission in : /etc/apparmor.d/usr.sbin.mysqld + COUNT_LINE=`sudo cat /etc/apparmor.d/usr.sbin.mysqld | wc -l` + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_DATA_DIR/** rwk," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/ r," /etc/apparmor.d/usr.sbin.mysqld + sudo sed -i "$(($COUNT_LINE)) i $MYSQL_LOG/** rwk," /etc/apparmor.d/usr.sbin.mysqld + + # reload app permission manager service + sudo service apparmor reload +} + +function UpdateMySQLConf { + echo "Updating MySQL conf files [DATA, LOGS]..." + sudo sed -i "s:/var/lib/mysql:$MYSQL_DATA_DIR:g" /etc/mysql/my.cnf + sudo sed -i "s:/var/log/mysql/error.log:$MYSQL_LOG/error.log:g" /etc/mysql/my.cnf + sudo sed -i "s:3306:$PORT:g" /etc/mysql/my.cnf + + if sudo test ! -f /usr/share/mysql/my-default.cnf; then + sudo cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf + fi + if sudo test ! -f /etc/mysql/conf.d/mysqld_charset.cnf; then + sudo cp $configs/mysqld_charset.cnf /etc/mysql/conf.d/mysqld_charset.cnf + fi + + if [ "$BIND_ADRESS" == "true" ]; then + sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf + fi +} + +function InitMySQLDb { + # create database DB_NAME + if [ "$DB_NAME" ]; then + echo "INIT DATABASE $DB_NAME" + sudo mysql -u root -e "CREATE DATABASE $DB_NAME"; + fi + + # create user and give rights + if [ "$DB_USER" ]; then + echo "CREATE USER $DB_USER WITH PASSWORD $DB_PASSWORD AND GRAND RIGHTS ON $DB_NAME" + sudo mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '$DB_PASSWORD'" + sudo mysql -uroot -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%' WITH GRANT OPTION" + sudo mysql -uroot -e "FLUSH PRIVILEGES" + fi +} + +# Create a new database path to the attched volume +if sudo test ! -d $VOLUME_HOME/data; then + echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME/data" + AllowFileSystemToMySQL + UpdateMySQLConf + echo "=> Init new database path to $MYSQL_DATA_DIR" + sudo mysql_install_db --basedir=/usr --datadir=$MYSQL_DATA_DIR + echo "=> MySQL database initialized !" +else + echo "=> Using an existing volume of MySQL" + AllowFileSystemToMySQL + UpdateMySQLConf +fi + +# Finally start MySQL with new configuration +StartMySQL +InitMySQLDb \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml new file mode 100644 index 0000000000..764b8d4c58 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: number123 + description: city name + default: 12.12 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml new file mode 100644 index 0000000000..19119f3d9a --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: K + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml new file mode 100644 index 0000000000..f9c09a4fed --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: boolean + description: city name + default: 11 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml new file mode 100644 index 0000000000..9a489879cc --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: number + description: city name + default: 1.2Noo + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml new file mode 100644 index 0000000000..4c0e07affc --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: number + description: city name + default: 1 2 3 + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml new file mode 100644 index 0000000000..f52ef04712 --- /dev/null +++ b/test-apis-ci/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml @@ -0,0 +1,140 @@ +heat_template_version: 2013-05-23 +################################# +# +# Changes in v0.2: +# - Unique availability zone for each VM +# - LAN8 and SLAN networks removed according to latest Prod/Type I diagram +# - 2 DB VMs added +# - Images corrected +# - VM start-up order: SMP->DB->BE->FE (no error handling yet) +# - Provisioning scripts placeholders +# +################################# + +description: ASC Template + +parameters: + city_name: + type: string + description: city name + default: שלום + address: + type: string + description: address + default: Alonim + home_number: + type: number + description: home_number + default: 8 +resources: +# scp_be_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_be_wait_handle } +# count: 5 +# timeout: 300 +# scp_be_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# scp_fe_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: scp_fe_wait_handle } +# count: 2 +# timeout: 300 +# scp_fe_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# smp_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: smp_wait_handle } +# count: 2 +# timeout: 300 +# smp_wait_handle: +# type: OS::Heat::WaitConditionHandle +# +# db_wait_condition: +# type: OS::Heat::WaitCondition +# properties: +# handle: { get_resource: db_wait_handle } +# count: 2 +# timeout: 300 +# db_wait_handle: +# type: OS::Heat::WaitConditionHandle + + FE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + BE_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + SMP_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + DB_Affinity: + type: OS::Nova::ServerGroup + properties: + policies: ["anti-affinity"] + + FE_Clustering_KA: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_fe_cluster_net_id } + + FE_Clustering_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: FE_Clustering_KA } + cidr: { get_param: int_vscp_fe_cluster_cidr } + + Clustering_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_cluster_net_id } + + Clustering_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: Clustering_Network } + cidr: { get_param: int_vscp_cluster_cidr } + + DB_Network: + type: OS::Contrail::VirtualNetwork + properties: + name: { get_param: int_vscp_db_network_net_id } + + DB_Network_subnet: + type: OS::Neutron::Subnet + properties: + network_id: { get_resource: DB_Network } + cidr: { get_param: int_vscp_db_network_cidr } + + server_scp_be0: + type: OS::Nova::Server +# depends on: db_wait_condition + properties: + name: { get_param: vm_scp_be0_name } + image: { get_param: image_scp_be_id } +# availability_zone: { get_param: availability_zone_be0 } + flavor: { get_param: flavor_scp_be_id } + scheduler_hints: { group: { get_resource: BE_Affinity } } + networks: + - port: { get_resource: be0_port_3 } + - port: { get_resource: be0_port_4 } + - port: { get_resource: be0_port_5 } + - port: { get_resource: be0_port_7 } + metadata: + vnf_id: { get_param: vnf_id } + user_data: + str_replace: + template: | + #!/bin/bash + #todo: provision $vm_name + wc_notify --data-binary '{"status": "SUCCESS"}' + params: + $vm_name: {get_param: vm_scp_be0_name} +# wc_notify: { get_attr: ['scp_be_wait_handle', 'curl_cli'] } diff --git a/test-apis-ci/src/test/resources/config.json b/test-apis-ci/src/test/resources/config.json new file mode 100644 index 0000000000..71c9d35e59 --- /dev/null +++ b/test-apis-ci/src/test/resources/config.json @@ -0,0 +1,12 @@ +{ + +catalogBeHost: behost, +catalogFeHost: fehost, +esHost: eshost, +catalogFePort: 8080, +catalogBePort: 8080, +esPort: 9200, +resourceConfigDir: "src/test/resources/CI/tests", +componentsConfigDir: "src/test/resources/CI/components" + +} \ No newline at end of file diff --git a/test-apis-ci/src/test/resources/logback-test.xml b/test-apis-ci/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..03ce9d1243 --- /dev/null +++ b/test-apis-ci/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/test-apis-ci/testng.xml b/test-apis-ci/testng.xml new file mode 100644 index 0000000000..8a47ef6d62 --- /dev/null +++ b/test-apis-ci/testng.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/test-apis-ci/testngLifeCycle.xml b/test-apis-ci/testngLifeCycle.xml new file mode 100644 index 0000000000..aa390dc213 --- /dev/null +++ b/test-apis-ci/testngLifeCycle.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-apis-ci/tmpCSAR b/test-apis-ci/tmpCSAR new file mode 100644 index 0000000000..c1d56528af Binary files /dev/null and b/test-apis-ci/tmpCSAR differ diff --git a/ui-ci-dev/.gitignore b/ui-ci-dev/.gitignore new file mode 100644 index 0000000000..6405eb7c05 --- /dev/null +++ b/ui-ci-dev/.gitignore @@ -0,0 +1,2 @@ +/bin/ +test-output/ \ No newline at end of file diff --git a/ui-ci-dev/pom.xml b/ui-ci-dev/pom.xml new file mode 100644 index 0000000000..f0ead6de8a --- /dev/null +++ b/ui-ci-dev/pom.xml @@ -0,0 +1,287 @@ + + 4.0.0 + + org.openecomp.sdc + sdc-main + + 1.1.0-SNAPSHOT + + ui-ci-dev + Selenium tests for the SDnC Application + + + + + + com.google.guava + guava + ${guava.version} + compile + + + org.seleniumhq.selenium + selenium-java + 3.0.1 + + + + org.seleniumhq.selenium + selenium-server + 2.48.2 + runtime + + + + org.openecomp.sdc + asdc-tests + ${asdc-tests.version} + + + + org.yaml + snakeyaml + ${snakeyaml.version} + compile + + + + com.google.code.gson + gson + ${gson.version} + compile + + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + compile + + + + org.apache.httpcomponents + httpmime + ${httpclient.version} + compile + + + + commons-io + commons-io + 1.3.2 + compile + + + + commons-logging + commons-logging + ${commons-logging} + compile + + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + compile + + + + + com.thinkaurelius.titan + titan-core + ${titan.version} + compile + + + + com.thinkaurelius.titan + titan-cassandra + ${titan.version} + compile + + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.2 + compile + + + + com.fasterxml.jackson.core + jackson-databind + 2.3.1 + compile + + + + com.fasterxml.jackson.core + jackson-core + 2.3.1 + compile + + + + org.openecomp.sdc + sdc-distribution-client + 1.1.3 + + + + junit + junit + ${junit.version} + compile + + + + org.testng + testng + ${testng.version} + compile + + + + xml-apis + xml-apis + 1.4.01 + compile + + + + com.googlecode.json-simple + json-simple + ${json-simple.version} + compile + + + + com.relevantcodes + extentreports + 1.4 + + + + org.apache.commons + commons-jci-core + ${commons-jci-core.version} + compile + + + + org.sikuli + sikuli-api + 1.2.0 + + + + org.sikuli + sikuli-core + 1.2.2 + + + + + + commons-codec + commons-codec + ${commons-codec} + compile + + + + + + + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-1 + false + + + + ui-ci-dev + initialize + + read-project-properties + + + + + ../target/FullReleaseVersion.properties + + + + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.5.5 + + + create.jar.with.dependencies + package + + single + + + + + org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest + + + + jar-with-dependencies + + + + + + + + + + + + + + + + + + + + + + + + + + + com.fortify.ps.maven.plugin + sca-maven-plugin + 4.30 + + false + + + + + diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/scripts/CreateVfsFromOnboarding.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/scripts/CreateVfsFromOnboarding.java new file mode 100644 index 0000000000..b11f8d19ef --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/scripts/CreateVfsFromOnboarding.java @@ -0,0 +1,67 @@ +package org.openecomp.sdc.uici.scripts; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.openecomp.sdc.uici.tests.datatypes.CleanTypeEnum; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.OnboardUtility; + +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; +import com.google.gson.GsonBuilder; + +/** + * This Class functions to load mass zip files to vfs through onboarding.
+ * It uses both BE & UI APIs + * + * @author mshitrit + * + */ +public class CreateVfsFromOnboarding extends SetupCDTest { + public static void main(String[] args) { + CreateVfsFromOnboarding manager = new CreateVfsFromOnboarding(); + + FunctionalInterfaces.swallowException(() -> manager.setEnvParameters(CleanTypeEnum.NONE.name())); + // String folderPath = args[0]; + String folderPath = "C:\\onboardingTest\\onBoardingZips"; + File folder = new File(folderPath); + File[] listOfFiles = folder.listFiles(); + List zipFileNames = Arrays.asList(listOfFiles).stream().map(file -> file.getName()) + .filter(fileName -> fileName.endsWith(".zip")).collect(Collectors.toList()); + Map filesSuccessMap = new HashMap<>(); + for (String fileName : zipFileNames) { + try { + // Before + manager.beforeState(null); + manager.setBrowserBeforeTest(); + createSingleVfFromOnboarding(folderPath, fileName); + filesSuccessMap.put(fileName, "SUCCESS"); + + } catch (Exception e) { + filesSuccessMap.put(fileName, "FAIL"); + } finally { + FunctionalInterfaces.swallowException(() -> manager.afterState(null)); + manager.quitAfterTest(); + } + } + Path file = Paths.get("RunResults.txt"); + String stringDataModel = new GsonBuilder().setPrettyPrinting().create().toJson(filesSuccessMap); + FunctionalInterfaces.swallowException(() -> Files.write(file, stringDataModel.getBytes())); + } + + private static void createSingleVfFromOnboarding(String filePath, String zipFileName) { + String userId = UserRoleEnum.DESIGNER.getUserId(); + OnboardUtility.createVfFromOnboarding(userId, zipFileName, filePath); + GeneralUIUtils.submitForTestingElement("Vf From Onboarding"); + + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasElement.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasElement.java new file mode 100644 index 0000000000..c23d05ab23 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasElement.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +import org.apache.commons.lang3.tuple.ImmutablePair; + +public final class CanvasElement { + private final String uniqueId; + private ImmutablePair location; + private String elementName; + + public String getElementName() { + return elementName; + } + + public CanvasElement(String uniqueId, String elementName, ImmutablePair location) { + super(); + this.uniqueId = uniqueId; + this.location = location; + this.elementName = elementName; + } + + public String getUniqueId() { + return uniqueId; + } + + public ImmutablePair getLocation() { + return location; + } + + public void setLocation(ImmutablePair location) { + this.location = location; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasManager.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasManager.java new file mode 100644 index 0000000000..5ef8c7a56a --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasManager.java @@ -0,0 +1,206 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; + +public final class CanvasManager { + private Map canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_ELEMENT_Y_OFFSET = 40; + private static final int CANVAS_ELEMENT_X_OFFSET = 21; // 14 - 27 + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair newLocation) { + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.sleep(500); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveElementOnCanvas(CanvasElement canvasElement) { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.waitForLoader(); + } + + public void selectElementFromCanvas(CanvasElement canvasElement) { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.waitForLoader(); + } + + public CanvasElement createElementOnCanvas(LeftPanelCanvasItems canvasItem) { + return createElementOnCanvas(canvasItem.getValue(), false); + } + + /** + * Creates Element on the Canvas - use the element name. + * + * @param elementName + * @return + */ + public CanvasElement createElementOnCanvas(String elementName) { + return createElementOnCanvas(elementName, true); + } + + private CanvasElement createElementOnCanvas(String elementName, boolean addPrefix) { + if (addPrefix) { + elementName = DataTestIdEnum.LEFT_PANEL_PREFIX + elementName; + } + GeneralUIUtils.waitForLoader(); + WebElement element = GeneralUIUtils.getWebElementWaitForVisible(elementName); + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(element, 0, 0); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + + String uniqueId = elementName + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, elementName, freePosition); + addCanvasElement(canvasElement); + GeneralUIUtils.waitForLoader(); + return canvasElement; + } + + public CanvasElement createUniqueVFOnCanvas(LeftPanelCanvasItems canvasItem) { + GeneralUIUtils.waitForLoader(); + WebElement element = GeneralUIUtils.getWebElementWaitForVisible(canvasItem.getValue()); + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(element, 0, 0); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + + String uniqueId = canvasItem.name() + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, canvasItem.getValue(), freePosition); + addCanvasElement(canvasElement); + GeneralUIUtils.waitForLoader(); + return canvasElement; + } + + private ImmutablePair getFreePosition() { + // TODO ui-ci use better method + ImmutablePair randomPosition = null; + boolean freePosition = false; + int minSpace = 150; + while (!freePosition) { + ImmutablePair tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair getRandomPosition() { + int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair(xElement, yElement); + } + + /** + * Links two elements on canvas.
+ * Currently Supports Only elements in the default size.
+ * Will not work for container type or smaller elements (cp, vl etc...)
+ * + * @param firstElement + * @param secondElement + */ + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) { + GeneralUIUtils.waitForLoader(); + drawSimpleLink(firstElement, secondElement); + selectReqAndCapAndConnect(); + + GeneralUIUtils.waitForLoader(); + + } + + private void selectReqAndCapAndConnect() { + // Select First Cap + GeneralUIUtils.getWebElementsListWaitForVisible(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0) + .click(); + // Select First Req + GeneralUIUtils.getWebElementsListWaitForVisible(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0) + .click(); + // Connect + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click(); + + } + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) { + + int yOffset = CANVAS_ELEMENT_Y_OFFSET; + int xOffset = CANVAS_ELEMENT_X_OFFSET; + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, + secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + GeneralUIUtils.waitForLoader(); + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CleanTypeEnum.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CleanTypeEnum.java new file mode 100644 index 0000000000..f0691b89fc --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CleanTypeEnum.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +import java.util.Arrays; +import java.util.Optional; + +/** + * enum that represents possible methods to clean DB before and after tests. + * + * @author mshitrit + * + */ +public enum CleanTypeEnum { + FULL, + /** Unreliable should be only used in dev **/ + PARTIAL, NONE; + + /** + * Returns CleanType enum by it name + * + * @param cleanType + * @return + */ + public static CleanTypeEnum findByName(String cleanType) { + final Optional findAny = Arrays.asList(CleanTypeEnum.values()).stream() + .filter(e -> e.name().equals(cleanType)).findAny(); + return findAny.get(); + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndImportButtonsEnum.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndImportButtonsEnum.java new file mode 100644 index 0000000000..382584a48d --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndImportButtonsEnum.java @@ -0,0 +1,7 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +public enum CreateAndImportButtonsEnum { + + IMPORT_VF, IMPORT_VFC, IMPORT_CP, IMPORT_VL, CREATE_VF, CREATE_SERVICE, CREATE_PRODUCT; + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndUpdateStepsEnum.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndUpdateStepsEnum.java new file mode 100644 index 0000000000..454affe528 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndUpdateStepsEnum.java @@ -0,0 +1,25 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +public enum CreateAndUpdateStepsEnum { + GENERAL("Generalstep"), + ICON("Iconstep"), + DEPLOYMENT_ARTIFACT("Deployment Artifactstep"), + INFORMATION_ARTIFACT("Information Artifactstep"), + PROPERTIES("Propertiesstep"), + ATTRIBUTES("Attributesstep"), + COMPOSITION("Compositionstep"), + DEPLOYMENT("Deploymentstep"), + REQUIREMENTS_AND_CAPABILITIES("Req. & Capabilitiesstep"), + INPUTS("Inputsstep"); + + private String value; + + public String getValue() { + return value; + } + + private CreateAndUpdateStepsEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java new file mode 100644 index 0000000000..2eb838281d --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java @@ -0,0 +1,477 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +public final class DataTestIdEnum { + private DataTestIdEnum() { + }; + + public enum MainMenue { + HOME("main-menu-button-home"), + CATALOG("main-menu-button-catalog"); + private String value; + + public String getValue() { + return value; + } + + private MainMenue(String value) { + this.value = value; + } + } + + public enum Dashboard { + IMPORT_AREA("importButtonsArea"), + BUTTON_ADD_VF("createResourceButton"), + BUTTON_ADD_SERVICE("createServiceButton"), + IMPORT_VFC("importVFCbutton"), + IMPORT_VF("importVFbutton"), + IMPORT_VFC_FILE("file-importVFCbutton"), + IMPORT_VF_FILE("file-importVFbutton"); + + private String value; + + public String getValue() { + return value; + } + + private Dashboard(String value) { + this.value = value; + } + } + + public enum LifeCyleChangeButtons { + CREATE("create/save"), + CHECK_IN("check_in"), + SUBMIT_FOR_TESTING("submit_for_testing"), + START_TESTING("start_testing"), + ACCEPT("accept"), + APPROVE("approve"), + DISTRIBUTE("distribute"); + + private String value; + + public String getValue() { + return value; + } + + private LifeCyleChangeButtons(String value) { + this.value = value; + } + } + + /** + * Artifacts Related Elements + * + * @author mshitrit + * + */ + public enum Artifatcs { + ADD_DEPLOYMENT_ARTIFACT("add-deployment-artifact-button"), + SELECT_ARTIFACT_DROPDOWN("selectArtifact"), + ARTIFACT_TYPE_DROPDOWN("artifacttype"), + BASE_CMUI_LAB1_ARTIFACT_ITEM("artifact-item-base-cmaui-lab1-06-27-2016-v1.yml"), + OPEN_EDIT_PROPERTIES_FORM_OF_BASE_CMUI_LAB1("edit-parameters-of-base-cmaui-lab1-06-27-2016-v1.yml"), + ARTIFACT_DESCRIPTION("description"), + ARTIFACT_LABEL("artifactLabel"), + BROWSE_BUTTON("browseButton"), + ADD_BUTTON("Add"); + + private String value; + + public String getValue() { + return value; + } + + private Artifatcs(String value) { + this.value = value; + } + + } + + public enum EnvParametersForm { + VALUE_FIELD_OF_AVAILABILITY_ZONE_0("value-field-of-availability_zone_0"), + VALUE_FIELD_OF_CMAUI_FLAVOR("value-field-of-cmaui_flavor"), + DELETE_AVAILABILITY_ZONE_0("delete-availability_zone_0"), + REVERET_CMAUI_FLAVOR("revert-cmaui_flavor"), + DEFAULT_VALUE_COLMN_OF_CMAUI_FLAVOR("default-value-of-cmaui_flavor"), + SAVE_BUTTON("Save"); + private String value; + + public String getValue() { + return value; + } + + private EnvParametersForm(String value) { + this.value = value; + } + + } + + public enum InformationalArtifatcs { + CLOUD_QUESTIONNAIRE("Cloud Questionnaire (completed)"), + FEATURES("Features"), + VENDOR_TEST_RESULT("Vendor Test Result"), + TEST_SCRIPTS("Test Scripts"), + HEAT_TEMPLATE_FROM_VENDOR("HEAT Template from Vendor"), + CAPACITY("Capacity"); + + private String value; + + public String getValue() { + return value; + } + + private InformationalArtifatcs(String value) { + this.value = value; + } + + } + + public enum ArtifactModal { + LABEL("artifactLabel"), TYPE("artifacttype"),; + + private String value; + + public String getValue() { + return value; + } + + private ArtifactModal(String value) { + this.value = value; + } + } + + public enum ModalItems { + BROWSE_BUTTON("browseButton"), + ADD("Add"), + DESCRIPTION("description"), + SUMBIT_FOR_TESTING_MESSAGE("changeLifeCycleMessage"), + OK("OK"), + CANCEL("Cancel"), + ACCEP_TESTING_MESSAGE("checkindialog"), + MESSAGE_TEXT("message"), + DONE("Done"); + + private String value; + + public String getValue() { + return value; + } + + private ModalItems(String value) { + this.value = value; + } + } + + public static final String LEFT_PANEL_PREFIX = "leftbar-section-content-item-"; + + public enum LeftPanelCanvasItems { + BLOCK_STORAGE(LEFT_PANEL_PREFIX + "BlockStorage"), + CINDER_VOLUME(LEFT_PANEL_PREFIX + "CinderVolume"), + COMPUTE(LEFT_PANEL_PREFIX + "Compute"), + LOAD_BALANCER(LEFT_PANEL_PREFIX + "LoadBalancer"), + NOVA_SERVER(LEFT_PANEL_PREFIX + "NovaServer"), + OBJECT_STORAGE(LEFT_PANEL_PREFIX + "ObjectStorage"), + // NEUTRON_PORT(LEFT_PANEL_PREFIX + "-NeutronPort"), + // PORT(LEFT_PANEL_PREFIX + "-Port"), + DATABASE(LEFT_PANEL_PREFIX + "-Database"); + + private String value; + + public String getValue() { + return value; + } + + private LeftPanelCanvasItems(String value) { + this.value = value; + } + } + + public enum RightBar { + PROPERTIES_AND_ATTRIBUTES("properties-and-attributes-tab"), + DEPLOYMENT_ARTIFACTS("deployment-artifact-tab"), + ARTIFACT_NAME("artifactName"), + ADD_ARTIFACT_BUTTON("add_Artifact_Button"), + DELETE_ARTIFACT_BUTTON("delete"), + MYATTR_ATTR_FROM_LIST("my_attr-attr"), + MYATTR_ATTR_VALUE_FROM_LIST("value-of-my_attr"),; + + private String value; + + public String getValue() { + return value; + } + + private RightBar(String value) { + this.value = value; + } + } + + + // for now we use index to work with the breadcrumbs + // any change in the breadcrumbs position will require an update here also + public enum BreadcrumbsButtonsEnum { + HOME("breadcrumbs-button-0"), + COMPONENT("breadcrumbs-button-1"); + + private String value; + + public String getValue() { + return value; + } + + private BreadcrumbsButtonsEnum(String value) { + this.value = value; + } + } + + public enum InputsEnum { + VF_INSTANCE("inputs-vf-instance-0"), + FIRST_INPUT_CHECKBOX("inputs-checkbox-0"), + SECOND_INPUT_CHECKBOX("inputs-checkbox-1"), + ADD_INPUTS_BUTTON("add-inputs-to-service-button"), + SERVICE_INPUT("service-input-0"), + DELETE_INPUT("delete-input-0"); + + private String value; + + public String getValue() { + return value; + } + + private InputsEnum(String value) { + this.value = value; + } + + } + + public enum TabsBar { + HIERARCHY_TAB("hierarchy-tab"), + SELECTED_TAB("selected-tab"), + TAB_HEADER("tab-header"), + TAB_SUB_HEADER("tab-sub-header"), + HIERARCHY_MODULE("hierarchy-module-0"), + HIERARCHY_MODULE_TITLE("hierarchy-module-0-title"), + HIERARCHY_SELECTED_MODULE_DATA("selected-module-data"), + HIERARCHY_SELECTED_MODULE_NAME("selected-module-name"), + HIERARCHY_SELECTED_MODULE_UUID("selected-module-group-uuid"), + HIERARCHY_SELECTED_MODULE_VERSION("selected-module-version"), + HIERARCHY_SELECTED_MODULE_IS_BASE("selected-module-is-base"), + HIERARCHY_SELECTED_MODULE_ARTIFACT_NAME("selected-module-artifact-name"), + HIERARCHY_SELECTED_MODULE_ARTIFACT_UUID("selected-module-artifact-uuid"), + HIERARCHY_SELECTED_MODULE_ARTIFACT_VERSION("selected-module-artifact-version"); + + private String value; + + public String getValue() { + return value; + } + + private TabsBar(String value) { + this.value = value; + } + } + + public enum UpdateNamePopover { + OPEN_POPOVER_ICON("edit-name-popover-icon"), + POPOVER_FORM("popover-form"), + POPOVER_SAVE_BUTTON("popover-save-button"), + POPOVER_INSTANCE_NAME("popover-vfinstance-name"), + POPOVER_HEAT_NAME("popover-heat-name"), + POPOVER_MODULE_NAME("popover-module-name"), + POPOVER_CLOSE_BUTTON("popover-close-button"), + POPOVER_X_BUTTON("popover-x-button"); + + private String value; + + public String getValue() { + return value; + } + + private UpdateNamePopover(String value) { + this.value = value; + } + } + + public enum LinkMenuItems { + CANCEL_BUTTON("link-menu-button-cancel"), + CONNECT_BUTTON("link-menu-button-connect"), + LINK_ITEM_CAP("link-item-capabilities"), + LINK_ITEM_REQ("link-item-requirements"), + LINK_MENU("link-menu-open"); + + private String value; + + public String getValue() { + return value; + } + + private LinkMenuItems(String value) { + this.value = value; + } + } + + public enum GeneralCanvasItems { + CANVAS("canvas"), + CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), + DELETE_INSTANCE_BUTTON("e-sdc-small-icon-delete"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralCanvasItems(String value) { + this.value = value; + } + } + + public enum AttributesSection { + TABLE_ROWS("attributes-table-row"), + EDIT_BUTTON_FOR_NETWORK_ATTR("edit_networks"), + DELETE_BUTTON_FOR_NETWORK_ATTR("delete_networks"), + ADD_BUTTON("add-attribute-button"); + + private String value; + + public String getValue() { + return value; + } + + private AttributesSection(String value) { + this.value = value; + } + } + + public enum AttributeForm { + NAME_FIELD("attributeName"), + DESCRIPTION_FIELD("description"), + TYPE_FIELD("type-field"), + DEFAULT_VAL_FIELD("defaultvalue"), + BOOL_DEFAULT_VAL_FIELD("booleantype"), + SCHEMA_FIELD("schema"), + BOOL_VALUE_FIELD("boolean-type-value"), + HIDDEN_FIELD("hidden"), + UPDATE_BUTTON("Update"), + DONE_BUTTON("Done"), + ADD_BUTTON("Add"); + + private String value; + + public String getValue() { + return value; + } + + private AttributeForm(String value) { + this.value = value; + } + } + + public enum PropertiesSection { + ADD_BUTTON("addGrey"),; + + private String value; + + public String getValue() { + return value; + } + + private PropertiesSection(String value) { + this.value = value; + } + } + + public enum PropertyForm { + FORM_CONTAINER("sdc-edit-property-container"), + NAME_FIELD("propertyName"), + DESCRIPTION_FIELD("description"), + TYPE_FIELD("propertyType"), + SCHEMA_FIELD("schema-type"), + SIMPLE_TYPE_DEFAULT_VAL_FIELD("defaultvalue"), + SIMPLE_TYPE_BOOL_DEFAULT_VAL_FIELD("booleantype"), + LIST_TYPE_DEFAULT_VAL_FIELD("listNewItem-1"), + MAP_TYPE_DEFAULT_VAL_KEY_FIELD_FOR_FIRST_ITEM("mapKey-10"), + MAP_TYPE_DEFAULT_VAL_VALUE_FIELD_FOR_FIRST_ITEM("mapValue-10"), + MAP_TYPE_DEFAULT_VAL_KEY_FIELD_FOR_SECOND_ITEM("mapKey-11"), + MAP_TYPE_DEFAULT_VAL_VALUE_FIELD_FOR_SECOND_ITEM("mapValue-11"), + ADD_ITEM_TO_LIST_BUTTON("add-list-item-1"), + ADD_ITEM_TO_MAP_BUTTON("add-map-item"), + DELETE_FIRST_ITEM_FROM_MAP_BUTTON("delete-map-item-10"), + START_PORT_FIELD_FOR_PORT_PAIRS_DT("-1start_port"), + SAVE_BUTTON("Save"); + + private String value; + + public String getValue() { + return value; + } + + private PropertyForm(String value) { + this.value = value; + } + } + + public enum GeneralSection { + BROWSE_BUTTON("browseButton"), FILE_NAME("filename"), NAME("name"), LOADER("tlv-loader"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralSection(String value) { + this.value = value; + } + } + + public enum ReqAndCapabilitiesSection { + SEARCH_BOX("search-box"), CAP_TAB("cap-tab"), REQ_TAB("req-tab"); + + private String value; + + public String getValue() { + return value; + } + + private ReqAndCapabilitiesSection(String value) { + this.value = value; + } + } + + public enum DeploymentSection { + MODULE_PROPERTIES_HEADER_LIST("list-of-Properties"); + + private String value; + + public String getValue() { + return value; + } + + private DeploymentSection(String value) { + this.value = value; + } + } + + public enum OnBoardingTable { + OPEN_MODAL_BUTTON("repository-icon"), + VENDOR_HEADER_COL("Vendor"), + NAME_HEADER_COL("Name"), + CATEGORY_HEADER_COL("Category"), + VERSION_HEADER_COL("Version"), + IMPORT_ICON("import-csar"), + UPDATE_ICON("update-csar"), + CSAR_ROW("csar-row"), + ONBOARDING_SEARCH("onboarding-search"); + + private String value; + + public String getValue() { + return value; + } + + private OnBoardingTable(String value) { + this.value = value; + } + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/MenuOptionsEnum.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/MenuOptionsEnum.java new file mode 100644 index 0000000000..4c45858de0 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/MenuOptionsEnum.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +public enum MenuOptionsEnum { + + EDIT("Edit"), CHECK_IN("Check in"), CHECK_OUT("Check out"), VIEW("View"), SUBMIT_FOR_TEST("Submit For Test"), ACCEPT("Accept"), REJECT("Reject"), START_TEST("Start test"), DISTREBUTE("Distribute"); + + private String value; + + public String getValue() { + return value; + } + + private MenuOptionsEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/UserCredentials.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/UserCredentials.java new file mode 100644 index 0000000000..0d94529b89 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/UserCredentials.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.uici.tests.datatypes; + +import org.openecomp.sdc.be.model.User; + +public class UserCredentials extends User { + + private String password; + + public UserCredentials(String userId, String password, String firstname, String lastname) { + super(); + setUserId(userId); + this.password = password; + setFirstName(firstname); + setLastName(lastname); + } + + public UserCredentials() { + super(); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java new file mode 100644 index 0000000000..f9e294cbc7 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java @@ -0,0 +1,419 @@ +package org.openecomp.sdc.uici.tests.execute.base; + +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang.NotImplementedException; +import org.apache.log4j.Logger; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; +import org.openecomp.sdc.uici.tests.datatypes.CleanTypeEnum; +import org.openecomp.sdc.uici.tests.datatypes.UserCredentials; +import org.openecomp.sdc.uici.tests.utilities.FileHandling; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.ITestResult; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; + +import com.google.common.collect.Lists; +import com.thinkaurelius.titan.core.TitanGraph; + +public abstract class SetupCDTest extends ComponentBaseTest { + + private TitanSnapshot snapshot; + private static CleanTypeEnum cleanType; + + public SetupCDTest() { + super(new TestName(), SetupCDTest.class.getName()); + } + + public SetupCDTest(TestName name, String className) { + super(name, className); + } + + public static Logger logger = Logger.getLogger(SetupCDTest.class.getName()); + + /**************** CONSTANTS ****************/ + private static final String CREDENTIALS_FILE = "src/main/resources/ci/conf/credentials.yaml"; + public static final String SELENIUM_NODE_URL = "http://%s:%s/wd/hub"; + + /**************** PRIVATES ****************/ + public static Config config; + private Map credentialsYamlFileMap; + + private static String devUrl, cdUrl; + + @BeforeSuite(alwaysRun = true) + public static void openTitan() throws FileNotFoundException { + try { + openTitanLogic(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @AfterSuite(alwaysRun = true) + public static void shutdownTitan() { + shutdownTitanLogic(); + } + + @BeforeSuite(alwaysRun = true) + @Parameters({ "clean-type" }) + public void setEnvParameters(@Optional("PARTIAL") String cleanType) throws FileNotFoundException { + this.cleanType = CleanTypeEnum.findByName(cleanType); + System.out.println("setup before class"); + config = Utils.getConfig(); + loadCredentialsFile(); + setUrl(); + } + + @BeforeMethod(alwaysRun = true) + public void setBrowserBeforeTest() { + setBrowserBeforeTest(getRole()); + } + + /**************** AFTER ****************/ + @AfterMethod(alwaysRun = true) + public void quitAfterTest() { + System.out.println("closing browser"); + GeneralUIUtils.getDriver().quit(); + } + + @BeforeMethod(alwaysRun = true) + public void beforeState(java.lang.reflect.Method method) throws Exception { + CleanTypeEnum cleanType = getCleanMode(); + switch (cleanType) { + case FULL: { + super.performeClean(); + break; + } + case PARTIAL: { + takeTitanSnapshot(); + break; + } + case NONE: { + // No Clean Up + break; + } + default: { + throw new NotImplementedException("Enum Value:" + cleanType.name() + " Is not handled"); + } + } + + } + + @AfterMethod(alwaysRun = true) + public void afterState(ITestResult result) throws Exception { + CleanTypeEnum cleanType = getCleanMode(); + switch (cleanType) { + case FULL: { + super.performeClean(); + break; + } + case PARTIAL: { + resetToOriginalSnapshot(); + break; + } + case NONE: { + // No Clean Up + break; + } + default: { + throw new NotImplementedException("Enum Value:" + cleanType.name() + " Is not handled"); + } + } + + } + + private void takeTitanSnapshot() { + List edgeList = Lists.newArrayList(getTitanGraph().edges(null)); + List verList = Lists.newArrayList(getTitanGraph().vertices(null)); + setSnapshot(new TitanSnapshot(edgeList, verList)); + + } + + private static class TitanSnapshot { + List edges; + List vertices; + + public List getEdges() { + return edges; + } + + public List getVertices() { + return vertices; + } + + private TitanSnapshot(List edges, List vertices) { + super(); + this.edges = edges; + this.vertices = vertices; + } + } + + private void resetToOriginalSnapshot() { + + List joinedEdges = new ArrayList<>(); + List joinedVertices = new ArrayList<>(); + TitanSnapshot original = getSnapshot(); + takeTitanSnapshot(); + TitanSnapshot current = getSnapshot(); + + original.getEdges().stream().forEach(e -> addIfIdInList(e, current.getEdges(), joinedEdges, e2 -> e2.id())); + original.getVertices().stream() + .forEach(e -> addIfIdInList(e, current.getVertices(), joinedVertices, e2 -> e2.id())); + + List edgesToRemove = removeFromList(current.getEdges(), joinedEdges, e2 -> e2.id()); + List verticesToRemove = removeFromList(current.getVertices(), joinedVertices, e2 -> e2.id()); + + List edgesToAdd = removeFromList(original.getEdges(), joinedEdges, e2 -> e2.id()); + List verticesToAdd = removeFromList(original.getVertices(), joinedVertices, e2 -> e2.id()); + + if (edgesToAdd.isEmpty() && verticesToAdd.isEmpty()) { + edgesToRemove.stream().forEach(e -> e.remove()); + verticesToRemove.stream().forEach(v -> v.remove()); + } + + } + + private List removeFromList(List listToRemoveFrom, List elementsToRemove, + Function idGetter) { + Set idSet = new HashSet<>(); + // Fill The Set + elementsToRemove.stream().map(e -> idGetter.apply(e)).forEach(e2 -> idSet.add(e2)); + return listToRemoveFrom.stream().filter(p -> !idSet.contains(idGetter.apply(p))).collect(Collectors.toList()); + + } + + private void addIfIdInList(Element e, List listToCheck, List listToAddTo, + Function idGetter) { + Stream matchingElements = listToCheck.stream() + .filter(p -> idGetter.apply(e).equals(idGetter.apply(p))); + listToAddTo.addAll(matchingElements.collect(Collectors.toList())); + } + + /**************** MAIN ****************/ + public static void main(String[] args) { + System.out.println("---------------------"); + System.out.println("running test from CLI"); + System.out.println("---------------------"); + args = new String[] { "ui-ci.xml" }; + StartTest.main(args); + } + + /***********************************************************************************/ + + protected void setBrowserBeforeTest(UserRoleEnum role) { + System.out.println("setup before test"); + GeneralUIUtils.initDriver(); + setDevUrl(role); + loginWithUser(role); + } + + protected void setUrl() { + cdUrl = config.getUrl(); + setDevUrl(getRole()); + } + + private Map loadCredentialsFile() { + final String credintialsFile = (System.getProperty("credentials.file") != null) + ? System.getProperty("credentials.file") : CREDENTIALS_FILE; + System.out.println("credentials file is : " + credintialsFile); + FunctionalInterfaces.swallowException( + () -> credentialsYamlFileMap = (Map) FileHandling.parseYamlFile(credintialsFile)); + System.out.println(credentialsYamlFileMap.toString()); + return (Map) credentialsYamlFileMap; + } + + protected UserCredentials getUserCredentialsFromFile(String userRole) throws Exception { + Map credentialsMap = (Map) credentialsYamlFileMap.get(userRole); + String user = (String) credentialsMap.get("username"); + String password = (String) credentialsMap.get("password"); + String firstname = (String) credentialsMap.get("firstname"); + String lastname = (String) credentialsMap.get("lastname"); + + return new UserCredentials(user, password, firstname, lastname); + } + + public void navigateToUrl(String url) throws InterruptedException { + WebDriver driver = GeneralUIUtils.getDriver(); + System.out.println("navigating to URL :" + url); + driver.navigate().to(url); + driver.manage().window().maximize(); + driver.manage().deleteAllCookies(); + } + + protected void loginToSystem(UserCredentials credentials) throws Exception { + + sendUserAndPasswordKeys(credentials); + WebElement submitButton = GeneralUIUtils.getDriver().findElement(By.name("btnSubmit")); + submitButton.click(); + WebElement buttonOK = GeneralUIUtils.getDriver().findElement(By.name("successOK")); + AssertJUnit.assertTrue(buttonOK.isDisplayed()); + buttonOK.click(); + System.out.println("Entering to design studio"); + Thread.sleep(2000); + WebElement enterToUserWorkspaceButton = GeneralUIUtils.getDriver() + .findElement(By.xpath("//button[@data-tests-id='Design Studio']")); + enterToUserWorkspaceButton.click(); + } + + private void sendUserAndPasswordKeys(UserCredentials userId) { + System.out.println("Login to system with user : " + userId.getUserId()); + WebElement userNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("userid")); + userNameTextbox.sendKeys(userId.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getDriver().findElement(By.name("password")); + passwordTextbox.sendKeys(userId.getPassword()); + } + + public String getUrl() { + String url; + final CleanTypeEnum workMode = getCleanMode(); + switch (workMode) { + case FULL: { + url = devUrl; + break; + } + case PARTIAL: { + url = devUrl; + break; + } + case NONE: { + url = cdUrl; + break; + } + default: { + throw new NotImplementedException(workMode.name()); + } + + } + return url; + } + + public static void setDevUrl(UserRoleEnum role) { + String url = SetupCDTest.devUrl; + switch (role) { + case ADMIN: { + url = "http://localhost:8181/sdc1/proxy-admin1#/dashboard"; + break; + } + case DESIGNER: { + url = "http://localhost:8181/sdc1/proxy-designer1#/dashboard"; + // url = "http://localhost:9000/#/dashboard"; + break; + } + case GOVERNOR: { + url = "http://localhost:8181/sdc1/proxy-governor1#/dashboard"; + break; + } + case OPS: { + url = "http://localhost:8181/sdc1/proxy-ops1#/dashboard"; + break; + } + case TESTER: { + url = "http://localhost:8181/sdc1/proxy-tester1#/dashboard"; + break; + } + default: { + break; + } + } + SetupCDTest.devUrl = url; + } + + public static Config getConfig() { + return config; + } + + private User user; + + public void loginWithUser(UserRoleEnum role) { + + setUser(role); + String url = getUrl(); + System.out.println("URL is : " + url); + try { + navigateToUrl(url); + if (url.contains("https://www.e-access.att.com")) { + System.out.println("going to update designer user to mechIDs form..."); + UserCredentials credentials = getUserCredentialsFromFile(role.name().toLowerCase()); + loginToSystem(credentials); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void setUser(UserRoleEnum role) { + user = new User(); + user.setUserId(role.getUserId()); + user.setFirstName(role.getFirstName()); + user.setRole(role.name()); + } + + /** + * Current User Role + * + * @return + */ + public UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + + /** + * To change clean type update configuration.
+ * Do not override this method. + * + * @return + */ + protected final CleanTypeEnum getCleanMode() { + return cleanType; + } + + public User getUser() { + return user; + } + + protected void quitAndReLogin(UserRoleEnum role) { + quitAfterTest(); + setBrowserBeforeTest(role); + GeneralUIUtils.waitForLoader(30); + } + + public TitanSnapshot getSnapshot() { + return snapshot; + } + + public void setSnapshot(TitanSnapshot snapshot) { + this.snapshot = snapshot; + } + + public static TitanGraph getTitanGraph() { + return titanGraph; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/generalTests/GeneralTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/generalTests/GeneralTests.java new file mode 100644 index 0000000000..c3caa98c54 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/generalTests/GeneralTests.java @@ -0,0 +1,26 @@ +package org.openecomp.sdc.uici.tests.execute.generalTests; + +import static org.testng.AssertJUnit.assertTrue; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.testng.annotations.Test; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; + +public class GeneralTests extends SetupCDTest{ + + @Test + public void filterVFCMT() throws Exception { + Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFCMT, NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_CALL_CONTROL , UserRoleEnum.DESIGNER, true).left().value(); + assertTrue(!GeneralUIUtils.isElementPresent(resource.getName())); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.MainMenue.CATALOG.getValue()).click(); + assertTrue(!GeneralUIUtils.isElementPresent(resource.getName())); + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceBasicTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceBasicTests.java new file mode 100644 index 0000000000..e42de862b7 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceBasicTests.java @@ -0,0 +1,147 @@ +package org.openecomp.sdc.uici.tests.execute.service; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.Arrays; + +import org.apache.http.HttpStatus; +import org.openecomp.sdc.uici.tests.datatypes.CanvasElement; +import org.openecomp.sdc.uici.tests.datatypes.CanvasManager; +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.uici.tests.utilities.FileHandling; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.utilities.RestCDUtils; +import org.openecomp.sdc.uici.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.uici.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.uici.tests.verificator.VfVerificator; +import org.openqa.selenium.WebElement; +import org.testng.annotations.Test; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; + +public class ServiceBasicTests extends SetupCDTest { + + @Test + public void testCreateService() { + ServiceReqDetails createServiceInUI = ServiceUIUtils.createServiceInUI(getUser()); + ServiceVerificator.verifyServiceCreated(createServiceInUI, getUser()); + } + + @Test + public void testLinkTwoRI() { + + // create 1st VF + ResourceReqDetails resourceOne = ResourceUIUtils.createResourceInUI(getUser()); + assertTrue(RestCDUtils.getResource(resourceOne).getErrorCode() == HttpStatus.SC_OK); + // add LoadBalancer to resource + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.OBJECT_STORAGE); + GeneralUIUtils.checkIn(); + + // create 2nd VF + ResourceReqDetails resourceTwo = ResourceUIUtils.createResourceInUI(getUser()); + assertTrue(RestCDUtils.getResource(resourceTwo).getErrorCode() == HttpStatus.SC_OK); + // add ObjectStorage to resource + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + canvasManager = CanvasManager.getCanvasManager(); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.LOAD_BALANCER); + GeneralUIUtils.checkIn(); + + // create service + ServiceReqDetails createServiceInUI = ServiceUIUtils.createServiceInUI(getUser()); + // Verify Service is Created + ServiceVerificator.verifyServiceCreated(createServiceInUI, getUser()); + + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + canvasManager = CanvasManager.getCanvasManager(); + + // adding two resource instances + CanvasElement vfOne = canvasManager.createElementOnCanvas(resourceOne.getName()); + + CanvasElement vfTwo = canvasManager.createElementOnCanvas(resourceTwo.getName()); + // link elements + canvasManager.linkElements(vfOne, vfTwo); + + // check results + ServiceVerificator.verifyServiceCreated(createServiceInUI, getUser()); + ServiceVerificator.verifyLinkCreated(createServiceInUI, getUser()); + + } + + /** + * This method tests the following:
+ * 1. Import of VF
+ * 2. Certification Of Vf
+ * 3. Adding deployment artifact to VF
+ * 4. Creation of Service
+ * 5. Adding Vf instance to Service
+ * 6. Service Certification
+ * 7. Approving Service to distribution by Governor
+ * 8. Making sure service is ready to distribute by ops
+ */ + @Test + public void testBuildServiceForDistribution() { + ResourceReqDetails importedVf = ResourceUIUtils.importVfInUI(getUser(), FileHandling.getResourcesFilesPath(), + "valid_vf.csar"); + GeneralUIUtils.waitForLoader(20); + // Verify Import + VfVerificator.verifyResourceIsCreated(importedVf); + + // Create Deployment Artifact + ArtifactUIUtils.createDeploymentArtifactOnVf(FileHandling.getResourcesFilesPath() + "myYang.xml", + ArtifactTypeEnum.YANG_XML); + VfVerificator.verifyResourceContainsDeploymentArtifacts(importedVf, + Arrays.asList(new ArtifactTypeEnum[] { ArtifactTypeEnum.YANG_XML })); + + // Submit For Testing Process VF + GeneralUIUtils.submitForTestingElement(importedVf.getName()); + + // Certify The VF + quitAndReLogin(UserRoleEnum.TESTER); + ResourceUIUtils.testAndAcceptElement(importedVf); + + // Verify Certification + GeneralUIUtils.waitForLoader(); + VfVerificator.verifyResourceIsCertified(importedVf); + + // Create Service + quitAndReLogin(UserRoleEnum.DESIGNER); + ServiceReqDetails createServiceInUI = ServiceUIUtils.createServiceInUI(getUser()); + ServiceVerificator.verifyServiceCreated(createServiceInUI, getUser()); + + // Drag the VF To the Service + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.createElementOnCanvas(importedVf.getName()); + + // Submit For Testing Process Service + GeneralUIUtils.submitForTestingElement(null); + + // Certify The Service + quitAndReLogin(UserRoleEnum.TESTER); + ResourceUIUtils.testAndAcceptElement(createServiceInUI); + ServiceVerificator.verifyServiceCertified(createServiceInUI, getUser()); + + // Approve with governor + quitAndReLogin(UserRoleEnum.GOVERNOR); + ServiceUIUtils.approveServiceForDistribution(createServiceInUI); + + // Log in with Ops and verify that can distribute + quitAndReLogin(UserRoleEnum.OPS); + GeneralUIUtils.getWebElementWaitForVisible(createServiceInUI.getName()).click(); + WebElement distributeWebElement = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.DISTRIBUTE.getValue()); + assertTrue(distributeWebElement != null); + + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceInputsTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceInputsTests.java new file mode 100644 index 0000000000..b3e8e023ca --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceInputsTests.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.uici.tests.execute.service; + +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.assertFalse; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.uici.tests.datatypes.CanvasElement; +import org.openecomp.sdc.uici.tests.datatypes.CanvasManager; +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.BreadcrumbsButtonsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.InputsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.ModalItems; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.FileHandling; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.uici.tests.verificator.ServiceVerificator; +import org.testng.annotations.Test; + +public class ServiceInputsTests extends SetupCDTest { + + public String serviceName = ""; + + @Test + private void testSelectingInputAndAddingItToTheService() { + ServiceInputsTestsSetUp(); + + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertTrue(GeneralUIUtils.isElementPresent(InputsEnum.SERVICE_INPUT.getValue())); + } + + @Test + private void testDeletingAnInputFromTheService() { + ServiceInputsTestsSetUp(); + + // clicking on the delete input button and accepting the delete + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.DELETE_INPUT.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(ModalItems.OK.getValue()).click(); + + assertFalse(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertFalse(GeneralUIUtils.isElementPresent(InputsEnum.SERVICE_INPUT.getValue())); + } + + @Test + private void testCheckingInTheServiceAndButtonsAreDisabled() throws Exception { + ServiceInputsTestsSetUp(); + + // Checking in the service and accessing it again in the home + GeneralUIUtils.checkIn(); + GeneralUIUtils.closeNotificatin(); + GeneralUIUtils.findComponentAndClick(serviceName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.INPUTS); + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.VF_INSTANCE.getValue()).click(); + + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.SECOND_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.DELETE_INPUT.getValue()).getAttribute("class").contains("disabled")); + } + + @Test + private void testInputsSanity() throws Exception { + ServiceInputsTestsSetUp(); + + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertTrue(GeneralUIUtils.isElementPresent(InputsEnum.SERVICE_INPUT.getValue())); + + // clicking on the delete input button and accepting the delete + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.DELETE_INPUT.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(ModalItems.OK.getValue()).click(); + + assertFalse(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertFalse(GeneralUIUtils.isElementPresent(InputsEnum.SERVICE_INPUT.getValue())); + + // adding the input to the service again + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.ADD_INPUTS_BUTTON.getValue()).click(); + + // Checking in the service and accessing it again in the home + GeneralUIUtils.checkIn(); + GeneralUIUtils.closeNotificatin(); + GeneralUIUtils.findComponentAndClick(serviceName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.INPUTS); + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.VF_INSTANCE.getValue()).click(); + + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + assertTrue(GeneralUIUtils.getWebElementWaitForVisible(InputsEnum.SECOND_INPUT_CHECKBOX.getValue()).getAttribute("class").contains("disabled")); + } + + private void ServiceInputsTestsSetUp() { + // create vf + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "service_with_inputs.csar"; + ResourceReqDetails importVfREsourceInUI = ResourceUIUtils.importVfInUIWithoutCheckin(getUser(), filePath, fileName); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.closeNotificatin(); + GeneralUIUtils.checkIn(); + GeneralUIUtils.closeNotificatin(); + + // create service + ServiceReqDetails createServiceInUI = ServiceUIUtils.createServiceInUI(getUser()); + ServiceVerificator.verifyServiceCreated(createServiceInUI, getUser()); + serviceName = createServiceInUI.getName(); + + // go to composition + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + + // drag vf into canvas + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement canvasElement = canvasManager.createElementOnCanvas(importVfREsourceInUI.getName()); + canvasManager.selectElementFromCanvas(canvasElement); + GeneralUIUtils.waitForLoader(); + + // moving to inputs view + GeneralUIUtils.getWebElementWaitForClickable(BreadcrumbsButtonsEnum.COMPONENT.getValue()).click(); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.INPUTS); + + // adding the input to the service + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.VF_INSTANCE.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.FIRST_INPUT_CHECKBOX.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(InputsEnum.ADD_INPUTS_BUTTON.getValue()).click(); + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java new file mode 100644 index 0000000000..d3bb8a1375 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java @@ -0,0 +1,333 @@ +package org.openecomp.sdc.uici.tests.execute.vf; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnException; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.Callable; + +import org.apache.http.HttpStatus; +import org.openecomp.sdc.uici.tests.datatypes.CanvasElement; +import org.openecomp.sdc.uici.tests.datatypes.CanvasManager; +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.uici.tests.utilities.FileHandling; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.utilities.RestCDUtils; +import org.openecomp.sdc.uici.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.uici.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.uici.tests.verificator.VfVerificator; +import org.openqa.selenium.WebElement; +import org.testng.annotations.Test; + +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +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.Convertor; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +public class VfBasicTests extends SetupCDTest { + + @Test + public void testImportVfTableColumns() { + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.OPEN_MODAL_BUTTON.getValue()).click(); + + assertTrue(GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.VENDOR_HEADER_COL.getValue()) != null); + assertTrue(GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.NAME_HEADER_COL.getValue()) != null); + assertTrue(GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.CATEGORY_HEADER_COL.getValue()) != null); + + assertTrue(GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.VERSION_HEADER_COL.getValue()) != null); + } + + private void testsToChangeSomeParametersValues(){ + //open parameters form + GeneralUIUtils.moveToHTMLElementByDataTestId(DataTestIdEnum.Artifatcs.BASE_CMUI_LAB1_ARTIFACT_ITEM.getValue()); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.Artifatcs.OPEN_EDIT_PROPERTIES_FORM_OF_BASE_CMUI_LAB1.getValue()).click(); + //edit values for parameter without default value and for parameter with default + String valueForFirstParam="111"; + String newValueForSecondParam="222"; + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_AVAILABILITY_ZONE_0.getValue()).sendKeys(valueForFirstParam); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_CMAUI_FLAVOR.getValue()).clear(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_CMAUI_FLAVOR.getValue()).sendKeys(newValueForSecondParam); + //save changes + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.EnvParametersForm.SAVE_BUTTON.getValue()).click(); + GeneralUIUtils.waitForLoader(); + //open form again + GeneralUIUtils.moveToHTMLElementByDataTestId(DataTestIdEnum.Artifatcs.BASE_CMUI_LAB1_ARTIFACT_ITEM.getValue()); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.Artifatcs.OPEN_EDIT_PROPERTIES_FORM_OF_BASE_CMUI_LAB1.getValue()).click(); + //check if values were changed + assertTrue("The parameter value without default was not changed.", + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_AVAILABILITY_ZONE_0.getValue()).getAttribute("value").equals(valueForFirstParam)); + assertTrue("The parameter value with default was not changed.", + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_CMAUI_FLAVOR.getValue()).getAttribute("value").equals(newValueForSecondParam)); + //delete the value of the parameter without default + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.EnvParametersForm.DELETE_AVAILABILITY_ZONE_0.getValue()).click(); + boolean isThereDefaultValue=!GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.EnvParametersForm.DEFAULT_VALUE_COLMN_OF_CMAUI_FLAVOR.getValue()).getText().isEmpty(); + if(isThereDefaultValue){ + //revert the value of the parameter with default + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.EnvParametersForm.REVERET_CMAUI_FLAVOR.getValue()).click(); + } + //save changes + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.EnvParametersForm.SAVE_BUTTON.getValue()).click(); + GeneralUIUtils.waitForLoader(); + //open form again + GeneralUIUtils.moveToHTMLElementByDataTestId(DataTestIdEnum.Artifatcs.BASE_CMUI_LAB1_ARTIFACT_ITEM.getValue()); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.Artifatcs.OPEN_EDIT_PROPERTIES_FORM_OF_BASE_CMUI_LAB1.getValue()).click(); + //check if values were changed + assertTrue("The parameter value without default was not deleted.", + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_AVAILABILITY_ZONE_0.getValue()).getAttribute("value").equals("")); + if(isThereDefaultValue){ + String theDefaultValue="m1.large"; + assertTrue("The parameter value with default was not reverted.", + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.EnvParametersForm.VALUE_FIELD_OF_CMAUI_FLAVOR.getValue()).getAttribute("value").equals(theDefaultValue)); + } + } + + @Test + public void testVFiUpdateHeatENVParameters() throws Exception { + // create vf + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "vmmc_work.csar"; + ResourceReqDetails importVfResourceInUI = ResourceUIUtils.importVfInUIWithoutCheckin(getUser(), filePath, + fileName); + GeneralUIUtils.closeNotificatin(); + GeneralUIUtils.checkIn(); + GeneralUIUtils.closeNotificatin(); + //create service + ServiceReqDetails createServiceInUI = ServiceUIUtils.createServiceInUI(getUser()); + ServiceVerificator.verifyServiceCreated(createServiceInUI, getUser()); + //go to composition + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + //drag vf into canvas + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement canvasElement = canvasManager.createElementOnCanvas(importVfResourceInUI.getName()); + canvasManager.selectElementFromCanvas(canvasElement); + GeneralUIUtils.waitForLoader(); + //go to deployment artifacts tab + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.RightBar.DEPLOYMENT_ARTIFACTS.getValue()).click(); + //test change parameters + testsToChangeSomeParametersValues(); + } + + @Test + public void testVFUpdateHeatENVParameters() throws Exception { + // create vf + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "vmmc_work.csar"; + ResourceReqDetails importVfResourceInUI = ResourceUIUtils.importVfInUIWithoutCheckin(getUser(), filePath, + fileName); + //go to deployment artifacts + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.DEPLOYMENT_ARTIFACT); + //test change parameters + testsToChangeSomeParametersValues(); + } + + @Test + public void testUpdateVfCreatedFromCsar() throws Exception { + // create vf + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "Sample_CSAR.csar"; + ResourceReqDetails importVfResourceInUI = ResourceUIUtils.importVfInUIWithoutCheckin(getUser(), filePath, + fileName); + // update csar + fileName = "Sample_CSAR2.csar"; + ResourceUIUtils.updateVfCsar(filePath, fileName); + VfVerificator.verifyNumOfComponentInstances(importVfResourceInUI, 4); + } + + @Test + public void testImportVf() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "Sample_CSAR.csar"; + ResourceReqDetails importVfResourceInUI = ResourceUIUtils.importVfInUI(getUser(), filePath, fileName); + GeneralUIUtils.waitForLoader(); + assertTrue(RestCDUtils.getResource(importVfResourceInUI).getErrorCode() == HttpStatus.SC_OK); + } + + @Test + public void testCreateVf() { + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + assertTrue(RestCDUtils.getResource(createResourceInUI).getErrorCode() == HttpStatus.SC_OK); + } + + @Test + public void testDeleteInstanceFromCanvas() { + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.BLOCK_STORAGE); + CanvasElement computeElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + VfVerificator.verifyNumOfComponentInstances(createResourceInUI, 2); + canvasManager.deleteElementFromCanvas(computeElement); + VfVerificator.verifyNumOfComponentInstances(createResourceInUI, 1); + + } + + @Test + public void testUpdateInstanceAttributeValue() { + // creare vfc with attrs + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceReqDetails importVfcResourceInUI = ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.checkIn(); + // create vf + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + // add vfc to canvas + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement canvasElement = canvasManager.createElementOnCanvas(importVfcResourceInUI.getName()); + canvasManager.selectElementFromCanvas(canvasElement); + // edit value of vfc attr + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.RightBar.PROPERTIES_AND_ATTRIBUTES.getValue()) + .click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.RightBar.MYATTR_ATTR_FROM_LIST.getValue()).click(); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.DEFAULT_VAL_FIELD.getValue()) + .sendKeys("2"); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.DONE_BUTTON.getValue()).click(); + String newValue = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.RightBar.MYATTR_ATTR_VALUE_FROM_LIST.getValue()).getText(); + assertEquals("2", newValue); + } + + @Test(enabled = false) + public void testAddInfomratinalArtifact() throws Exception { + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.INFORMATION_ARTIFACT); + + ArtifactReqDetails informationalArtifact = ElementFactory.getDefaultArtifact(); + final String FILE_PATH = System.getProperty("user.dir") + "\\src\\main\\resources\\Files\\"; + final String FILE_NAME = "Valid_tosca_Mycompute.yml"; + + ArtifactUIUtils.addInformationArtifact(informationalArtifact, FILE_PATH + FILE_NAME, + DataTestIdEnum.InformationalArtifatcs.FEATURES); + ArtifactUIUtils.addInformationArtifact(informationalArtifact, FILE_PATH + FILE_NAME, + DataTestIdEnum.InformationalArtifatcs.CAPACITY); + + RestResponse getResourceResponse = RestCDUtils.getResource(createResourceInUI); + assertEquals("Did not succeed to get resource after create", HttpStatus.SC_OK, + getResourceResponse.getErrorCode().intValue()); + + Map> artifactsListFromResponse = ArtifactUIUtils + .getArtifactsListFromResponse(getResourceResponse.getResponse(), "artifacts"); + Map map = artifactsListFromResponse.get("Features"); + + assertTrue(artifactsListFromResponse.size() >= 2); + + } + + @Test + public void testVfCertification() throws IOException { + // Create VF + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + assertTrue(RestCDUtils.getResource(createResourceInUI).getErrorCode() == HttpStatus.SC_OK); + + // Submit For Testing Process + GeneralUIUtils.submitForTestingElement(createResourceInUI.getName()); + + // Tester + quitAndReLogin(UserRoleEnum.TESTER); + ResourceUIUtils.testAndAcceptElement(createResourceInUI); + + // Verification + GeneralUIUtils.waitForLoader(); + VfVerificator.verifyResourceIsCertified(createResourceInUI); + + } + + @Test + public void testDeploymentArtifactForVFi() { + User user = getUser(); + // create vf + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(user); + GeneralUIUtils.checkIn(); + GeneralUIUtils.waitForLoader(); + // create service + GeneralUIUtils.clickOnCreateEntityFromDashboard(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()); + ResourceUIUtils.defineResourceName("serv"); + GeneralUIUtils.defineDescription("description"); + GeneralUIUtils.waitForLoader(); + ResourceUIUtils.defineResourceCategory("Mobility", "selectGeneralCategory"); + ResourceUIUtils.defineProjectCode("012345"); + GeneralUIUtils.clickSaveButton(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + GeneralUIUtils.waitForLoader(); + // add vf to canvas + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement canvasElement = canvasManager.createElementOnCanvas(createResourceInUI.getName()); + canvasManager.selectElementFromCanvas(canvasElement); + GeneralUIUtils.waitForLoader(); + // add artifact + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.RightBar.DEPLOYMENT_ARTIFACTS.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.RightBar.ADD_ARTIFACT_BUTTON.getValue()).click(); + String newArtifactLabel = "newArtifact"; + ArtifactReqDetails details = new ArtifactReqDetails("new_atifact", "DCAE_INVENTORY_EVENT", "desc", "", + newArtifactLabel); + ResourceUIUtils.fillinDeploymentArtifactFormAndClickDone(details, + FileHandling.getResourcesFilesPath() + "yamlSample.yml"); + assertTrue(GeneralUIUtils.isElementPresent("artifact_Display_Name-" + newArtifactLabel)); + // edit artifact + GeneralUIUtils.getWebElementWaitForClickable("artifact_Display_Name-" + newArtifactLabel).click(); + String newFileName = "yamlSample2.yml"; + retryMethodOnException( + () -> GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.GeneralSection.BROWSE_BUTTON.getValue()) + .sendKeys(FileHandling.getResourcesFilesPath() + newFileName)); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.DONE.getValue()).click(); + GeneralUIUtils.waitForLoader(); + assertEquals(newFileName, + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.RightBar.ARTIFACT_NAME.getValue()).getText()); + // delete artifact + GeneralUIUtils.moveToHTMLElementByDataTestId("artifact_Display_Name-" + newArtifactLabel); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.RightBar.DELETE_ARTIFACT_BUTTON.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.waitForLoader(); + assertTrue(!GeneralUIUtils.isElementPresent("artifact_Display_Name-" + newArtifactLabel)); + } + + @Test + public void testDisplayVfModuleProperies() { + //create vf with components instances properties + ResourceReqDetails importedVf = ResourceUIUtils.importVfInUI(getUser(), FileHandling.getResourcesFilesPath(), + "vmmc_work.csar"); + GeneralUIUtils.waitForLoader(40); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.DEPLOYMENT); + GeneralUIUtils.getWebElementWaitForClickable("hierarchy-module-0-title").click(); + assertTrue(GeneralUIUtils.isElementPresent(DataTestIdEnum.DeploymentSection.MODULE_PROPERTIES_HEADER_LIST.getValue())); + } + + protected ArtifactReqDetails defineInformationalArtifact() throws IOException, Exception { + return ElementFactory.getDefaultArtifact(); + } + + protected ResourceRespJavaObject buildResourceJavaObject(ResourceReqDetails resource, RestResponse restResponse, + User user) { + ResourceRespJavaObject resourceObject = new ResourceRespJavaObject(); + resourceObject = Convertor.constructFieldsForRespValidation(resource, resource.getVersion(), user); + resourceObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString()); + resourceObject.setAbstractt("false"); + resourceObject.setIcon(resource.getIcon().replace(" ", "")); + resourceObject.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + return resourceObject; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfCanvasTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfCanvasTests.java new file mode 100644 index 0000000000..73b09666ae --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfCanvasTests.java @@ -0,0 +1,80 @@ +package org.openecomp.sdc.uici.tests.execute.vf; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.uici.tests.datatypes.CanvasElement; +import org.openecomp.sdc.uici.tests.datatypes.CanvasManager; +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.verificator.VfVerificator; +import org.testng.annotations.Test; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; + +public class VfCanvasTests extends SetupCDTest { + + @Test + public void testCanvasDrag() { + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement createElementOnCanvas = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.BLOCK_STORAGE); + + ImmutablePair preMovePos = ResourceUIUtils.getRIPosition(createResourceInUI, getUser()); + + canvasManager.moveElementOnCanvas(createElementOnCanvas); + + VfVerificator.verifyRILocationChanged(createResourceInUI, preMovePos, getUser()); + + } + + @Test + public void testCanvasConnectComponents() { + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement bsElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.BLOCK_STORAGE); + CanvasElement computeElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + + canvasManager.linkElements(bsElement, computeElement); + + VfVerificator.verifyLinkCreated(createResourceInUI); + + } + + @Test + public void testCanvasVFSanity() { + ResourceReqDetails createResourceInUI = ResourceUIUtils.createResourceInUI(getUser()); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.COMPOSITION); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CanvasElement bsElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.BLOCK_STORAGE); + CanvasElement compElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + + ImmutablePair preMovePos = ResourceUIUtils.getRIPosition(createResourceInUI, getUser()); + canvasManager.moveElementOnCanvas(bsElement); + canvasManager.moveElementOnCanvas(compElement); + + VfVerificator.verifyRILocationChanged(createResourceInUI, preMovePos, getUser()); + + CanvasElement bsElement2 = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.BLOCK_STORAGE); + + canvasManager.linkElements(bsElement2, compElement); + + VfVerificator.verifyLinkCreated(createResourceInUI); + + VfVerificator.verifyNumOfComponentInstances(createResourceInUI, 3); + + canvasManager.moveElementOnCanvas(compElement); + + canvasManager.deleteElementFromCanvas(bsElement); + + VfVerificator.verifyNumOfComponentInstances(createResourceInUI, 2); + + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfDeploymentTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfDeploymentTests.java new file mode 100644 index 0000000000..47344b7c68 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfDeploymentTests.java @@ -0,0 +1,340 @@ +package org.openecomp.sdc.uici.tests.execute.vf; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.regex.Pattern; + +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.FileHandling; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.utilities.RestCDUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.Test; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; + +public class VfDeploymentTests extends SetupCDTest { + + // *****************************EditNamePopoverTests*****************************// + @Test + public void ClickingOnEditNamePopoverIconShouldOpenTheEditNamePopoverForm() { + EditNamePopoverTestsSetUp(); + + assertTrue(GeneralUIUtils.isElementPresent(DataTestIdEnum.UpdateNamePopover.POPOVER_FORM.getValue())); + } + + @Test + public void ModuleDataShouldBeDisplayedInTheEditNameForm() { + EditNamePopoverTestsSetUp(); + + WebElement instanceName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_INSTANCE_NAME.getValue()); + WebElement heatName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_HEAT_NAME.getValue()); + WebElement moduleName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_MODULE_NAME.getValue()); + + String moduleNameToDivide = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()).getText(); + + String[] dividedModuleName = moduleNameToDivide.split(Pattern.quote("..")); + + assertEquals(dividedModuleName[0], instanceName.getText()); + assertEquals(dividedModuleName[1], heatName.getAttribute("value")); + assertEquals(dividedModuleName[2], moduleName.getText()); + + } + + @Test + public void CloseButtonShouldCloseThePopover() { + EditNamePopoverTestsSetUp(); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_CLOSE_BUTTON.getValue()) + .click(); + + assertFalse(GeneralUIUtils.isElementPresent(DataTestIdEnum.UpdateNamePopover.POPOVER_FORM.getValue())); + } + + @Test + public void XButtonShouldCloseThePopover() { + EditNamePopoverTestsSetUp(); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_X_BUTTON.getValue()) + .click(); + + assertFalse(GeneralUIUtils.isElementPresent(DataTestIdEnum.UpdateNamePopover.POPOVER_FORM.getValue())); + } + + @Test + public void SaveButtonShouldBeDisabledWhileTheNameHasNotBeenChanged() { + EditNamePopoverTestsSetUp(); + + WebElement popoverSaveButton = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_SAVE_BUTTON.getValue()); + + assertTrue(popoverSaveButton.getAttribute("class").contains("disabled")); + } + + @Test + public void ClickingOnTheSaveButtonShouldUpdateTheModuleName() { + EditNamePopoverTestsSetUp(); + + String newName = "testName"; + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_HEAT_NAME.getValue()) + .clear(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_HEAT_NAME.getValue()) + .sendKeys(newName); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_SAVE_BUTTON.getValue()) + .click(); + + GeneralUIUtils.waitForLoader(); + + String moduleName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()).getText(); + + String[] dividedModuleName = moduleName.split(Pattern.quote("..")); + + assertEquals(dividedModuleName[1], newName); + } + + @Test + public void testUpdateModuleNameSanity() { + EditNamePopoverTestsSetUp(); + + String newName = "testName"; + + WebElement instanceName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_INSTANCE_NAME.getValue()); + WebElement heatName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_HEAT_NAME.getValue()); + WebElement moduleName = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_MODULE_NAME.getValue()); + + String moduleNameToDivide = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()).getText(); + + String[] dividedModuleName = moduleNameToDivide.split(Pattern.quote("..")); + + assertEquals(dividedModuleName[0], instanceName.getText()); + assertEquals(dividedModuleName[1], heatName.getAttribute("value")); + assertEquals(dividedModuleName[2], moduleName.getText()); + + WebElement popoverSaveButton = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.POPOVER_SAVE_BUTTON.getValue()); + + assertTrue(popoverSaveButton.getAttribute("class").contains("disabled")); + + heatName.clear(); + heatName.sendKeys(newName); + + popoverSaveButton.click(); + + GeneralUIUtils.waitForLoader(); + + moduleNameToDivide = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()).getText(); + dividedModuleName = moduleNameToDivide.split(Pattern.quote("..")); + + assertEquals(dividedModuleName[1], newName); + } + + // *****************************DeploymentTabsTests*****************************// + + @Test + public void testTabIsBeingDisplayedAtDeploymentView() { + DeploymentTestsSetUp(); + + assertTrue(GeneralUIUtils.isElementPresent(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue())); + } + + @Test + public void testClickingOnTabSetsItAsSelected() { + DeploymentTestsSetUp(); + + WebElement hierarchyTab = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()); + hierarchyTab.click(); + + assertTrue(hierarchyTab.getAttribute("class").contains("selected")); + } + + @Test + public void testTabNameIsBeingDisplayedInTheSelectedTabHeader() { + DeploymentTestsSetUp(); + + // select the hierarchy tab and check the header + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + WebElement tabHeader = GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.TAB_HEADER.getValue()); + + assertEquals(tabHeader.getText(), "HIERARCHY"); + } + + @Test + public void testSelectingModuleNameInTheHierarchyTabShouldSelectIt() { + DeploymentTestsSetUp(); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + WebElement hierarchyModule = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE_TITLE.getValue()); + + hierarchyModule.click(); + + assertTrue(hierarchyModule.getAttribute("class").contains("selected")); + } + + @Test + public void testSelectingModuleNameInTheHierarchyTabShouldExpandIt() { + DeploymentTestsSetUp(); + + // select hierarchy tab + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + WebElement hierarchyModule = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()); + + hierarchyModule.click(); + + assertTrue(hierarchyModule.getAttribute("class").contains("expanded")); + } + + @Test + public void testSelectingModuleNameInTheHierarchyTabShouldDisplayItsData() { + DeploymentTestsSetUp(); + + // select hierarchy tab + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()).click(); + + assertTrue(GeneralUIUtils.isElementPresent(DataTestIdEnum.TabsBar.HIERARCHY_SELECTED_MODULE_DATA.getValue())); + } + + @Test(enabled = false) + public void testResourceNameIsBeingDisplayedInTheSelectedTabSubHeader() { + DeploymentTestsSetUp(); + + // select the hierarchy tab and check the header + // WebElement tabSubHeader = + // getWebElement(DataTestIdEnum.TabsBar.TAB_SUB_HEADER.getValue()); + + // assertEquals(tabSubHeader.getText(), vmmcCsar.getName()); + } + + @Test(enabled = false) + public void testSelectingModuleNameInTheHierarchyTabShouldDisplayItsInformation() throws IOException { + DeploymentTestsSetUp(); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + WebElement hierarchyModule = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()); + + // get the module + // String component = RestCDUtils.getResource(vmmcCsar).getResponse(); + // TODO idana fix test + /* + * GroupDefinitionInfo module = getModuleById(component, + * hierarchyModule.getText()); + * + * hierarchyModule.click(); + * + * assertModuleDetails(module, hierarchyModule); + */ + + } + + @Test(enabled = false) + public void testSelectingModuleNameInTheHierarchyTabShouldDisplayItsArtifacts() throws IOException { + DeploymentTestsSetUp(); + + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + WebElement hierarchyModule = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()); + + // TODO idana fix test + // Get the artifact from the module + /* + * String component = RestCDUtils.getResource(vmmcCsar, + * getUser()).getResponse(); GroupDefinitionInfo module = + * getModuleById(component, hierarchyModule.getText()); + * ArtifactDefinitionInfo artifact = module.getArtifacts().get(0); + * + * hierarchyModule.click(); + * + * assertModuleArtifactDetails(artifact); + */ + } + + @Test + public void testTabsViewSanity() throws IOException { + DeploymentTestsSetUp(); + + WebElement hierarchyTab = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()); + + assertTrue(hierarchyTab != null); + + hierarchyTab.click(); + + assertTrue(hierarchyTab.getAttribute("class").contains("selected")); + + WebElement tabHeader = GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.TAB_HEADER.getValue()); + WebElement tabSubHeader = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.TAB_SUB_HEADER.getValue()); + + assertEquals(tabHeader.getText(), "HIERARCHY"); + // assertEquals(tabSubHeader.getText(), vmmcCsar.getName()); + + WebElement hierarchyModule = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()); + WebElement hierarchyModuleTitle = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE_TITLE.getValue()); + hierarchyModule.click(); + WebElement selectedModuleData = GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_SELECTED_MODULE_DATA.getValue()); + + assertTrue(hierarchyModuleTitle.getAttribute("class").contains("selected")); + assertTrue(hierarchyModule.getAttribute("class").contains("expanded")); + assertTrue(selectedModuleData.getAttribute("ng-if") != null); + // TODO idana fix test + /* + * String component = RestCDUtils.getResource(vmmcCsar, + * getUser()).getResponse(); GroupDefinitionInfo module = + * getModuleById(component, hierarchyModule.getText()); + * ArtifactDefinitionInfo artifact = module.getArtifacts().get(0); + * + * assertModuleDetails(module, hierarchyModule); + * + * assertModuleArtifactDetails(artifact); + */ + + } + + // ************************DeploymentTestsSetUpFunction************************// + + private void EditNamePopoverTestsSetUp() { + DeploymentTestsSetUp(); + + // clicking on a module and opening the edit name popover + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_TAB.getValue()).click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.TabsBar.HIERARCHY_MODULE.getValue()).click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.UpdateNamePopover.OPEN_POPOVER_ICON.getValue()) + .click(); + } + + private void DeploymentTestsSetUp() { + // import csar + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "vf_with_groups.csar"; + ResourceUIUtils.importVfInUI(getUser(), filePath, fileName); + + GeneralUIUtils.waitForLoader(20); + + // moving to deployment view + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.DEPLOYMENT); + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfOnboardingTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfOnboardingTests.java new file mode 100644 index 0000000000..a81d854630 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfOnboardingTests.java @@ -0,0 +1,63 @@ +package org.openecomp.sdc.uici.tests.execute.vf; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.OnboardUtility; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.testng.annotations.Test; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import com.google.gson.GsonBuilder; + +public class VfOnboardingTests extends SetupCDTest { + + @Test + public void testUpdateVfCreatedOnBoarding() { + // create vf + ResourceReqDetails importVfResourceInUI = ResourceUIUtils.importVfFromOnBoardingModalWithoutCheckin(getUser(), + "mock_vf"); + // update vf + ResourceUIUtils.updateVfCsarFromOnBoarding(); + } + + @Test + public void createVfsFromOnboarding() throws IOException { + String folderPath = "C:\\onboardingTest\\onBoardingZips"; + File folder = new File(folderPath); + File[] listOfFiles = folder.listFiles(); + List zipFileNames = Arrays.asList(listOfFiles).stream().map(file -> file.getName()) + .filter(fileName -> fileName.endsWith(".zip")).collect(Collectors.toList()); + Map filesSuccessMap = new HashMap<>(); + for (String fileName : zipFileNames) { + try { + createSingleVfFromOnboarding(folderPath, fileName); + filesSuccessMap.put(fileName, "SUCCESS"); + } catch (Exception e) { + filesSuccessMap.put(fileName, "FAIL"); + } + } + Path file = Paths.get("RunResults.txt"); + String stringDataModel = new GsonBuilder().setPrettyPrinting().create().toJson(filesSuccessMap); + Files.write(file, stringDataModel.getBytes()); + } + + private static void createSingleVfFromOnboarding(String filePath, String zipFileName) { + String userId = UserRoleEnum.DESIGNER.getUserId(); + OnboardUtility.createVfFromOnboarding(userId, zipFileName, filePath); + GeneralUIUtils.submitForTestingElement("Vf From Onboarding"); + + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java new file mode 100644 index 0000000000..eb4980e3a0 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java @@ -0,0 +1,270 @@ +package org.openecomp.sdc.uici.tests.execute.vfc; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.http.HttpStatus; +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openecomp.sdc.uici.tests.utilities.FileHandling; +import org.openecomp.sdc.uici.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.utilities.RestCDUtils; +import org.openecomp.sdc.uici.tests.verificator.VfVerificator; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; +import org.testng.annotations.Test; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +public class VfcBasicTests extends SetupCDTest { + + @Test + public void testRequirementsAndCapabilitiesSectionOfVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "mycompute.yml"; + ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.REQUIREMENTS_AND_CAPABILITIES); + // all expected requirements + assertTrue("Not all expected requirements are displayed.", + GeneralUIUtils.isElementPresent("dependency") && GeneralUIUtils.isElementPresent("local_storage")); + // filter requirements + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ReqAndCapabilitiesSection.SEARCH_BOX.getValue()) + .sendKeys("root"); + Supplier supplier = () -> !GeneralUIUtils.isElementPresent("local_storage"); + Function resultVerifier = isNotPresent -> isNotPresent; + Boolean isFilteredRowNotPresent = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The new property was not inserted to the properties table.", isFilteredRowNotPresent); + assertTrue("Filter problem.", GeneralUIUtils.isElementPresent("dependency") && isFilteredRowNotPresent); + // move to cap tab + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ReqAndCapabilitiesSection.CAP_TAB.getValue()).click(); + GeneralUIUtils.getWebElementWaitForVisible("endpoint").click(); + GeneralUIUtils.getWebElementWaitForVisible("initiator").click(); + supplier = () -> GeneralUIUtils.isElementPresent(DataTestIdEnum.PropertyForm.FORM_CONTAINER.getValue()); + resultVerifier = isPresent -> isPresent; + Boolean isPopupOpen = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The update property popup was not opened.", isPopupOpen); + } + + @Test + public void testCreatePropertyTypeListForVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.PROPERTIES); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertiesSection.ADD_BUTTON.getValue()).click(); + // fill in fields + String newPropName = "listProperty"; + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.NAME_FIELD.getValue()) + .sendKeys(newPropName); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.DESCRIPTION_FIELD.getValue()) + .sendKeys("desc"); + Select typeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.TYPE_FIELD.getValue())); + typeField.selectByVisibleText("list"); + Select schemaTypeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.SCHEMA_FIELD.getValue())); + schemaTypeField.selectByVisibleText("string"); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.LIST_TYPE_DEFAULT_VAL_FIELD.getValue()) + .sendKeys("first"); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.ADD_ITEM_TO_LIST_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.LIST_TYPE_DEFAULT_VAL_FIELD.getValue()) + .sendKeys("second"); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.ADD_ITEM_TO_LIST_BUTTON.getValue()) + .click(); + // save + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.SAVE_BUTTON.getValue()).click(); + Supplier supplier = () -> GeneralUIUtils.isElementPresent(newPropName); + Function resultVerifier = isPresent -> isPresent; + Boolean isPresent = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The new property was not inserted to the properties table.", isPresent); + } + + @Test + public void testCreatePropertyTypeMapForVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.PROPERTIES); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertiesSection.ADD_BUTTON.getValue()).click(); + // fill in fields + String newPropName = "mapProperty"; + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.NAME_FIELD.getValue()) + .sendKeys(newPropName); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.DESCRIPTION_FIELD.getValue()) + .sendKeys("desc"); + Select typeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.TYPE_FIELD.getValue())); + typeField.selectByVisibleText("map"); + Select schemaTypeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.SCHEMA_FIELD.getValue())); + schemaTypeField.selectByVisibleText("string"); + // insert item to map + GeneralUIUtils + .getWebElementWaitForVisible( + DataTestIdEnum.PropertyForm.MAP_TYPE_DEFAULT_VAL_KEY_FIELD_FOR_FIRST_ITEM.getValue()) + .sendKeys("key1"); + GeneralUIUtils + .getWebElementWaitForVisible( + DataTestIdEnum.PropertyForm.MAP_TYPE_DEFAULT_VAL_VALUE_FIELD_FOR_FIRST_ITEM.getValue()) + .sendKeys("val1"); + // insert item to map + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.ADD_ITEM_TO_MAP_BUTTON.getValue()) + .click(); + GeneralUIUtils + .getWebElementWaitForVisible( + DataTestIdEnum.PropertyForm.MAP_TYPE_DEFAULT_VAL_KEY_FIELD_FOR_SECOND_ITEM.getValue()) + .sendKeys("key2"); + GeneralUIUtils + .getWebElementWaitForVisible( + DataTestIdEnum.PropertyForm.MAP_TYPE_DEFAULT_VAL_VALUE_FIELD_FOR_SECOND_ITEM.getValue()) + .sendKeys("val2"); + // delete item from map + GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.DELETE_FIRST_ITEM_FROM_MAP_BUTTON.getValue()) + .click(); + // save + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.SAVE_BUTTON.getValue()).click(); + Supplier supplier = () -> GeneralUIUtils.isElementPresent(newPropName); + Function resultVerifier = isPresent -> isPresent; + Boolean isPresent = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The new property was not inserted to the properties table.", isPresent); + } + + @Test + public void testCreatePropertyTypeDTForVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.PROPERTIES); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertiesSection.ADD_BUTTON.getValue()).click(); + // fill in fields + String newPropName = "dt"; + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.NAME_FIELD.getValue()) + .sendKeys(newPropName); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.DESCRIPTION_FIELD.getValue()) + .sendKeys("desc"); + Select typeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.TYPE_FIELD.getValue())); + typeField.selectByValue("org.openecomp.datatypes.heat.contrail.network.rule.PortPairs"); + GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.START_PORT_FIELD_FOR_PORT_PAIRS_DT.getValue()) + .sendKeys("first"); + // save + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.PropertyForm.SAVE_BUTTON.getValue()).click(); + Supplier supplier = () -> GeneralUIUtils.isElementPresent(newPropName); + Function resultVerifier = isPresent -> isPresent; + Boolean isPresent = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The new property was not inserted to the properties table.", isPresent); + } + + @Test + public void testViewAttributesTabForVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceReqDetails importVfcResourceInUI = ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.ATTRIBUTES); + + List attributesRows = GeneralUIUtils + .getWebElementsListWaitForVisible(DataTestIdEnum.AttributesSection.TABLE_ROWS.getValue()); + assertTrue("There is not any row in the table.", !CollectionUtils.isEmpty(attributesRows)); + // display editable buttons + assertTrue("The Add button is not dispaly.", + GeneralUIUtils.isElementPresent(DataTestIdEnum.AttributesSection.ADD_BUTTON.getValue())); + assertTrue("The Edit button is not dispaly for 'network' attribute.", GeneralUIUtils + .isElementPresent(DataTestIdEnum.AttributesSection.EDIT_BUTTON_FOR_NETWORK_ATTR.getValue())); + assertTrue("The Remove button is not dispaly for 'network' attribute.", GeneralUIUtils + .isElementPresent(DataTestIdEnum.AttributesSection.DELETE_BUTTON_FOR_NETWORK_ATTR.getValue())); + // click checkin + GeneralUIUtils.checkIn(); + // enter again + GeneralUIUtils.getWebElementWaitForVisible(importVfcResourceInUI.getName()).click(); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.ATTRIBUTES); + // the editable buttons disappear + assertTrue("The Add button is not dispaly.", + !GeneralUIUtils.isElementPresent(DataTestIdEnum.AttributesSection.ADD_BUTTON.getValue())); + assertTrue("The Edit button is not dispaly for 'network' attribute.", !GeneralUIUtils + .isElementPresent(DataTestIdEnum.AttributesSection.EDIT_BUTTON_FOR_NETWORK_ATTR.getValue())); + assertTrue("The Remove button is not dispaly for 'network' attribute.", !GeneralUIUtils + .isElementPresent(DataTestIdEnum.AttributesSection.DELETE_BUTTON_FOR_NETWORK_ATTR.getValue())); + } + + @Test + public void testCreateAttributeForVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceReqDetails importVfcResourceInUI = ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.ATTRIBUTES); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributesSection.ADD_BUTTON.getValue()).click(); + // fill in fields + String newAttrName = "attr"; + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.NAME_FIELD.getValue()) + .sendKeys(newAttrName); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.DESCRIPTION_FIELD.getValue()) + .sendKeys("desc"); + Select typeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.TYPE_FIELD.getValue())); + typeField.selectByVisibleText("integer"); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.DEFAULT_VAL_FIELD.getValue()) + .sendKeys("2"); + // click ok + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.DONE_BUTTON.getValue()).click(); + Supplier supplier = () -> GeneralUIUtils.isElementPresent(newAttrName); + Function resultVerifier = isPresent -> isPresent; + Boolean isPresent = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The new attribute was not inserted to the attributes table.", isPresent); + } + + @Test + public void testUpdateTypeForAttributeOfVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceReqDetails importVfcResourceInUI = ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + VfVerificator.verifyResourceIsCreated(importVfcResourceInUI); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.ATTRIBUTES); + GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.AttributesSection.EDIT_BUTTON_FOR_NETWORK_ATTR.getValue()) + .click(); + // fill in fields + Select typeField = new Select( + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.TYPE_FIELD.getValue())); + typeField.selectByVisibleText("float"); + // click ok + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.AttributeForm.DONE_BUTTON.getValue()).click(); + Supplier supplier = () -> GeneralUIUtils.isElementPresent("float"); + Function resultVerifier = isPresent -> isPresent; + Boolean isPresent = FunctionalInterfaces.retryMethodOnResult(supplier, resultVerifier); + assertTrue("The attribute type was not updated.", isPresent); + } + + @Test + public void testDeleteAttributeForVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "VFCWithAttributes.yml"; + ResourceReqDetails importVfcResourceInUI = ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.ATTRIBUTES); + GeneralUIUtils + .getWebElementWaitForVisible(DataTestIdEnum.AttributesSection.DELETE_BUTTON_FOR_NETWORK_ATTR.getValue()) + .click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.waitForLoader(); + Boolean retryResult = FunctionalInterfaces + .retryMethodOnResult(() -> !GeneralUIUtils.isElementPresent("networks"), boolResult -> boolResult); + assertTrue("The attribute is shown in the attributes table.", retryResult); + } + + @Test + public void testImportVfc() { + String filePath = FileHandling.getResourcesFilesPath(); + String fileName = "CP.yml"; + ResourceReqDetails importVfcResourceInUI = ResourceUIUtils.importVfcInUI(getUser(), filePath, fileName); + assertTrue(RestCDUtils.getResource(importVfcResourceInUI).getErrorCode() == HttpStatus.SC_OK); + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java new file mode 100644 index 0000000000..25cf4749c5 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java @@ -0,0 +1,252 @@ +package org.openecomp.sdc.uici.tests.run; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.testng.TestNG; + +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utils.Utils; + +public class StartTest { + + public static long timeOfTest = 0; + + public static boolean debug = false; + + public static AtomicBoolean loggerInitialized = new AtomicBoolean(false); + + protected static Logger logger = null; + + public static void main(String[] args) { + // TODO ui-ci add jar building + String debugEnabled = System.getProperty("debug"); + if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) { + debug = true; + } + System.out.println("Debug mode is " + (debug ? "enabled" : "disabled")); + + enableLogger(); + + Config config = null; + try { + config = Utils.getConfig(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if (config == null) { + logger.error("Failed to configuration file of ci tests."); + System.exit(1); + } + + TestNG testng = new TestNG(); + + List suites = new ArrayList(); + suites.add("testSuites/" + args[0]); + testng.setTestSuites(suites); + // testng.setUseDefaultListeners(true); + testng.setOutputDirectory("target/"); + + testng.run(); + + } + + public StartTest() { + logger = Logger.getLogger(StartTest.class.getName()); + } + + public static void enableLogger() { + + if (false == loggerInitialized.get()) { + + loggerInitialized.set(true); + + String log4jPropsFile = System.getProperty("log4j.configuration"); + if (System.getProperty("os.name").contains("Windows")) { + String logProps = "src/main/resources/ci/conf/log4j.properties"; + if (log4jPropsFile == null) { + System.setProperty("targetlog", "target/"); + log4jPropsFile = logProps; + } + + } + PropertyConfigurator.configureAndWatch(log4jPropsFile); + + } + } + + private List getClassesForPackage(String pkgname) { + + List classes = new ArrayList(); + + // Get a File object for the package + File directory = null; + String fullPath; + String relPath = pkgname.replace('.', '/'); + + // System.out.println("ClassDiscovery: Package: " + pkgname + + // " becomes Path:" + relPath); + + URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); + + // System.out.println("ClassDiscovery: Resource = " + resource); + if (resource == null) { + throw new RuntimeException("No resource for " + relPath); + } + fullPath = resource.getFile(); + // System.out.println("ClassDiscovery: FullPath = " + resource); + + if (debug) { + System.out.println("fullPath is " + fullPath); + } + + try { + directory = new File(resource.toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException( + pkgname + " (" + resource + + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", + e); + } catch (IllegalArgumentException e) { + directory = null; + } + // System.out.println("ClassDiscovery: Directory = " + directory); + + if (directory != null && directory.exists()) { + + // Get the list of the files contained in the package + String[] files = directory.list(); + for (int i = 0; i < files.length; i++) { + + // we are only interested in .class files + if (files[i].endsWith(".class") && false == files[i].contains("$")) { + + // removes the .class extension + String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); + + // System.out.println("ClassDiscovery: className = " + + // className); + + if (debug) { + System.out.println("ClassDiscovery: className = " + className); + } + + try { + Class clas = Class.forName(className); + boolean isAddToRun = false; + Method[] methods = clas.getMethods(); + for (Method method : methods) { + Annotation[] anns = method.getAnnotations(); + for (Annotation an : anns) { + if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) { + isAddToRun = true; + break; + } + } + } + if (isAddToRun) + classes.add(clas); + } catch (ClassNotFoundException e) { + throw new RuntimeException("ClassNotFoundException loading " + className); + } + } + } + } else { + try { + String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); + + if (debug) { + System.out.println("jarPath is " + jarPath); + } + + JarFile jarFile = new JarFile(jarPath); + Enumeration entries = jarFile.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) { + + // System.out.println("ClassDiscovery: JarEntry: " + + // entryName); + String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); + + // System.out.println("ClassDiscovery: className = " + + // className); + + if (false == className.contains("$")) { + + if (debug) { + System.out.println("ClassDiscovery: className = " + className); + } + + try { + Class clas = Class.forName(className); + boolean isAddToRun = false; + Method[] methods = clas.getMethods(); + for (Method method : methods) { + Annotation[] anns = method.getAnnotations(); + for (Annotation an : anns) { + if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) { + isAddToRun = true; + break; + } + } + } + if (isAddToRun) + classes.add(clas); + } catch (ClassNotFoundException e) { + throw new RuntimeException("ClassNotFoundException loading " + className); + } + } + } + } + jarFile.close(); + + } catch (IOException e) { + throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); + } + } + return classes; + } + + private void addTableHead(StringBuilder results) { + results.append(""); + results.append("").append("Unit Test").append(""); + results.append("").append("Result").append(""); + results.append(""); + } + + // private void addUnitTestResult(StringBuilder results, + // Class testClass, Result unitTestResult) { + // + // boolean isSuccess = unitTestResult.wasSuccessful(); + // + // String result = (isSuccess) ? "success" : "fail"; + // String fileName = FileUtils.getFileName(testClass.getName()); + // results.append(""); + // // + // results.append("").append(FileUtils.getFileName(testClass.getName())).append(""); + // results.append("") + // .append("" + // + fileName + "").append(""); + // results.append("").append(result) + // .append(""); + // results.append(""); + // } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ArtifactUIUtils.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ArtifactUIUtils.java new file mode 100644 index 0000000000..91c9c07da8 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ArtifactUIUtils.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnException; + +import java.util.Map; + +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.Artifatcs; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.InformationalArtifatcs; +import org.openqa.selenium.WebElement; + +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +public final class ArtifactUIUtils { + + private ArtifactUIUtils() { + throw new UnsupportedOperationException(); + } + + public static void addInformationArtifact(ArtifactReqDetails artifact, String filePath, + final InformationalArtifatcs dataTestEnum) { + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.sleep(2000); + GeneralUIUtils.getWebElementWaitForVisible(dataTestEnum.getValue()).click(); + + final WebElement browseWebElement = FunctionalInterfaces.retryMethodOnException( + () -> GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue())); + browseWebElement.sendKeys(filePath); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.DESCRIPTION.getValue()) + .sendKeys(artifact.getDescription()); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.DONE.getValue()).click(); + + } + + public static Map> getArtifactsListFromResponse(String jsonResponse, + String fieldOfArtifactList) { + JSONObject object = (JSONObject) JSONValue.parse(jsonResponse); + Map> map = (Map>) object.get(fieldOfArtifactList); + return map; + } + + /** + * Creates a deployment artifact on the vf.
+ * Moves automatically to DeploymentArtifact Section + * + * @param artifactPayloadPath + * @param artifactType + */ + public static void createDeploymentArtifactOnVf(final String artifactPayloadPath, + final ArtifactTypeEnum artifactType) { + GeneralUIUtils.moveToStep(CreateAndUpdateStepsEnum.DEPLOYMENT_ARTIFACT); + GeneralUIUtils.getWebElementWaitForClickable(Artifatcs.ADD_DEPLOYMENT_ARTIFACT.getValue()).click(); + GeneralUIUtils.getSelectList("Create New Artifact", Artifatcs.SELECT_ARTIFACT_DROPDOWN.getValue()); + GeneralUIUtils.getSelectList(artifactType.getType(), Artifatcs.ARTIFACT_TYPE_DROPDOWN.getValue()); + GeneralUIUtils.getWebElementWaitForVisible(Artifatcs.ARTIFACT_DESCRIPTION.getValue()) + .sendKeys("Artifact Description"); + GeneralUIUtils.getWebElementWaitForVisible(Artifatcs.ARTIFACT_LABEL.getValue()).sendKeys("MyArtifactLabel"); + retryMethodOnException(() -> GeneralUIUtils.getWebElementByDataTestId(Artifatcs.BROWSE_BUTTON.getValue()) + .sendKeys(artifactPayloadPath)); + GeneralUIUtils.getWebElementWaitForVisible(Artifatcs.ADD_BUTTON.getValue()).click(); + GeneralUIUtils.waitForLoader(); + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/FileHandling.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/FileHandling.java new file mode 100644 index 0000000000..b1549741ed --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/FileHandling.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.Map; + +import org.yaml.snakeyaml.Yaml; + +public class FileHandling { + + public static Map parseYamlFile(String filePath) throws FileNotFoundException { + Yaml yaml = new Yaml(); + File file = new File(filePath); + InputStream inputStream = new FileInputStream(file); + Map map = (Map) yaml.load(inputStream); + return map; + } + + public static String getBasePath() { + return System.getProperty("user.dir"); + } + + public static String getResourcesFilesPath() { + return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator; + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java new file mode 100644 index 0000000000..42aab187ea --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java @@ -0,0 +1,344 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnException; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnResult; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.swallowException; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.openecomp.sdc.uici.tests.datatypes.CreateAndUpdateStepsEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.Dashboard; +import org.openecomp.sdc.uici.tests.execute.base.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.Platform; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.remote.RemoteWebDriver; +import org.openqa.selenium.support.ui.ExpectedCondition; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.Assert; + +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +public final class GeneralUIUtils { + + private static final int DEFAULT_WAIT_TIME_IN_SECONDS = 10; + /**************** DRIVERS ****************/ + private static WebDriver driver; + + private GeneralUIUtils() { + throw new UnsupportedOperationException(); + } + + /** + * Finding a component in the home screen by name and clicks on it + * Uses the search + * + * @param componentName + * @throws Exception + */ + public static void findComponentAndClick(String componentName) throws Exception { + getWebElementWaitForVisible("main-menu-input-search").sendKeys(componentName); + try { + getWebElementWaitForClickable(componentName).click(); + GeneralUIUtils.waitForLoader(); + getWebElementWaitForVisible("formlifecyclestate"); + } catch (Exception e) { + String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName); + System.out.println(msg); + Assert.fail(msg); + } + } + + public static WebElement getWebElementWaitForVisible(String dataTestId) { + return getWebElementWaitForVisible(dataTestId, DEFAULT_WAIT_TIME_IN_SECONDS); + } + + public static WebElement getWebElementWaitForVisible(String dataTestId, int time) { + WebDriverWait wait = new WebDriverWait(getDriver(), time); + ExpectedCondition visibilityOfElementLocated = ExpectedConditions + .visibilityOfElementLocated(builDataTestIdLocator(dataTestId)); + WebElement webElement = wait.until(visibilityOfElementLocated); + return webElement; + } + + public static WebElement getWebElementWaitForClickable(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), DEFAULT_WAIT_TIME_IN_SECONDS); + ExpectedCondition condition = ExpectedConditions + .elementToBeClickable(builDataTestIdLocator(dataTestId)); + WebElement webElement = wait.until(condition); + return webElement; + } + + private static By builDataTestIdLocator(String dataTestId) { + return By.xpath("//*[@data-tests-id='" + dataTestId + "']"); + + } + + /** + * Returns A list of Web Elements When they are all visible + * + * @param dataTestId + * @return + */ + public static List getWebElementsListWaitForVisible(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), DEFAULT_WAIT_TIME_IN_SECONDS); + ExpectedCondition> visibilityOfAllElementsLocatedBy = ExpectedConditions + .visibilityOfAllElementsLocatedBy(builDataTestIdLocator(dataTestId)); + return wait.until(visibilityOfAllElementsLocatedBy); + } + + /** + * @deprecated Do not use. use {@link #getWebElementWaitForVisible(String)} + * @param dataTestId + * @return + */ + public static WebElement getWebElementByDataTestId(String dataTestId) { + return driver.findElement(builDataTestIdLocator(dataTestId)); + } + + /** + * Checks if element is present with given dataTestsId + * + * @param dataTestId + * @return + */ + public static boolean isElementPresent(String dataTestId) { + final boolean isPresent = !driver.findElements(builDataTestIdLocator(dataTestId)).isEmpty(); + return isPresent; + } + + public static void clickOnCreateEntityFromDashboard(String buttonId) { + Supplier addVfButtonSipplier = () -> { + // TODO ui-ci replace with data-test-id + GeneralUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new"); + return GeneralUIUtils.getWebElementByDataTestId(buttonId); + }; + WebElement addVfButton = FunctionalInterfaces.retryMethodOnException(addVfButtonSipplier); + addVfButton.click(); + } + + // this function located select list by the data-test-id value and the item + // to be selected.. + public static Select getSelectList(String item, String dataTestId) { + Select selectlist = new Select(driver.findElement(builDataTestIdLocator(dataTestId))); + if (item != null) { + selectlist.selectByVisibleText(item); + } + return selectlist; + } + + // Define description area . + public static String defineDescription(String descriptionText) { + + WebElement resourceDescriptionTextbox = GeneralUIUtils.getWebElementWaitForVisible("description"); + resourceDescriptionTextbox.clear(); + resourceDescriptionTextbox.sendKeys(descriptionText); + + return descriptionText; + } + + /** + * Clicks on the create button waits for the create to finish and the check + * in button to appear + */ + public static void clickCreateButton() { + GeneralUIUtils.waitForLoader(); + getWebElementWaitForClickable(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue()).click(); + GeneralUIUtils.waitForLoader(); + closeNotificatin(); + getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.CHECK_IN.getValue()); + } + + public static void closeNotificatin() { + WebElement notification = driver.findElement(By.className("ui-notification")); + if (notification != null) { + notification.click(); + } + } + + public static void clickSaveButton() { + WebElement createButton = getWebElementWaitForClickable(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue()); + createButton.click(); + } + + public static void checkIn() { + waitForLoader(); + getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.CHECK_IN.getValue()).click(); + getWebElementWaitForVisible(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue()).sendKeys("Check in !"); + getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click(); + waitForLoader(); + } + + public static void moveToStep(CreateAndUpdateStepsEnum Stepname) { + waitForLoader(); + getWebElementWaitForClickable(Stepname.getValue()).click(); + waitForLoader(); + } + + public static void sleep(int duration) { + swallowException(() -> Thread.sleep(duration)); + } + + public static WebDriver getDriver() { + return driver; + } + + public static void initDriver() { + try { + System.out.println("opening browser"); + WebDriver webDriver; + boolean remoteTesting = SetupCDTest.config.isRemoteTesting(); + if (!remoteTesting) { + webDriver = new FirefoxDriver(); + } else { + String remoteEnvIP = SetupCDTest.config.getRemoteTestingMachineIP(); + String remoteEnvPort = SetupCDTest.config.getRemoteTestingMachinePort(); + DesiredCapabilities cap = new DesiredCapabilities(); + cap = DesiredCapabilities.firefox(); + cap.setPlatform(Platform.WINDOWS); + cap.setBrowserName("firefox"); + + String remoteNodeUrl = String.format(SetupCDTest.SELENIUM_NODE_URL, remoteEnvIP, remoteEnvPort); + webDriver = new RemoteWebDriver(new URL(remoteNodeUrl), cap); + + } + driver = webDriver; + + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + + } + + /** + * waits until either loader finishes or 10 seconds has passed.
+ * If 10 seconds has passed and loader didn't finish throws + * LoaderStuckException.
+ */ + public static void waitForLoader() { + waitForLoader(10); + } + + /** + * waits until either loader finishes or maxWaitTimeInSeconds has + * passed.
+ * If maxWaitTimeInSeconds has passed and loader didn't finish throws + * LoaderStuckException.
+ * + * @param maxWaitTimeInSeconds + */ + public static void waitForLoader(int maxWaitTimeInSeconds) { + long maxWaitTimeMS = maxWaitTimeInSeconds * 1000L; + Boolean loaderIsRunning = retryMethodOnResult( + () -> isElementPresent(DataTestIdEnum.GeneralSection.LOADER.getValue()), + isLoaderPresent -> !isLoaderPresent, maxWaitTimeMS, 50); + if (loaderIsRunning) { + throw new LoaderStuckException( + "UI Loader is stuck, max wait time of " + maxWaitTimeInSeconds + " seconds has passed."); + } + + } + + private static class LoaderStuckException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private LoaderStuckException(String message) { + super(message); + } + } + + /** + * Move to HTML element by class name. When moving to the HTML element, it + * will raise hover event. + * + * @param className + */ + public static void moveToHTMLElementByClassName(String className) { + Actions actions = new Actions(getDriver()); + final WebElement createButtonsArea = getDriver().findElement(By.className(className)); + actions.moveToElement(createButtonsArea).perform(); + } + + /** + * Move to HTML element by element id. When moving to the HTML element, it + * will raise hover event. + * + * @param className + */ + public static void moveToHTMLElementByDataTestId(String dataTestId) { + Actions actions = new Actions(getDriver()); + final WebElement createButtonsArea = getWebElementByDataTestId(dataTestId); + actions.moveToElement(createButtonsArea).perform(); + } + + public static void defineVendorName(String resourceVendorName) { + // TODO ui-ci replace with Enum + WebElement resourceVendorNameTextbox = getWebElementWaitForVisible("vendorName"); + resourceVendorNameTextbox.clear(); + resourceVendorNameTextbox.sendKeys(resourceVendorName); + } + + public static String defineUserId(String UserId) { + // TODO ui-ci replace with Enum + WebElement resourceTagsTextbox = getWebElementWaitForVisible("contactId"); + resourceTagsTextbox.clear(); + resourceTagsTextbox.sendKeys(UserId); + return UserId; + } + + public static void clickAddComponent(Dashboard componentType) { + Runnable clickAddTask = () -> { + // TODO ui-ci replace with data-test-id + moveToHTMLElementByClassName("w-sdc-dashboard-card-new"); + WebElement addVfButton = getWebElementByDataTestId(componentType.getValue()); + addVfButton.click(); + }; + retryMethodOnException(clickAddTask); + } + + /** + * This method perform submit for testing process for existing service or + * resource.
+ * It assumes it is activated when in the resource screen and the Submit For + * Testing button is available. + * + * @param componentNameForMessage + * TODO + */ + public static void submitForTestingElement(String componentNameForMessage) { + waitForLoader(); + getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.SUBMIT_FOR_TESTING.getValue()).click(); + waitForLoader(); + getWebElementWaitForVisible(DataTestIdEnum.ModalItems.SUMBIT_FOR_TESTING_MESSAGE.getValue()) + .sendKeys("Submit for testing for " + componentNameForMessage); + waitForLoader(); + getWebElementWaitForClickable(DataTestIdEnum.ModalItems.OK.getValue()).click(); + waitForLoader(); + waitForElementToDisappear(DataTestIdEnum.ModalItems.OK.getValue()); + + } + + /** + * Waits Until elements disappears or until 10 seconds pass + * + * @param dataTestId + */ + public static void waitForElementToDisappear(String dataTestId) { + Supplier elementPresenseChecker = () -> GeneralUIUtils.isElementPresent(dataTestId); + Function verifier = isElementPresent -> !isElementPresent; + FunctionalInterfaces.retryMethodOnResult(elementPresenseChecker, verifier); + + } + +} \ No newline at end of file diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/MethodManipulationUtils.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/MethodManipulationUtils.java new file mode 100644 index 0000000000..28b39e86f3 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/MethodManipulationUtils.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.uici.tests.utilities; + +/** + * Class For manipulations on method + * + * @author mshitrit + * + */ +public final class MethodManipulationUtils { + + private MethodManipulationUtils() { + throw new IllegalAccessError(); + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/OnboardUtility.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/OnboardUtility.java new file mode 100644 index 0000000000..3d21539e86 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/OnboardUtility.java @@ -0,0 +1,477 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import static org.testng.AssertJUnit.assertTrue; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +import javax.validation.constraints.AssertTrue; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONObject; +import org.junit.Test; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; + +import org.openecomp.sdc.ci.tests.config.Config; +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; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +/** + * Utility Class For Onboarding + * + * @author mshitrit + * + */ +public final class OnboardUtility { + + private OnboardUtility() { + throw new UnsupportedOperationException(); + } + + private static final class Constants { + private static final String VENDOR_SOFTWARE_PRODUCTS = "vendor-software-products"; + private static final String VENDOR_LICENSE_MODELS = "vendor-license-models"; + + private static final String VSP_ID = "vspId"; + private static final String VALUE = "value"; + + enum Actions { + CHECK_IN("Checkin"), SUBMIT("Submit"), CREATE_PACKAGE("Create_Package"); + + private String value; + + private Actions(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + }; + } + + /** + * @param heatFileName + * @param filepath + * @param userId + * @param vld + * @return + * @throws Exception + */ + public static void createVendorSoftwareProduct(String heatFileName, String filepath, String userId, + VendorLicenseDetails vld) { + RestResponse createNewVendorSoftwareProduct = FunctionalInterfaces + .swallowException(() -> createNewVendorSoftwareProduct(vld, userId)); + assertTrue(createNewVendorSoftwareProduct.getErrorCode() == HttpStatus.SC_OK); + String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), + Constants.VSP_ID); + + RestResponse response = FunctionalInterfaces + .swallowException(() -> uploadHeatPackage(filepath, heatFileName, vspid, userId)); + assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + + response = actionOnComponent(vspid, Constants.Actions.CHECK_IN.getValue(), Constants.VENDOR_SOFTWARE_PRODUCTS, + userId); + assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + + response = actionOnComponent(vspid, Constants.Actions.SUBMIT.getValue(), Constants.VENDOR_SOFTWARE_PRODUCTS, + userId); + assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + + response = actionOnComponent(vspid, Constants.Actions.CREATE_PACKAGE.getValue(), + Constants.VENDOR_SOFTWARE_PRODUCTS, userId); + assertTrue(response.getErrorCode() == HttpStatus.SC_OK); + + } + + /** + * Contains Details Relevant to Vendor License + * + * @author mshitrit + * + */ + public static final class VendorLicenseDetails { + private final String vendorId; + private final String vendorLicenseName; + private final String vendorLicenseAgreementId; + private final String featureGroupId; + private final String vendorSoftwareProduct; + + private VendorLicenseDetails(String vendorId, String vendorLicenseName, String vendorLicenseAgreementId, + String featureGroupId) { + super(); + this.vendorId = vendorId; + this.vendorLicenseName = vendorLicenseName; + this.vendorLicenseAgreementId = vendorLicenseAgreementId; + this.featureGroupId = featureGroupId; + vendorSoftwareProduct = UUID.randomUUID().toString().split("-")[0]; + } + + public String getVendorId() { + return vendorId; + } + + public String getVendorLicenseName() { + return vendorLicenseName; + } + + public String getVendorLicenseAgreementId() { + return vendorLicenseAgreementId; + } + + public String getFeatureGroupId() { + return featureGroupId; + } + + public String getVendorSoftwareProduct() { + return vendorSoftwareProduct; + } + + } + + /** + * Creates Vendor License + * + * @param userId + * @return + * @throws Exception + */ + public static VendorLicenseDetails createVendorLicense(String userId) { + final String fieldNameValue = Constants.VALUE; + String vendorLicenseName = UUID.randomUUID().toString().split("-")[0]; + RestResponse vendorLicenseResponse = FunctionalInterfaces + .swallowException(() -> createVendorLicenseModels(vendorLicenseName, userId)); + assertTrue(vendorLicenseResponse.getErrorCode() == HttpStatus.SC_OK); + + String vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), fieldNameValue); + + RestResponse vendorKeyGroupsResponse = FunctionalInterfaces + .swallowException(() -> createVendorKeyGroups(vendorId, userId)); + assertTrue(vendorKeyGroupsResponse.getErrorCode() == HttpStatus.SC_OK); + String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), + fieldNameValue); + + RestResponse vendorEntitlementPool = FunctionalInterfaces + .swallowException(() -> createVendorEntitlementPool(vendorId, userId)); + assertTrue(vendorEntitlementPool.getErrorCode() == HttpStatus.SC_OK); + String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), + fieldNameValue); + + RestResponse vendorLicenseFeatureGroups = FunctionalInterfaces.swallowException( + () -> createVendorLicenseFeatureGroups(vendorId, keyGroupId, entitlementPoolId, userId)); + assertTrue(vendorLicenseFeatureGroups.getErrorCode() == HttpStatus.SC_OK); + String featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), + fieldNameValue); + + RestResponse vendorLicenseAgreement = FunctionalInterfaces + .swallowException(() -> createVendorLicenseAgreement(vendorId, featureGroupId, userId)); + assertTrue(vendorLicenseAgreement.getErrorCode() == HttpStatus.SC_OK); + String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), + fieldNameValue); + + RestResponse actionOnComponent = actionOnComponent(vendorId, Constants.Actions.CHECK_IN.getValue(), + Constants.VENDOR_LICENSE_MODELS, userId); + assertTrue(actionOnComponent.getErrorCode() == HttpStatus.SC_OK); + + actionOnComponent = actionOnComponent(vendorId, Constants.Actions.SUBMIT.getValue(), + Constants.VENDOR_LICENSE_MODELS, userId); + assertTrue(actionOnComponent.getErrorCode() == HttpStatus.SC_OK); + + return new VendorLicenseDetails(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId); + } + + private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, String userId) { + Config config = FunctionalInterfaces.swallowException(() -> Utils.getConfig()); + String url = String.format("http://%s:%s/onboarding-api/v1.0/%s/%s/actions", config.getCatalogBeHost(), + config.getCatalogBePort(), onboardComponent, vspid); + + JSONObject jObject = new JSONObject(); + FunctionalInterfaces.swallowException(() -> jObject.put("action", action)); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = FunctionalInterfaces + .swallowException(() -> http.httpSendPut(url, jObject.toString(), headersMap)); + return response; + } + + private static RestResponse createVendorLicenseModels(String name, String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(), + config.getCatalogBePort()); + + JSONObject jObject = new JSONObject(); + jObject.put("vendorName", name); + jObject.put("description", "new vendor license model"); + jObject.put("iconRef", "icon"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + private static RestResponse createVendorLicenseAgreement(String vspid, String featureGroupId, String userId) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/license-agreements", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + JSONObject licenseTermpObject = new JSONObject(); + licenseTermpObject.put("choice", "Fixed_Term"); + licenseTermpObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "abc"); + jObjectBody.put("description", "new vendor license agreement"); + jObjectBody.put("requirementsAndConstrains", "abc"); + jObjectBody.put("licenseTerm", licenseTermpObject); + jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray()); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + private static RestResponse createVendorLicenseFeatureGroups(String vspid, String licenseKeyGroupId, + String entitlementPoolId, String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/feature-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + JSONObject jObject = new JSONObject(); + jObject.put("name", "xyz"); + jObject.put("description", "new vendor license feature groups"); + jObject.put("partNumber", "123abc456"); + jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray()); + jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray()); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + private static RestResponse createVendorEntitlementPool(String vspid, String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/entitlement-pools", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + JSONObject jEntitlementMetricObject = new JSONObject(); + jEntitlementMetricObject.put("choice", "CPU"); + jEntitlementMetricObject.put("other", ""); + + JSONObject jAggregationFunctionObject = new JSONObject(); + jAggregationFunctionObject.put("choice", "Peak"); + jAggregationFunctionObject.put("other", ""); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jTimeObject = new JSONObject(); + jTimeObject.put("choice", "Hour"); + jTimeObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "def"); + jObjectBody.put("description", "new vendor license entitlement pool"); + jObjectBody.put("thresholdValue", "23"); + jObjectBody.put("thresholdUnits", "Absolute"); + jObjectBody.put("entitlementMetric", jEntitlementMetricObject); + jObjectBody.put("increments", "abcd"); + jObjectBody.put("aggregationFunction", jAggregationFunctionObject); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("time", jTimeObject); + jObjectBody.put("manufacturerReferenceNumber", "123aaa"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + private static RestResponse createVendorKeyGroups(String vspid, String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/license-key-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Tenant").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "keyGroup"); + jObjectBody.put("description", "new vendor license key group"); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("type", "Universal"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + private static RestResponse createNewVendorSoftwareProduct(VendorLicenseDetails vld, String userId) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products", + config.getCatalogBeHost(), config.getCatalogBePort()); + + JSONObject jlicensingDataObj = new JSONObject(); + jlicensingDataObj.put("licenseAgreement", vld.getVendorLicenseAgreementId()); + jlicensingDataObj.put("featureGroups", Arrays.asList(vld.getFeatureGroupId()).toArray()); + + JSONObject jObject = new JSONObject(); + jObject.put("name", vld.getVendorSoftwareProduct()); + jObject.put("description", "new VSP description"); + jObject.put("category", "resourceNewCategory.generic"); + jObject.put("subCategory", "resourceNewCategory.generic.database"); + jObject.put("licensingVersion", "1.0"); + jObject.put("vendorName", vld.getVendorLicenseName()); + jObject.put("vendorId", vld.getVendorId()); + jObject.put("icon", "icon"); + jObject.put("licensingData", jlicensingDataObj); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + + return response; + } + + private static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, String userId) + throws Exception { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(filepath, filename))); + + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/upload", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + Map headersMap = prepareHeadersMap(userId); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data"); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + + Iterator iterator = headersMap.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + String value = headersMap.get(key); + httpPost.addHeader(key, value); + } + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static File getTestZipFile(String filepath, String filename) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); + return filePath.toFile(); + } + + protected static Map prepareHeadersMap(String userId) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + return headersMap; + } + + public static void createVfFromOnboarding(String userID, String zipFile, String filepath) { + VendorLicenseDetails vld = createVendorLicense(userID); + createVendorSoftwareProduct(zipFile, filepath, userID, vld); + + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.OPEN_MODAL_BUTTON.getValue()).click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.ONBOARDING_SEARCH.getValue()) + .sendKeys(vld.getVendorSoftwareProduct()); + + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.sleep(1000); + GeneralUIUtils.getWebElementWaitForClickable(vld.getVendorSoftwareProduct()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.IMPORT_ICON.getValue()).click(); + GeneralUIUtils.getWebElementWaitForClickable(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue()).click(); + GeneralUIUtils.waitForLoader(300); + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ResourceUIUtils.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ResourceUIUtils.java new file mode 100644 index 0000000000..149912944e --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ResourceUIUtils.java @@ -0,0 +1,299 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.Dashboard; +import org.openqa.selenium.By; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +public final class ResourceUIUtils { + public static final String RESOURCE_NAME_PREFIX = "ResourceCDTest-"; + protected static final boolean IS_BEFORE_TEST = true; + public static final String INITIAL_VERSION = "0.1"; + public static final String ICON_RESOURCE_NAME = "call_controll"; + protected static final String UPDATED_RESOURCE_ICON_NAME = "objectStorage"; + + private ResourceUIUtils() { + } + + public static void defineResourceName(String resourceName) { + + WebElement resourceNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("componentName")); + resourceNameTextbox.clear(); + resourceNameTextbox.sendKeys(resourceName); + } + + public static void defineResourceCategory(String category, String datatestsid) { + + GeneralUIUtils.getSelectList(category, datatestsid); + } + + public static void importFileWithSendKeyBrowse(String FilePath, String FileName) throws Exception { + WebElement browsebutton = GeneralUIUtils.getWebElementWaitForVisible("browseButton"); + browsebutton.sendKeys(FilePath + FileName); + } + + public static void defineTagsList(ResourceReqDetails resource, String[] resourceTags) { + List taglist = new ArrayList(); + ; + WebElement resourceTagsTextbox = GeneralUIUtils.getWebElementWaitForVisible("i-sdc-tag-input"); + for (String tag : resourceTags) { + resourceTagsTextbox.clear(); + resourceTagsTextbox.sendKeys(tag); + resourceTagsTextbox.sendKeys(Keys.ENTER); + taglist.add(tag); + } + resource.setTags(taglist); + } + + public static void defineVendorRelease(String resourceVendorRelease) { + + WebElement resourceVendorReleaseTextbox = GeneralUIUtils.getWebElementWaitForVisible("vendorRelease"); + resourceVendorReleaseTextbox.clear(); + resourceVendorReleaseTextbox.sendKeys(resourceVendorRelease); + } + + public static void defineProjectCode(String projectCode) { + + WebElement resourceNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("projectCode")); + resourceNameTextbox.clear(); + resourceNameTextbox.sendKeys(projectCode); + } + + public static void clickButton(String selectButton) { + + WebElement clickButton = GeneralUIUtils.getDriver() + .findElement(By.xpath("//*[@data-tests-id='" + selectButton + "']")); + clickButton.click(); + } + + public static WebElement Waitfunctionforbuttons(String element, int timeout) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout); + return wait.until(ExpectedConditions.elementToBeClickable(By.xpath(element))); + } + + // coded by teddy + public static void fillGeneralInformationPage(ResourceReqDetails resource, User user) { + try { + resource.setContactId(user.getUserId()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFullName()); + defineResourceName(resource.getName()); + defineResourceCategory(resource.getCategories().get(0).getSubcategories().get(0).getName(), + "selectGeneralCategory"); + GeneralUIUtils.defineDescription(resource.getDescription()); + GeneralUIUtils.defineVendorName(resource.getVendorName()); + defineVendorRelease(resource.getVendorRelease()); + defineTagsList(resource, new String[] { resource.getName() }); + GeneralUIUtils.defineUserId(resource.getCreatorUserId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static ResourceReqDetails createResourceInUI(User user) { + ResourceReqDetails defineResourceDetails = defineResourceDetails(); + GeneralUIUtils.clickAddComponent(DataTestIdEnum.Dashboard.BUTTON_ADD_VF); + + GeneralUIUtils.waitForLoader(); + fillGeneralInformationPage(defineResourceDetails, user); + GeneralUIUtils.clickCreateButton(); + return defineResourceDetails; + + } + + @SuppressWarnings("deprecation") + private static void openImportWithFile(String filePath, String fileName, Dashboard elementType) { + Runnable openImportTask = () -> { + GeneralUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue()); + WebElement imoprtVFButton = GeneralUIUtils.getWebElementByDataTestId(elementType.getValue()); + imoprtVFButton.sendKeys(filePath + fileName); + }; + retryMethodOnException(openImportTask); + + } + + public static ResourceReqDetails importVfcInUI(User user, String filePath, String fileName) { + ResourceReqDetails defineResourceDetails = defineResourceDetails(); + openImportWithFile(filePath, fileName, DataTestIdEnum.Dashboard.IMPORT_VFC_FILE); + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + fillGeneralInformationPage(defineResourceDetails, user); + GeneralUIUtils.clickCreateButton(); + return defineResourceDetails; + } + + /** + * Import VF + * + * @param user + * @param filePath + * @param fileName + * @return + */ + public static ResourceReqDetails importVfInUI(User user, String filePath, String fileName) { + ResourceReqDetails defineResourceDetails = defineResourceDetails(); + openImportWithFile(filePath, fileName, DataTestIdEnum.Dashboard.IMPORT_VF_FILE); + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + fillGeneralInformationPage(defineResourceDetails, user); + + GeneralUIUtils.clickSaveButton(); + + return defineResourceDetails; + } + + public static ResourceReqDetails importVfInUIWithoutCheckin(User user, String filePath, String fileName) { + ResourceReqDetails defineResourceDetails = defineResourceDetails(); + openImportWithFile(filePath, fileName, DataTestIdEnum.Dashboard.IMPORT_VF_FILE); + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + fillGeneralInformationPage(defineResourceDetails, user); + GeneralUIUtils.clickSaveButton(); + GeneralUIUtils.waitForLoader(40); + // String okButtonId=DataTestIdEnum.ModalItems.OK.getValue(); + // ResourceUIUtils.clickButton(okButtonId); + // ResourceUIUtils.Waitfunctionforbuttons("//*[@data-tests-id='"+okButtonId+"']",10); + // ResourceUIUtils.clickButton(okButtonId); + return defineResourceDetails; + } + + public static ResourceReqDetails importVfFromOnBoardingModalWithoutCheckin(User user, String fileName) { + ResourceReqDetails defineResourceDetails = defineResourceDetails(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.OPEN_MODAL_BUTTON.getValue()).click(); + GeneralUIUtils.getWebElementWaitForVisible(fileName).click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.IMPORT_ICON.getValue()).click(); + + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickSaveButton(); + GeneralUIUtils.waitForLoader(); + return defineResourceDetails; + } + + @SuppressWarnings("deprecation") + public static void updateVfCsar(String filePath, String fileName) { + retryMethodOnException( + () -> GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.GeneralSection.BROWSE_BUTTON.getValue()) + .sendKeys(filePath + fileName)); + GeneralUIUtils.clickSaveButton(); + GeneralUIUtils.waitForLoader(); + } + + public static void updateVfCsarFromOnBoarding() { + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.GeneralSection.BROWSE_BUTTON.getValue()).click(); + GeneralUIUtils.getWebElementsListWaitForVisible(DataTestIdEnum.OnBoardingTable.CSAR_ROW.getValue()).get(0) + .click(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.OnBoardingTable.UPDATE_ICON.getValue()).click(); + GeneralUIUtils.clickSaveButton(); + GeneralUIUtils.waitForLoader(); + } + + public static ResourceReqDetails defineResourceDetails() { + ResourceReqDetails resource = new ResourceReqDetails(); + resource = ElementFactory.getDefaultResource(NormativeTypesEnum.ROOT, + ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS); + resource.setVersion(INITIAL_VERSION); + resource.setIcon(ICON_RESOURCE_NAME); + resource.setResourceType(ResourceTypeEnum.VF.toString()); + resource.setName(getRandomComponentName(RESOURCE_NAME_PREFIX)); + + return resource; + } + + protected static String getRandomComponentName(String prefix) { + return prefix + new Random().nextInt(10000); + } + + public static ImmutablePair getRIPosition(ResourceReqDetails createResourceInUI, User user) { + GeneralUIUtils.sleep(1000); + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String xPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posX"); + String yPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posY"); + return new ImmutablePair(xPosPostDrag, yPosPostDrag); + + } + + public static void fillinDeploymentArtifactFormAndClickDone( + org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails details, String filePath) { + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ArtifactModal.LABEL.getValue()) + .sendKeys(details.getArtifactLabel()); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.DESCRIPTION.getValue()) + .sendKeys(details.getDescription()); + GeneralUIUtils.getSelectList(details.getArtifactType(), DataTestIdEnum.ArtifactModal.TYPE.getValue()); + retryMethodOnException(() -> GeneralUIUtils + .getWebElementByDataTestId(DataTestIdEnum.GeneralSection.BROWSE_BUTTON.getValue()).sendKeys(filePath)); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.DONE.getValue()).click(); + GeneralUIUtils.waitForLoader(); + } + + /** + * Tests and Accept resource or service + * + * @param createResourceInUI + */ + public static void testAndAcceptElement(ComponentReqDetails createResourceInUI) { + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(createResourceInUI.getName()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.START_TESTING.getValue()) + .click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue()) + .sendKeys("resource " + createResourceInUI.getName() + " tested successfuly"); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementToDisappear(DataTestIdEnum.ModalItems.OK.getValue()); + } + + /** + * Waits Until resource changed to requested lifeCycle State + * + * @param createResourceInUI + * @param requestedLifeCycleState + * @return + */ + public static Resource waitForState(ResourceReqDetails createResourceInUI, + LifecycleStateEnum requestedLifeCycleState) { + Supplier resourceGetter = () -> { + String resourceString = RestCDUtils.getResource(createResourceInUI).getResponse(); + return ResponseParser.convertResourceResponseToJavaObject(resourceString); + }; + Function verifier = res -> res.getLifecycleState() == requestedLifeCycleState; + return FunctionalInterfaces.retryMethodOnResult(resourceGetter, verifier); + + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/RestCDUtils.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/RestCDUtils.java new file mode 100644 index 0000000000..8b602e305d --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/RestCDUtils.java @@ -0,0 +1,167 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnResult; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.swallowException; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.apache.http.HttpStatus; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +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.rest.ProductRestUtils; +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; + +public class RestCDUtils { + + private static void setResourceUniqueIdAndUUID(ComponentReqDetails element, RestResponse getResourceResponse) { + element.setUniqueId(ResponseParser.getUniqueIdFromResponse(getResourceResponse)); + element.setUUID(ResponseParser.getUuidFromResponse(getResourceResponse)); + } + + public static RestResponse getResourceByNameAndVersionRetryOnFail(String userId, String resourceName, + String resourceVersion) { + Supplier resourceGetter = () -> swallowException( + () -> ResourceRestUtils.getResourceByNameAndVersion(userId, resourceName, resourceVersion)); + Function validator = restRes -> restRes.getErrorCode() == HttpStatus.SC_OK; + return retryMethodOnResult(resourceGetter, validator); + } + + public static RestResponse getResource(ResourceReqDetails resource) { + try { + System.out.println("trying to get resource"); + RestResponse getResourceResponse = null; + String reourceUniqueId = resource.getUniqueId(); + + if (reourceUniqueId != null) { + GeneralUIUtils.sleep(1000); + getResourceResponse = ResourceRestUtils.getResource(reourceUniqueId); + if (getResourceResponse.getErrorCode().intValue() == HttpStatus.SC_OK) { + System.out.println("succeeded to get resource"); + } + return getResourceResponse; + } + JSONObject getResourceJSONObject = null; + getResourceResponse = getResourceByNameAndVersionRetryOnFail(UserRoleEnum.ADMIN.getUserId(), + resource.getName(), resource.getVersion()); + if (getResourceResponse.getErrorCode().intValue() == HttpStatus.SC_OK) { + JSONArray jArray = new JSONArray(getResourceResponse.getResponse()); + for (int i = 0; i < jArray.length(); i++) { + getResourceJSONObject = jArray.getJSONObject(i); + String resourceType = ResponseParser.getValueFromJsonResponse(getResourceJSONObject.toString(), + "resourceType"); + if (resourceType.equals(resource.getResourceType())) { + getResourceResponse.setResponse(getResourceJSONObject.toString()); + setResourceUniqueIdAndUUID(resource, getResourceResponse); + System.out.println("succeeded to get resource"); + return getResourceResponse; + } + } + } + + return getResourceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static RestResponse getService(ServiceReqDetails service, User user) { + Supplier serviceFetcher = () -> swallowException( + () -> ServiceRestUtils.getServiceByNameAndVersion(user, service.getName(), service.getVersion())); + Function verifier = restResponse -> restResponse.getErrorCode() + .intValue() == HttpStatus.SC_OK; + RestResponse getServiceResponse = retryMethodOnResult(serviceFetcher, verifier); + + if (getServiceResponse.getErrorCode().intValue() == HttpStatus.SC_OK) { + setResourceUniqueIdAndUUID(service, getServiceResponse); + } + return getServiceResponse; + } + + public static RestResponse getProduct(ProductReqDetails product, User user) throws Exception { + Thread.sleep(3500); + RestResponse getProductResponse = ProductRestUtils.getProductByNameAndVersion(product.getName(), + product.getVersion(), user.getUserId()); + if (getProductResponse.getErrorCode().intValue() == 200) { + setResourceUniqueIdAndUUID(product, getProductResponse); + } + return getProductResponse; + } + + public static Map getAllElementVersionsFromResponse(RestResponse getResource) throws Exception { + Map versionsMap = new HashMap(); + try { + ObjectMapper mapper = new ObjectMapper(); + + JSONObject object = new JSONObject(getResource.getResponse()); + versionsMap = mapper.readValue(object.get("allVersions").toString(), Map.class); + + } catch (Exception e) { + e.printStackTrace(); + return versionsMap; + + } + + return versionsMap; + } + + public static void deleteElementVersions(Map elementVersions, boolean isBeforeTest, Object clazz, + User user) throws Exception { + Iterator iterator = elementVersions.keySet().iterator(); + while (iterator.hasNext()) { + String singleVersion = iterator.next(); + String uniqueId = elementVersions.get(singleVersion); + RestResponse deleteResponse = null; + if (clazz instanceof ServiceReqDetails) { + deleteResponse = ServiceRestUtils.deleteServiceById(uniqueId, user.getUserId()); + } else if (clazz instanceof ResourceReqDetails) { + deleteResponse = ResourceRestUtils.deleteResource(uniqueId, user.getUserId()); + } else if (clazz instanceof ProductReqDetails) { + deleteResponse = ProductRestUtils.deleteProduct(uniqueId, user.getUserId()); + } + + if (isBeforeTest) { + assertTrue(deleteResponse.getErrorCode().intValue() == 204 + || deleteResponse.getErrorCode().intValue() == 404); + } else { + assertTrue(deleteResponse.getErrorCode().intValue() == 204); + } + } + } + + public static void deleteAllResourceVersionsAfterTest(ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + deleteAllComponentVersion(false, componentDetails, getObjectResponse, user); + } + + public static void deleteAllResourceVersionsBeforeTest(ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + deleteAllComponentVersion(true, componentDetails, getObjectResponse, user); + } + + public static void deleteAllComponentVersion(boolean isBeforeTest, ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + if (getObjectResponse.getErrorCode().intValue() == 404) + return; + Map componentVersionsMap = getAllElementVersionsFromResponse(getObjectResponse); + System.out.println("deleting..."); + deleteElementVersions(componentVersionsMap, isBeforeTest, componentDetails, user); + componentDetails.setUniqueId(null); + } + +} \ No newline at end of file diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ServiceUIUtils.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ServiceUIUtils.java new file mode 100644 index 0000000000..0130b710a0 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ServiceUIUtils.java @@ -0,0 +1,147 @@ +package org.openecomp.sdc.uici.tests.utilities; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.uici.tests.datatypes.DataTestIdEnum.GeneralSection; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +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.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +public final class ServiceUIUtils { + + public static final String SERVICE_NAME_PREFIX = "ServiceCDTest-"; + public static final String INITIAL_VERSION = "0.1"; + public static final String ICON_SERVICE_NAME = "mobility"; + + private ServiceUIUtils() { + throw new UnsupportedOperationException(); + } + + public static String defineServiceName(String serviceName) { + WebElement serviceNameElement = GeneralUIUtils.getWebElementWaitForVisible(GeneralSection.NAME.getValue()); + serviceNameElement.clear(); + serviceNameElement.sendKeys(serviceName); + return serviceName; + } + + public static void defineTagsList(ServiceReqDetails service, String[] serviceTags) { + List taglist = new ArrayList(); + ; + WebElement serviceTagsTextbox = GeneralUIUtils.getWebElementWaitForVisible("i-sdc-tag-input"); + for (String tag : serviceTags) { + serviceTagsTextbox.clear(); + serviceTagsTextbox.sendKeys(tag); + serviceTagsTextbox.sendKeys(Keys.ENTER); + taglist.add(tag); + } + taglist.add(0, service.getName()); + service.setTags(taglist); + } + + public static Select defineServiceCategory(String category) { + + return GeneralUIUtils.getSelectList(category, "selectGeneralCategory"); + } + + private static void defineServiceProjectCode(String projectCode) { + WebElement attProjectCodeTextbox = GeneralUIUtils.getWebElementWaitForVisible("projectCode"); + attProjectCodeTextbox.clear(); + attProjectCodeTextbox.sendKeys(projectCode); + } + + private static void fillServiceGeneralPage(ServiceReqDetails service, User user) { + service.setContactId(user.getUserId()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFullName()); + defineServiceName(service.getName()); + defineServiceCategory(service.getCategories().get(0).getName()); + GeneralUIUtils.defineDescription(service.getDescription()); + defineTagsList(service, + new String[] { service.getName(), "This-is-tag", "another-tag", "Test-automation-tag" }); + GeneralUIUtils.defineUserId(service.getCreatorUserId()); + defineServiceProjectCode(service.getProjectCode()); + + } + + public static ServiceReqDetails createServiceInUI(User user) { + + ServiceReqDetails defineServiceetails = defineServiceDetails(user); + GeneralUIUtils.clickAddComponent(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE); + + GeneralUIUtils.waitForLoader(); + fillServiceGeneralPage(defineServiceetails, user); + + GeneralUIUtils.clickCreateButton(); + + return defineServiceetails; + + } + + public static ServiceReqDetails defineServiceDetails(User user) { + ServiceReqDetails service = new ServiceReqDetails(); + service = ElementFactory.getDefaultService(ServiceCategoriesEnum.MOBILITY, user); + service.setVersion(INITIAL_VERSION); + service.setIcon(ICON_SERVICE_NAME); + service.setName(getRandomComponentName(SERVICE_NAME_PREFIX)); + + return service; + } + + protected static String getRandomComponentName(String prefix) { + return prefix + new Random().nextInt(10000); + } + + /** + * Waits Until service changed to requested lifeCycle State + * + * @param createServiceInUI + * @param requestedLifeCycleState + * @param user + * @return + */ + public static Service waitForState(ServiceReqDetails createServiceInUI, LifecycleStateEnum requestedLifeCycleState, + User user) { + Supplier serviceGetter = () -> { + String resourceString = RestCDUtils.getService(createServiceInUI, user).getResponse(); + return ResponseParser.convertServiceResponseToJavaObject(resourceString); + }; + Function verifier = res -> res.getLifecycleState() == requestedLifeCycleState; + return FunctionalInterfaces.retryMethodOnResult(serviceGetter, verifier); + + } + + /** + * This Method Approves service for distribution
+ * It assumes governor role is already logged in + * + * @param createServiceInUI + */ + public static void approveServiceForDistribution(ServiceReqDetails createServiceInUI) { + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(createServiceInUI.getName()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.LifeCyleChangeButtons.APPROVE.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue()) + .sendKeys("Service " + createServiceInUI.getName() + " Approved For Distribution"); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementWaitForVisible(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementToDisappear(DataTestIdEnum.ModalItems.OK.getValue()); + } + +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/ServiceVerificator.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/ServiceVerificator.java new file mode 100644 index 0000000000..0306df0638 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/ServiceVerificator.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.uici.tests.verificator; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.function.Function; +import java.util.function.Supplier; + +import org.apache.http.HttpStatus; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.uici.tests.utilities.RestCDUtils; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +public class ServiceVerificator { + public static void verifyNumOfComponentInstances(ServiceReqDetails createServiceInUI, int numOfVFC, User user) { + String responseAfterDrag = RestCDUtils.getService(createServiceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + int size = ((JSONArray) jsonResource.get("componentInstances")).size(); + assertTrue(size == numOfVFC); + } + + public static void verifyLinkCreated(ServiceReqDetails createServiceInUI, User user) { + String responseAfterDrag = RestCDUtils.getService(createServiceInUI, user).getResponse(); + JSONObject jsonService = (JSONObject) JSONValue.parse(responseAfterDrag); + assertTrue(((JSONArray) jsonService.get("componentInstancesRelations")).size() == 1); + + } + + public static void verifyServiceCreated(ServiceReqDetails createServiceInUI, User user) { + assertTrue(RestCDUtils.getService(createServiceInUI, user).getErrorCode() == HttpStatus.SC_OK); + + } + + /** + * Verifies service is certified with version 1.0 + * + * @param createServiceInUI + * @param user + */ + public static void verifyServiceCertified(ServiceReqDetails createServiceInUI, User user) { + Supplier serviceGetter = () -> FunctionalInterfaces.swallowException( + () -> ServiceRestUtils.getServiceByNameAndVersion(user, createServiceInUI.getName(), "1.0")); + Function serviceVerificator = restResp -> restResp.getErrorCode() == HttpStatus.SC_OK; + RestResponse certifiedResourceResopnse = FunctionalInterfaces.retryMethodOnResult(serviceGetter, + serviceVerificator); + assertTrue(certifiedResourceResopnse.getErrorCode() == HttpStatus.SC_OK); + + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VerificatorUtil.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VerificatorUtil.java new file mode 100644 index 0000000000..9e983b44d3 --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VerificatorUtil.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.uici.tests.verificator; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.function.Function; +import java.util.function.Supplier; + +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +/** + * Util Class For Verificators + * + * @author mshitrit + * + */ +public final class VerificatorUtil { + + private VerificatorUtil() { + throw new IllegalAccessError(); + } + + public static void verifyWithRetry(Supplier verificator) { + Function retryVerificationLogic = isVerified -> isVerified; + Boolean isVerifiedAfterRetries = FunctionalInterfaces.retryMethodOnResult(verificator, retryVerificationLogic); + assertTrue(isVerifiedAfterRetries); + } +} diff --git a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VfVerificator.java b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VfVerificator.java new file mode 100644 index 0000000000..a1c7ca002b --- /dev/null +++ b/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VfVerificator.java @@ -0,0 +1,143 @@ +package org.openecomp.sdc.uici.tests.verificator; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.http.HttpStatus; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.uici.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.uici.tests.utilities.RestCDUtils; + +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +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.rest.ResponseParser; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; + +/** + * Class to hold Test Verifications relevant for VF + * + * @author mshitrit + * + */ +public final class VfVerificator { + private VfVerificator() { + throw new UnsupportedOperationException(); + } + + /** + * Verifies that the resource contains a certain number of component + * instances + * + * @param createResourceInUI + * @param numOfVFC + */ + public static void verifyNumOfComponentInstances(ResourceReqDetails createResourceInUI, int numOfVFC) { + Supplier verificator = () -> { + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + int size = ((JSONArray) jsonResource.get("componentInstances")).size(); + return size == numOfVFC; + }; + VerificatorUtil.verifyWithRetry(verificator); + } + + /** + * Verifies That the createResourceInUI is different that prevRIPos. + * + * @param createResourceInUI + * @param prevRIPos + * @param user + */ + public static void verifyRILocationChanged(ResourceReqDetails createResourceInUI, + ImmutablePair prevRIPos, User user) { + Supplier verificator = () -> { + ImmutablePair currRIPos = ResourceUIUtils.getRIPosition(createResourceInUI, user); + final boolean isXLocationChanged = !prevRIPos.left.equals(currRIPos.left); + final boolean isYLocationChange = !prevRIPos.right.equals(currRIPos.right); + return isXLocationChanged || isYLocationChange; + }; + VerificatorUtil.verifyWithRetry(verificator); + } + + /** + * Verifies That resource contains two connected instances + * + * @param createResourceInUI + */ + public static void verifyLinkCreated(ResourceReqDetails createResourceInUI) { + Supplier verificator = () -> { + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + return ((JSONArray) jsonResource.get("componentInstancesRelations")).size() == 1; + }; + VerificatorUtil.verifyWithRetry(verificator); + + } + + /** + * Verifies That the VF is certified to version 1.0 + * + * @param vfToVerify + */ + public static void verifyResourceIsCertified(ResourceReqDetails vfToVerify) { + RestResponse certifiedResourceResopnse = RestCDUtils + .getResourceByNameAndVersionRetryOnFail(UserRoleEnum.ADMIN.getUserId(), vfToVerify.getName(), "1.0"); + assertTrue(certifiedResourceResopnse.getErrorCode().equals(HttpStatus.SC_OK)); + + } + + /** + * Verifies That the VF exist + * + * @param vfToVerify + */ + public static void verifyResourceIsCreated(ResourceReqDetails vfToVerify) { + assertTrue(RestCDUtils.getResource(vfToVerify).getErrorCode() == HttpStatus.SC_OK); + } + + /** + * Verify the resource contains the deployment artifacts in the list + * + * @param vfToVerify + * @param artifactTypeEnums + */ + public static void verifyResourceContainsDeploymentArtifacts(ResourceReqDetails vfToVerify, + List artifactTypeEnums) { + String resourceString = RestCDUtils.getResource(vfToVerify).getResponse(); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceString); + List foundArtifacts = new ArrayList<>(); + if (resource.getDeploymentArtifacts() != null) { + foundArtifacts = resource.getDeploymentArtifacts().values().stream() + .map(artifact -> artifact.getArtifactType()).collect(Collectors.toList()); + } + List excpectedArtifacts = artifactTypeEnums.stream().map(e -> e.getType()).collect(Collectors.toList()); + assertTrue(foundArtifacts.containsAll(excpectedArtifacts)); + + } + + /** + * Verifies The life cycle State of the resource + * + * @param createResourceInUI + * @param requestedLifeCycleState + */ + public static void verifyState(ResourceReqDetails createResourceInUI, LifecycleStateEnum requestedLifeCycleState) { + Resource resource = ResourceUIUtils.waitForState(createResourceInUI, requestedLifeCycleState); + assertTrue(resource.getLifecycleState() == requestedLifeCycleState); + + } + +} diff --git a/ui-ci-dev/src/main/resources/ci/conf/attsdc-packages.yaml b/ui-ci-dev/src/main/resources/ci/conf/attsdc-packages.yaml new file mode 100644 index 0000000000..dcb78eefc1 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/conf/attsdc-packages.yaml @@ -0,0 +1,2 @@ +packages: + - org.openecomp.sdc.ci.tests.execute.resourceui \ No newline at end of file diff --git a/ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml b/ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml new file mode 100644 index 0000000000..8cd8068d08 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml @@ -0,0 +1,80 @@ +outputFolder: target +reportName: index.html +catalogBeHost: behost +catalogFeHost: fehost +esHost: eshost +disributionClientHost: disClient +catalogFePort: 8181 +catalogBePort: 8080 +disributionClientPort: 8181 +esPort: 9200 +neoHost: neoHost +neoPort: 7474 +neoDBusername: neo4j +neoDBpassword: 123456 +url: http://localhost:8181/sdc1/proxy-designer1#/dashboard +webSealSimulatorUrl: http://localhost:8285/sdc1 +remoteTestingMachineIP: localhost +remoteTestingMachinePort: 5555 +remoteTesting: false + +resourceConfigDir: src/test/resources/CI/tests +componentsConfigDir: src/test/resources/CI/components +importResourceConfigDir: ../catalog-be/src/main/resources/import/tosca/capability-types +importResourceTestsConfigDir: src/test/resources/CI/importResourceTests +errorConfigurationFile: ../catalog-be/src/main/resources/config/error-configuration.yaml +configurationFile: ../catalog-be/src/main/resources/config/configuration.yaml +importTypesConfigDir: src/test/resources/CI/importTypesTest + + +titanPropertiesFile: src/main/resources/ci/conf/titan.properties +cassandraHost: 127.0.0.1 +cassandraAuthenticate: false +cassandraUsername: koko +cassandraPassword: bobo +cassandraSsl: false +cassandraTruststorePath : /path/path +cassandraTruststorePassword : 123123 +cassandraAuditKeySpace: sdcaudit +cassandraArtifactKeySpace: sdcartifact + +stopOnClassFailure: false + +#List of non-abstract resources to keep during titan cleanup between tests +#Only 1.0 version will be kept +resourcesNotToDelete: + - Compute + - Database + - ObjectStorage + - BlockStorage + - LoadBalancer + - Port + - Network + - Root + - ContainerApplication + - ContainerRuntime + - DBMS + - SoftwareComponent + - WebApplication + - WebServer + - CinderVolume + - ContrailVirtualNetwork + - NeutronNet + - NeutronPort + - NovaServer +#Resource categories to keep (including all their subcategories) +resourceCategoriesNotToDelete: + - Generic + - Network L2-3 + - Network L4+ + - Application L4+ + - Network Connectivity + - Template + - Allotted Resource + +#Service categories to keep +serviceCategoriesNotToDelete: + - Mobility + - Network L1-3 + - Network L4 + - VoIP Call Control \ No newline at end of file diff --git a/ui-ci-dev/src/main/resources/ci/conf/credentials.yaml b/ui-ci-dev/src/main/resources/ci/conf/credentials.yaml new file mode 100644 index 0000000000..63a4280264 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/conf/credentials.yaml @@ -0,0 +1,48 @@ + designer: { + username: m99121, + password: 66-Percent, + firstname: ASDC, + lastname: KASPIN + } + admin: { + username: m99122, + password: 98-Degrees, + firstname: ASDC, + lastname: KASPIN + } + ops: { + username: m99123, + password: 17-Diameter, + firstname: ASDC, + lastname: KASPIN + } + tester: { + username: m99124, + password: 802-NotaGroup, + firstname: ASDC, + lastname: KASPIN + } + governor: { + username: m99125, + password: 142-Officiant, + firstname: ASDC, + lastname: KASPIN + } + product_strategist: { + username: m99126, + password: 1910-FruitGum, + firstname: ASDC, + lastname: KASPIN + } + product_manager: { + username: m99127, + password: 747-Airplane, + firstname: ASDC, + lastname: KASPIN + } + product_local: { + username: pm0001, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } \ No newline at end of file diff --git a/ui-ci-dev/src/main/resources/ci/conf/log4j.properties b/ui-ci-dev/src/main/resources/ci/conf/log4j.properties new file mode 100644 index 0000000000..3e159ec8df --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/conf/log4j.properties @@ -0,0 +1,34 @@ +# Define the root logger with appender file +log4j.rootLogger = DEBUG, FILE, stdout + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender +log4j.appender.FILE.File=${targetlog}logs/ci-log.out + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%10c] : %m%n + +# Set the maximum file size before rollover +log4j.appender.FILE.maxFileSize=5MB + +# Set the the backup index +log4j.appender.FILE.maxBackupIndex=10 + + +############################################################# + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n + +log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG +log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout + +log4j.logger.org.openecomp.sdc.ci.tests.utils=TRACE, FILE, stdout +log4j.additivity.org.openecomp.sdc.ci.tests.utils=false + + diff --git a/ui-ci-dev/src/main/resources/ci/conf/titan.properties b/ui-ci-dev/src/main/resources/ci/conf/titan.properties new file mode 100644 index 0000000000..94d12cfba0 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/conf/titan.properties @@ -0,0 +1,7 @@ +storage.backend=cassandra +storage.hostname=cassandrahost +storage.port=9160 + +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 \ No newline at end of file diff --git a/ui-ci-dev/src/main/resources/ci/scripts/startTest.sh b/ui-ci-dev/src/main/resources/ci/scripts/startTest.sh new file mode 100644 index 0000000000..cc58bc22c5 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/scripts/startTest.sh @@ -0,0 +1,123 @@ +#!/bin/bash + +TOMCAT_DIR=/home/apache-tomcat-7.0.41/webapps/sdc-ci + +function usage { + echo "Usage: $0 " +} + +function exitOnError() { + if [ $1 -ne 0 ] + then + echo "Failed running task $2" + exit 2 + fi +} + +if [ $# -lt 1 ] +then + usage + exit 2 +fi + +CURRENT_DIR=`pwd` +BASEDIR=$(dirname $0) + +if [ ${BASEDIR:0:1} = "/" ] +then + FULL_PATH=$BASEDIR +else + FULL_PATH=$CURRENT_DIR/$BASEDIR +fi + +LOGS_PROP_FILE=file:${FULL_PATH}/../conf/log4j.properties +############################################# +TARGET_DIR=${FULL_PATH}/../target +TARGET_LOG_DIR="${TARGET_DIR}/" +CONF_FILE=${FULL_PATH}/../conf/attsdc.yaml +DEBUG=true +MainClass=org.openecomp.sdc.ci.tests.run.StartTest + +JAR_FILE=$1 + +#TARGET_DIR=`echo ${TARGET_DIR} | sed 's/\//\//g'` +#echo $TARGET_DIR + +TESTS_DIR=/opt/app/sdc/ci/resources/tests +COMPONENTS_DIR=/opt/app/sdc/ci/resources/components + + +sed -i 's#\(outputFolder:\).*#\1 '${TARGET_DIR}'#g' $CONF_FILE +sed -i 's#\(resourceConfigDir:\).*#\1 '${TESTS_DIR}'#g' $CONF_FILE +sed -i 's#\(componentsConfigDir:\).*#\1 '${COMPONENTS_DIR}'#g' $CONF_FILE + + + +mkdir -p ${TARGET_DIR} +if [ -d ${TARGET_DIR} ] +then + rm -rf ${TARGET_DIR}/* + exitOnError $? "Failed_to_delete_target_dir" +fi + + +debug_port=8800 +#JAVA_OPTION="-javaagent:/var/tmp/jacoco/lib/jacocoagent.jar=destfile=jacoco-it.exec" +JAVA_OPTION="" +case "$2" in + -debug) echo "Debug mode, Listen on port $debug_port"; JAVA_OPTION="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${debug_port}" ;; + "") echo "Standard mode";; + *) echo "USAGE: startTest.sh [-debug]";; +esac + +#cmd="java $JAVA_OPTION -Dconfig.resource=attodlit.conf -Dlog4j.configuration=file:./conf/log4j.properties -cp #att-odl-it_0.0.1-SNAPSHOT-jar-with-dependencies.jar org.openecomp.d2.it.StartTest" + +#cmd="java $JAVA_OPTION -Dconfig.resource=attsdc.conf -Ddebug=true -Dlog4j.configuration=file:./conf/log4j.properties -cp uber-ci-1.0.0-SNAPSHOT.jar org.openecomp.sdc.ci.tests.run.StartTest" + + +cmd="java $JAVA_OPTION -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass}" + +#echo $cmd +#console=`$cmd` + + + +if [ $DEBUG == "true" ] +then + $cmd +else + $cmd >> /dev/null +fi +status=`echo $?` + +#echo "console=$console" +#echo "status=$status" +#tomcat=`ps -ef | grep tomcat | grep java | wc -l` + +#if [ $tomcat == 0 ]; then +# echo "Bring tomcat up" +# apache-tomcat-7.0.41/bin/startup.sh +#fi + +#`rm -rf ./html/*.html` +#`mv *.html ./html/` + + +if [ -d ${TOMCAT_DIR} ] +then + + cp ${TARGET_DIR}/*.html ${TOMCAT_DIR} + mv ${TOMCAT_DIR}/SDC-testReport.html ${TOMCAT_DIR}/index.html +fi + +#echo "tomcat=$tomcat" +#ip=`ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p' | grep 172.20` + +#echo "Report url: http://$ip:8090/att-odl-it/" + +echo "##################################################" +echo "################# status is $status " +echo "##################################################" + +exit $status + diff --git a/ui-ci-dev/src/main/resources/ci/testSuites/fullTests.xml b/ui-ci-dev/src/main/resources/ci/testSuites/fullTests.xml new file mode 100644 index 0000000000..9f912e58b8 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/testSuites/fullTests.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml b/ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml new file mode 100644 index 0000000000..99e8765038 --- /dev/null +++ b/ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ci-dev/src/main/resources/images/gizmorambo.jpg b/ui-ci-dev/src/main/resources/images/gizmorambo.jpg new file mode 100644 index 0000000000..c9a8fe8a64 Binary files /dev/null and b/ui-ci-dev/src/main/resources/images/gizmorambo.jpg differ diff --git a/ui-ci-dev/src/test/Completetheform.js b/ui-ci-dev/src/test/Completetheform.js new file mode 100644 index 0000000000..7e8b7572cc --- /dev/null +++ b/ui-ci-dev/src/test/Completetheform.js @@ -0,0 +1,3 @@ +/** + * New node file + */ diff --git a/ui-ci/.gitignore b/ui-ci/.gitignore new file mode 100644 index 0000000000..6405eb7c05 --- /dev/null +++ b/ui-ci/.gitignore @@ -0,0 +1,2 @@ +/bin/ +test-output/ \ No newline at end of file diff --git a/ui-ci/hs_err_pid10052.log b/ui-ci/hs_err_pid10052.log new file mode 100644 index 0000000000..3475f9250a --- /dev/null +++ b/ui-ci/hs_err_pid10052.log @@ -0,0 +1,389 @@ +# +# A fatal error has been detected by the Java Runtime Environment: +# +# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006f70a0a5, pid=10052, tid=0x0000000000001f50 +# +# JRE version: Java(TM) SE Runtime Environment (8.0_101-b13) (build 1.8.0_101-b13) +# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.101-b13 mixed mode windows-amd64 compressed oops) +# Problematic frame: +# V [jvm.dll+0x12a0a5] +# +# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows +# +# If you would like to submit a bug report, please visit: +# http://bugreport.java.com/bugreport/crash.jsp +# + +--------------- T H R E A D --------------- + +Current thread (0x000000001d458800): JavaThread "JDWP Transport Listener: dt_socket" daemon [_thread_in_vm, id=8016, stack(0x000000001e150000,0x000000001e250000)] + +siginfo: ExceptionCode=0xc0000005, reading address 0xffffffffffffffff + +Registers: +RAX=0x000000001e24f201, RBX=0x000000001d458800, RCX=0x293b676e69727453, RDX=0x0000000000000000 +RSP=0x000000001e24f290, RBP=0x293b676e69727453, RSI=0x000000001e24f3a8, RDI=0x000000000237c720 +R8 =0x000000001d458800, R9 =0x000000000000ff00, R10=0x0000000000000000, R11=0x004e596502bc0041 +R12=0x0000000000000000, R13=0x000000001d451788, R14=0x0000000000000000, R15=0x0000000000000000 +RIP=0x000000006f70a0a5, EFLAGS=0x0000000000010206 + +Top of Stack: (sp=0x000000001e24f290) +0x000000001e24f290: 000000001d458800 000000001fbdbe40 +0x000000001e24f2a0: 000000001e24f358 000000006f912f0b +0x000000001e24f2b0: 000000001d458800 000000006f92f76d +0x000000001e24f2c0: 0000000000000000 0000000055559155 +0x000000001e24f2d0: 000000001f30efd8 000000005556291e +0x000000001e24f2e0: 000000001d458800 0000000000000000 +0x000000001e24f2f0: 0000000000000000 0000000000000000 +0x000000001e24f300: 293b676e69727453 0000000055561a15 +0x000000001e24f310: 000000001e24f3a8 000000001e24f380 +0x000000001e24f320: 0000000000000001 000000001f30efd8 +0x000000001e24f330: 293b676e69727453 00000000555453b3 +0x000000001e24f340: 000000001e24f470 0000000000000001 +0x000000001e24f350: 0000000000000001 000000001f30efd8 +0x000000001e24f360: 00000000f000100a 0000000000000000 +0x000000001e24f370: 0000000000000000 0000000000000000 +0x000000001e24f380: 0000000000000001 0000000055545571 + +Instructions: (pc=0x000000006f70a0a5) +0x000000006f70a085: cc cc cc cc cc cc cc cc cc cc cc 48 83 ec 28 48 +0x000000006f70a095: 85 c9 75 07 33 c0 48 83 c4 28 c3 48 89 5c 24 20 +0x000000006f70a0a5: 48 8b 19 48 85 db 74 20 48 83 fb 37 74 1a 48 8b +0x000000006f70a0b5: 13 48 8b cb ff 52 10 84 c0 74 0d 48 8b c3 48 8b + + +Register to memory mapping: + +RAX=0x000000001e24f201 is pointing into the stack for thread: 0x000000001d458800 +RBX=0x000000001d458800 is a thread +RCX=0x293b676e69727453 is an unknown value +RDX=0x0000000000000000 is an unknown value +RSP=0x000000001e24f290 is pointing into the stack for thread: 0x000000001d458800 +RBP=0x293b676e69727453 is an unknown value +RSI=0x000000001e24f3a8 is pointing into the stack for thread: 0x000000001d458800 +RDI=0x000000000237c720 is an unknown value +R8 =0x000000001d458800 is a thread +R9 =0x000000000000ff00 is an unknown value +R10=0x0000000000000000 is an unknown value +R11=0x004e596502bc0041 is an unknown value +R12=0x0000000000000000 is an unknown value +R13=0x000000001d451788 is an unknown value +R14=0x0000000000000000 is an unknown value +R15=0x0000000000000000 is an unknown value + + +Stack: [0x000000001e150000,0x000000001e250000], sp=0x000000001e24f290, free space=1020k +Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) +V [jvm.dll+0x12a0a5] +V [jvm.dll+0x34f76d] +C [jdwp.dll+0x21a15] +C [jdwp.dll+0x53b3] +C [jdwp.dll+0x5571] +C [jdwp.dll+0xf0a8] +C [jdwp.dll+0x1f2d5] +C [jdwp.dll+0x1f4aa] +V [jvm.dll+0x1bd258] +V [jvm.dll+0x2451a4] +V [jvm.dll+0x29c18a] +C [msvcr100.dll+0x21d9f] +C [msvcr100.dll+0x21e3b] +C [kernel32.dll+0x159cd] +C [ntdll.dll+0x2a2e1] + + +--------------- P R O C E S S --------------- + +Java Threads: ( => current thread ) + 0x000000001f2a0000 JavaThread "Thread-25" daemon [_thread_in_native, id=11400, stack(0x0000000024be0000,0x0000000024ce0000)] + 0x000000001f29f000 JavaThread "Thread-24" daemon [_thread_in_native, id=1112, stack(0x00000000243d0000,0x00000000244d0000)] + 0x000000001f29e800 JavaThread "Thread-23" [_thread_in_native, id=2452, stack(0x0000000022cc0000,0x0000000022dc0000)] + 0x000000001f93d000 JavaThread "ReaderThread" [_thread_in_native, id=11720, stack(0x0000000021250000,0x0000000021350000)] + 0x000000001d4e8800 JavaThread "Service Thread" daemon [_thread_blocked, id=10596, stack(0x000000001e6f0000,0x000000001e7f0000)] + 0x000000001d474800 JavaThread "C1 CompilerThread2" daemon [_thread_blocked, id=8028, stack(0x000000001e3d0000,0x000000001e4d0000)] + 0x000000001d471000 JavaThread "C2 CompilerThread1" daemon [_thread_blocked, id=5140, stack(0x000000001e4f0000,0x000000001e5f0000)] + 0x000000001d46d000 JavaThread "C2 CompilerThread0" daemon [_thread_blocked, id=12216, stack(0x000000001dd90000,0x000000001de90000)] + 0x000000001d45f800 JavaThread "JDWP Command Reader" daemon [_thread_in_native, id=7520, stack(0x000000001e2d0000,0x000000001e3d0000)] + 0x000000001d45e000 JavaThread "JDWP Event Helper Thread" daemon [_thread_blocked, id=2652, stack(0x000000001df60000,0x000000001e060000)] +=>0x000000001d458800 JavaThread "JDWP Transport Listener: dt_socket" daemon [_thread_in_vm, id=8016, stack(0x000000001e150000,0x000000001e250000)] + 0x000000001d444800 JavaThread "Attach Listener" daemon [_thread_blocked, id=7364, stack(0x000000001d200000,0x000000001d300000)] + 0x000000001bfff000 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=9460, stack(0x000000001d850000,0x000000001d950000)] + 0x000000001bfe6800 JavaThread "Finalizer" daemon [_thread_blocked, id=7944, stack(0x000000001d340000,0x000000001d440000)] + 0x000000001bf9d000 JavaThread "Reference Handler" daemon [_thread_blocked, id=6028, stack(0x000000001d080000,0x000000001d180000)] + 0x0000000002381000 JavaThread "main" [_thread_blocked, id=12148, stack(0x0000000002480000,0x0000000002580000)] + +Other Threads: + 0x000000001bf95800 VMThread [stack: 0x000000001cf80000,0x000000001d080000] [id=8456] + 0x000000001d537000 WatcherThread [stack: 0x000000001e840000,0x000000001e940000] [id=5808] + +VM state:not at safepoint (normal execution) + +VM Mutex/Monitor currently owned by a thread: None + +Heap: + PSYoungGen total 144896K, used 11229K [0x000000076c700000, 0x0000000776d80000, 0x00000007c0000000) + eden space 143360K, 6% used [0x000000076c700000,0x000000076d087050,0x0000000775300000) + from space 1536K, 95% used [0x0000000775d00000,0x0000000775e70540,0x0000000775e80000) + to space 9216K, 0% used [0x0000000776480000,0x0000000776480000,0x0000000776d80000) + ParOldGen total 93184K, used 6916K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5ac1178,0x00000006caf00000) + Metaspace used 26524K, capacity 27092K, committed 27264K, reserved 1073152K + class space used 3209K, capacity 3367K, committed 3456K, reserved 1048576K + +Card table byte_map: [0x0000000011cf0000,0x00000000124d0000] byte_map_base: 0x000000000e6c6000 + +Marking Bits: (ParMarkBitMap*) 0x000000006fdfa6d0 + Begin Bits: [0x00000000130c0000, 0x0000000016f70000) + End Bits: [0x0000000016f70000, 0x000000001ae20000) + +Polling page: 0x0000000000370000 + +CodeCache: size=245760Kb used=14912Kb max_used=14912Kb free=230848Kb + bounds [0x0000000002930000, 0x00000000037d0000, 0x0000000011930000] + total_blobs=4013 nmethods=3595 adapters=338 + compilation: enabled + +Compilation events (10 events): +Event: 131.300 Thread 0x000000001d474800 4189 ! 3 com.google.gson.JsonParser::parse (100 bytes) +Event: 131.302 Thread 0x000000001d474800 nmethod 4189 0x00000000037cce10 code [0x00000000037cd120, 0x00000000037ceb08] +Event: 131.303 Thread 0x000000001d474800 4190 ! 3 com.google.gson.internal.Streams::parse (68 bytes) +Event: 131.304 Thread 0x000000001d474800 nmethod 4190 0x00000000037a77d0 code [0x00000000037a79e0, 0x00000000037a81d8] +Event: 131.304 Thread 0x000000001d474800 4191 3 com.google.gson.internal.bind.TypeAdapters$25::read (6 bytes) +Event: 131.304 Thread 0x000000001d474800 nmethod 4191 0x00000000037a7390 code [0x00000000037a7500, 0x00000000037a7728] +Event: 131.313 Thread 0x000000001d474800 4192 1 java.lang.StackTraceElement::getClassName (5 bytes) +Event: 131.313 Thread 0x000000001d474800 nmethod 4192 0x00000000037a4c90 code [0x00000000037a4de0, 0x00000000037a4ef0] +Event: 131.313 Thread 0x000000001d474800 4193 ! 3 sun.nio.cs.StreamEncoder::flushBuffer (42 bytes) +Event: 131.313 Thread 0x000000001d474800 nmethod 4193 0x00000000037a6910 code [0x00000000037a6ac0, 0x00000000037a7098] + +GC Heap History (10 events): +Event: 98.293 GC heap before +{Heap before GC invocations=12 (full 1): + PSYoungGen total 169472K, used 169111K [0x000000076c700000, 0x0000000778200000, 0x00000007c0000000) + eden space 167424K, 100% used [0x000000076c700000,0x0000000776a80000,0x0000000776a80000) + from space 2048K, 82% used [0x0000000778000000,0x00000007781a5ff0,0x0000000778200000) + to space 10752K, 0% used [0x0000000776d00000,0x0000000776d00000,0x0000000777780000) + ParOldGen total 93184K, used 6900K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abd178,0x00000006caf00000) + Metaspace used 26364K, capacity 26900K, committed 27008K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +Event: 98.299 GC heap after +Heap after GC invocations=12 (full 1): + PSYoungGen total 164352K, used 1859K [0x000000076c700000, 0x0000000778080000, 0x00000007c0000000) + eden space 162304K, 0% used [0x000000076c700000,0x000000076c700000,0x0000000776580000) + from space 2048K, 90% used [0x0000000776d00000,0x0000000776ed0fe0,0x0000000776f00000) + to space 10752K, 0% used [0x0000000777600000,0x0000000777600000,0x0000000778080000) + ParOldGen total 93184K, used 6900K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abd178,0x00000006caf00000) + Metaspace used 26364K, capacity 26900K, committed 27008K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +} +Event: 112.449 GC heap before +{Heap before GC invocations=13 (full 1): + PSYoungGen total 164352K, used 164163K [0x000000076c700000, 0x0000000778080000, 0x00000007c0000000) + eden space 162304K, 100% used [0x000000076c700000,0x0000000776580000,0x0000000776580000) + from space 2048K, 90% used [0x0000000776d00000,0x0000000776ed0fe0,0x0000000776f00000) + to space 10752K, 0% used [0x0000000777600000,0x0000000777600000,0x0000000778080000) + ParOldGen total 93184K, used 6900K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abd178,0x00000006caf00000) + Metaspace used 26410K, capacity 26964K, committed 27264K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +Event: 112.470 GC heap after +Heap after GC invocations=13 (full 1): + PSYoungGen total 158720K, used 1461K [0x000000076c700000, 0x0000000777780000, 0x00000007c0000000) + eden space 157184K, 0% used [0x000000076c700000,0x000000076c700000,0x0000000776080000) + from space 1536K, 95% used [0x0000000777600000,0x000000077776d550,0x0000000777780000) + to space 10240K, 0% used [0x0000000776380000,0x0000000776380000,0x0000000776d80000) + ParOldGen total 93184K, used 6900K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abd178,0x00000006caf00000) + Metaspace used 26410K, capacity 26964K, committed 27264K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +} +Event: 114.140 GC heap before +{Heap before GC invocations=14 (full 1): + PSYoungGen total 158720K, used 158645K [0x000000076c700000, 0x0000000777780000, 0x00000007c0000000) + eden space 157184K, 100% used [0x000000076c700000,0x0000000776080000,0x0000000776080000) + from space 1536K, 95% used [0x0000000777600000,0x000000077776d550,0x0000000777780000) + to space 10240K, 0% used [0x0000000776380000,0x0000000776380000,0x0000000776d80000) + ParOldGen total 93184K, used 6900K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abd178,0x00000006caf00000) + Metaspace used 26418K, capacity 26964K, committed 27264K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +Event: 114.143 GC heap after +Heap after GC invocations=14 (full 1): + PSYoungGen total 154624K, used 1655K [0x000000076c700000, 0x0000000777680000, 0x00000007c0000000) + eden space 152576K, 0% used [0x000000076c700000,0x000000076c700000,0x0000000775c00000) + from space 2048K, 80% used [0x0000000776380000,0x000000077651dff0,0x0000000776580000) + to space 9728K, 0% used [0x0000000776d00000,0x0000000776d00000,0x0000000777680000) + ParOldGen total 93184K, used 6908K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abf178,0x00000006caf00000) + Metaspace used 26418K, capacity 26964K, committed 27264K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +} +Event: 115.355 GC heap before +{Heap before GC invocations=15 (full 1): + PSYoungGen total 154624K, used 154231K [0x000000076c700000, 0x0000000777680000, 0x00000007c0000000) + eden space 152576K, 100% used [0x000000076c700000,0x0000000775c00000,0x0000000775c00000) + from space 2048K, 80% used [0x0000000776380000,0x000000077651dff0,0x0000000776580000) + to space 9728K, 0% used [0x0000000776d00000,0x0000000776d00000,0x0000000777680000) + ParOldGen total 93184K, used 6908K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abf178,0x00000006caf00000) + Metaspace used 26418K, capacity 26964K, committed 27264K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +Event: 115.360 GC heap after +Heap after GC invocations=15 (full 1): + PSYoungGen total 150016K, used 1591K [0x000000076c700000, 0x0000000776f00000, 0x00000007c0000000) + eden space 147968K, 0% used [0x000000076c700000,0x000000076c700000,0x0000000775780000) + from space 2048K, 77% used [0x0000000776d00000,0x0000000776e8dff0,0x0000000776f00000) + to space 9216K, 0% used [0x0000000775d00000,0x0000000775d00000,0x0000000776600000) + ParOldGen total 93184K, used 6908K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abf178,0x00000006caf00000) + Metaspace used 26418K, capacity 26964K, committed 27264K, reserved 1073152K + class space used 3204K, capacity 3367K, committed 3456K, reserved 1048576K +} +Event: 127.014 GC heap before +{Heap before GC invocations=16 (full 1): + PSYoungGen total 150016K, used 149559K [0x000000076c700000, 0x0000000776f00000, 0x00000007c0000000) + eden space 147968K, 100% used [0x000000076c700000,0x0000000775780000,0x0000000775780000) + from space 2048K, 77% used [0x0000000776d00000,0x0000000776e8dff0,0x0000000776f00000) + to space 9216K, 0% used [0x0000000775d00000,0x0000000775d00000,0x0000000776600000) + ParOldGen total 93184K, used 6908K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5abf178,0x00000006caf00000) + Metaspace used 26464K, capacity 27028K, committed 27264K, reserved 1073152K + class space used 3205K, capacity 3367K, committed 3456K, reserved 1048576K +Event: 127.033 GC heap after +Heap after GC invocations=16 (full 1): + PSYoungGen total 144896K, used 1473K [0x000000076c700000, 0x0000000776d80000, 0x00000007c0000000) + eden space 143360K, 0% used [0x000000076c700000,0x000000076c700000,0x0000000775300000) + from space 1536K, 95% used [0x0000000775d00000,0x0000000775e70540,0x0000000775e80000) + to space 9216K, 0% used [0x0000000776480000,0x0000000776480000,0x0000000776d80000) + ParOldGen total 93184K, used 6916K [0x00000006c5400000, 0x00000006caf00000, 0x000000076c700000) + object space 93184K, 7% used [0x00000006c5400000,0x00000006c5ac1178,0x00000006caf00000) + Metaspace used 26464K, capacity 27028K, committed 27264K, reserved 1073152K + class space used 3205K, capacity 3367K, committed 3456K, reserved 1048576K +} + +Deoptimization events (10 events): +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x0000000003181274 method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 116.483 Thread 0x0000000002381000 Uncommon trap: reason=range_check action=none pc=0x00000000032857bc method=sun.reflect.generics.parser.SignatureParser.current()C @ 34 +Event: 131.311 Thread 0x0000000002381000 Uncommon trap: reason=unstable_if action=reinterpret pc=0x0000000003324434 method=org.codehaus.jackson.impl.ReaderBasedParser.nextToken()Lorg/codehaus/jackson/JsonToken; @ 37 + +Internal exceptions (10 events): +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774722590) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774723398) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774724040) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774724d40) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x00000007747259e8) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x00000007747266e0) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774727458) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774728060) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 116.483 Thread 0x0000000002381000 Exception (0x0000000774728c58) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\interpreter\interpreterRuntime.cpp, line 366] +Event: 119.647 Thread 0x0000000002381000 Exception (0x0000000774aedd18) thrown at [C:\re\workspace\8-2-build-windows-amd64-cygwin\jdk8u101\7261\hotspot\src\share\vm\prims\jni.cpp, line 735] + +Events (10 events): +Event: 2632.158 Executing VM operation: EnterInterpOnlyMode +Event: 2632.158 Executing nested VM operation: Deoptimize +Event: 2632.159 Executing nested VM operation: Deoptimize done +Event: 2632.159 Executing VM operation: EnterInterpOnlyMode done +Event: 2632.159 Executing VM operation: ChangeSingleStep +Event: 2632.159 Executing VM operation: ChangeSingleStep done +Event: 2632.160 Executing VM operation: ChangeSingleStep +Event: 2632.160 Executing VM operation: ChangeSingleStep done +Event: 2632.193 Executing VM operation: RedefineClasses +Event: 2632.229 Executing VM operation: RedefineClasses done + + +Dynamic libraries: +0x000000013fd10000 - 0x000000013fd47000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\javaw.exe +0x0000000077510000 - 0x00000000776ba000 C:\WINDOWS\SYSTEM32\ntdll.dll +0x00000000773f0000 - 0x000000007750f000 C:\WINDOWS\system32\kernel32.dll +0x000007fefd2e0000 - 0x000007fefd34a000 C:\WINDOWS\system32\KERNELBASE.dll +0x000007fefd600000 - 0x000007fefd6db000 C:\WINDOWS\system32\ADVAPI32.dll +0x000007fefe3e0000 - 0x000007fefe47f000 C:\WINDOWS\system32\msvcrt.dll +0x000007fefe480000 - 0x000007fefe49f000 C:\WINDOWS\SYSTEM32\sechost.dll +0x000007fefe510000 - 0x000007fefe63d000 C:\WINDOWS\system32\RPCRT4.dll +0x00000000772f0000 - 0x00000000773ea000 C:\WINDOWS\system32\USER32.dll +0x000007fefe4a0000 - 0x000007fefe507000 C:\WINDOWS\system32\GDI32.dll +0x000007feff730000 - 0x000007feff73e000 C:\WINDOWS\system32\LPK.dll +0x000007fefe820000 - 0x000007fefe8ea000 C:\WINDOWS\system32\USP10.dll +0x000007fefb4c0000 - 0x000007fefb6b4000 C:\WINDOWS\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.7601.18837_none_fa3b1e3d17594757\COMCTL32.dll +0x000007fefd9e0000 - 0x000007fefda51000 C:\WINDOWS\system32\SHLWAPI.dll +0x000007fefd9b0000 - 0x000007fefd9de000 C:\WINDOWS\system32\IMM32.DLL +0x000007fefdff0000 - 0x000007fefe0f9000 C:\WINDOWS\system32\MSCTF.dll +0x000007fef9c10000 - 0x000007fef9c9a000 C:\WINDOWS\system32\VSMAPIMon.dll +0x000007fef27e0000 - 0x000007fef2887000 C:\Program Files\McAfee\Host Intrusion Prevention\HcApi.dll +0x00000000705b0000 - 0x00000000705bb000 C:\Program Files\McAfee\Host Intrusion Prevention\HcThe.dll +0x0000000055580000 - 0x0000000055652000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\msvcr100.dll +0x000000006f5e0000 - 0x000000006fe7a000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\server\jvm.dll +0x000007fefbda0000 - 0x000007fefbda9000 C:\WINDOWS\system32\WSOCK32.dll +0x000007feff6e0000 - 0x000007feff72d000 C:\WINDOWS\system32\WS2_32.dll +0x000007fefdfc0000 - 0x000007fefdfc8000 C:\WINDOWS\system32\NSI.dll +0x000007fefaee0000 - 0x000007fefaf1b000 C:\WINDOWS\system32\WINMM.dll +0x000007fefc5f0000 - 0x000007fefc5fc000 C:\WINDOWS\system32\VERSION.dll +0x00000000776e0000 - 0x00000000776e7000 C:\WINDOWS\system32\PSAPI.DLL +0x00000000711e0000 - 0x00000000711ef000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\verify.dll +0x0000000065240000 - 0x0000000065269000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\java.dll +0x0000000055540000 - 0x0000000055575000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\jdwp.dll +0x00000000711d0000 - 0x00000000711d8000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\npt.dll +0x00000000003b0000 - 0x00000000003c6000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\zip.dll +0x000007fefe8f0000 - 0x000007feff67a000 C:\WINDOWS\system32\SHELL32.dll +0x000007fefdae0000 - 0x000007fefdce3000 C:\WINDOWS\system32\ole32.dll +0x000007fefd240000 - 0x000007fefd24f000 C:\WINDOWS\system32\profapi.dll +0x00000000711c0000 - 0x00000000711c9000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\dt_socket.dll +0x000007fefaa20000 - 0x000007fefaa35000 C:\WINDOWS\system32\NLAapi.dll +0x000007fef7bc0000 - 0x000007fef7bd5000 C:\WINDOWS\system32\napinsp.dll +0x000007fef7ba0000 - 0x000007fef7bb9000 C:\WINDOWS\system32\pnrpnsp.dll +0x000007fefca20000 - 0x000007fefca75000 C:\WINDOWS\System32\mswsock.dll +0x000007fefc8a0000 - 0x000007fefc8fb000 C:\WINDOWS\system32\DNSAPI.dll +0x000007fef7b90000 - 0x000007fef7b9b000 C:\WINDOWS\System32\winrnr.dll +0x000007fef7b80000 - 0x000007fef7b90000 C:\WINDOWS\system32\wshbth.dll +0x000007fefa330000 - 0x000007fefa357000 C:\WINDOWS\system32\IPHLPAPI.DLL +0x000007fefa320000 - 0x000007fefa32b000 C:\WINDOWS\system32\WINNSI.DLL +0x000007fef95a0000 - 0x000007fef95f3000 C:\WINDOWS\System32\fwpuclnt.dll +0x000007fef7010000 - 0x000007fef7018000 C:\WINDOWS\system32\rasadhlp.dll +0x000007fefc2d0000 - 0x000007fefc2d7000 C:\WINDOWS\System32\wshtcpip.dll +0x000000006f380000 - 0x000000006f39a000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\net.dll +0x000007fefca10000 - 0x000007fefca17000 C:\WINDOWS\System32\wship6.dll +0x000007fefca80000 - 0x000007fefca98000 C:\WINDOWS\system32\CRYPTSP.dll +0x000007fefc780000 - 0x000007fefc7c7000 C:\WINDOWS\system32\rsaenh.dll +0x000007fefd400000 - 0x000007fefd41e000 C:\WINDOWS\system32\USERENV.dll +0x000007fefd180000 - 0x000007fefd18f000 C:\WINDOWS\system32\CRYPTBASE.dll +0x000007fef9550000 - 0x000007fef9561000 C:\WINDOWS\system32\dhcpcsvc6.DLL +0x000007fef98c0000 - 0x000007fef98d8000 C:\WINDOWS\system32\dhcpcsvc.DLL +0x000000006f300000 - 0x000000006f311000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\nio.dll +0x000007fefd120000 - 0x000007fefd177000 C:\WINDOWS\system32\apphelp.dll +0x0000000051ba0000 - 0x0000000051bc4000 C:\Program Files\Java\jdk1.8.0_101\jre\bin\sunec.dll +0x000007fef68d0000 - 0x000007fef69f5000 C:\WINDOWS\system32\dbghelp.dll + +VM Arguments: +jvm_args: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:65399 -ea -Dlogback.configurationFile=src/test/resources/logback-test.xml -Dfile.encoding=Cp1252 +java_command: org.testng.remote.RemoteTestNG -serport 65394 -protocol json -d C:\Users\md9897\Projects\d2-sdnc\ui-ci\test-output C:\Users\md9897\AppData\Local\Temp\testng-eclipse-914658768\testng-customsuite.xml +java_class_path (initial): C:\Users\md9897\Desktop\eclipse\plugins\org.testng.eclipse_6.9.13.201609291640\lib\testng-remote.jar;C:\Users\md9897\Projects\d2-sdnc\ui-ci\target\test-classes;C:\Users\md9897\Projects\d2-sdnc\ui-ci\target\classes;C:\Users\md9897\.m2\repository\org\seleniumhq\selenium\selenium-java\2.45.0\selenium-java-2.45.0.jar;C:\Users\md9897\.m2\repository\org\seleniumhq\selenium\selenium-chrome-driver\2.45.0\selenium-chrome-driver-2.45.0.jar;C:\Users\md9897\.m2\repository\org\seleniumhq\selenium\selenium-remote-driver\2.45.0\selenium-remote-driver-2.45.0.jar;C:\Users\md9897\.m2\repository\cglib\cglib-nodep\2.1_3\cglib-nodep-2.1_3.jar;C:\Users\md9897\.m2\repository\org\seleniumhq\selenium\selenium-api\2.45.0\selenium-api-2.45.0.jar;C:\Users\md9897\.m2\repository\org\seleniumhq\selenium\selenium-htmlunit-driver\2.45.0\selenium-htmlunit-driver-2.45.0.jar;C:\Users\md9897\.m2\repository\net\sourceforge\htmlunit\htmlunit\2.15\htmlunit-2.15.jar;C:\Users\md9897\.m2\repository\xalan\xalan\2.7.1\xalan-2.7.1.jar;C:\Users\md9897\.m2\repository\xalan\serializer\2.7.1\serializer-2.7.1.jar;C:\Users\md9897\.m2\repository\net\sourceforge\htmlunit\htmlunit-core-js\2.15\htmlunit-core-js-2.15.jar;C:\Users\md9897\.m2\repository\xerces\xercesImpl\2.11.0\xercesImpl-2.11.0.jar;C:\Users\md9897\.m2\repository\net\sourceforge\nekohtml\nekohtml\1.9.21\nekohtml-1.9.21.jar;C:\Users\md9897\.m2\repository\net\sourceforge\cssparser\cssparser\0.9.14\cssparser-0.9.14.jar;C:\Users\md9897\.m2\repository\org\w3c\css\sac\1.3\sac-1.3.jar;C:\Users\md9897\.m2\repository\org\eclipse\jetty\jetty-websocket\8.1.15.v20140411\jetty-websocket-8.1.15.v20140411.jar;C:\Users\md9897\.m2\repository\org\eclipse\jetty\jetty-util\8.1.15.v20140411\jetty-util-8.1.15.v20140411.jar;C:\Users\md9897\.m2\repository\org\eclipse\jetty\jetty-io\8.1.15.v20140411\jetty-io-8.1.15.v20140411.jar;C:\Users\md9897\.m2\repository\org\eclipse\jetty\jetty-http\8.1.15.v20140411\jetty-http-8.1.15.v20140411.jar;C:\Users\md9897\. +Launcher Type: SUN_STANDARD + +Environment Variables: +PATH=C:\Program Files\Java\jdk1.8.0_101\jre\bin;C:/Program Files/Java/jre1.8.0_101/bin/server;C:/Program Files/Java/jre1.8.0_101/bin;C:/Program Files/Java/jre1.8.0_101/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\RSA SecurID Token Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Git\cmd;C:\Program Files (x86)\GitExtensions\;C:\HashiCorp\Vagrant\bin;C:\Program Files (x86)\WinSCP\;C:\Program Files (x86)\PuTTY\;C:\Program Files\nodejs\;C:\Users\md9897\AppData\Roaming\npm;C:\Users\md9897\Desktop\eclipse; +USERNAME=md9897 +OS=Windows_NT +PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 78 Stepping 3, GenuineIntel + + + +--------------- S Y S T E M --------------- + +OS: Windows 7 , 64 bit Build 7601 (6.1.7601.23543) + +CPU:total 4 (2 cores per cpu, 2 threads per core) family 6 model 78 stepping 3, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, avx, avx2, aes, clmul, erms, rtm, 3dnowpref, lzcnt, ht, tsc, tscinvbit, bmi1, bmi2, adx + +Memory: 4k page, physical 16432244k(7214352k free), swap 32862628k(23040548k free) + +vm_info: Java HotSpot(TM) 64-Bit Server VM (25.101-b13) for windows-amd64 JRE (1.8.0_101-b13), built on Jun 22 2016 01:21:29 by "java_re" with MS VC++ 10.0 (VS2010) + +time: Wed Nov 09 17:56:52 2016 +elapsed time: 2632 seconds (0d 0h 43m 52s) + diff --git a/ui-ci/pom.xml b/ui-ci/pom.xml new file mode 100644 index 0000000000..072a610360 --- /dev/null +++ b/ui-ci/pom.xml @@ -0,0 +1,357 @@ + + + 4.0.0 + + ui-ci + Selenium tests for the SDnC Application + + + org.openecomp.sdc + sdc-main + 1.1.0-SNAPSHOT + + + + + com.google.guava + guava + ${guava.version} + compile + + + + org.seleniumhq.selenium + selenium-java + 2.53.1 + + + + org.seleniumhq.selenium + selenium-server + 2.53.1 + runtime + + + + commons-net + commons-net + 3.3 + compile + + + + commons-io + commons-io + 2.4 + compile + + + + org.openecomp.sdc + test-apis-ci + ${project.version} + + compile + + + + org.yaml + snakeyaml + ${snakeyaml.version} + compile + + + org.functionaljava + functionaljava + ${functionaljava.version} + compile + + + + com.google.code.gson + gson + ${gson.version} + compile + + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + compile + + + + org.apache.httpcomponents + httpmime + ${httpclient.version} + compile + + + + commons-logging + commons-logging + ${commons-logging} + compile + + + + org.slf4j + slf4j-api + ${slf4j-api.version} + compile + + + + ch.qos.logback + logback-classic + ${logback.version} + compile + + + + ch.qos.logback + logback-core + ${logback.version} + compile + + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + compile + + + + + com.thinkaurelius.titan + titan-core + ${titan.version} + compile + + + + com.thinkaurelius.titan + titan-cassandra + ${titan.version} + compile + + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.2 + compile + + + + com.fasterxml.jackson.core + jackson-databind + 2.3.1 + compile + + + + com.fasterxml.jackson.core + jackson-core + 2.3.1 + compile + + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.annotations.version} + compile + + + + org.openecomp.sdc.sdc-distribution-client + sdc-distribution-client + 1.1.9-SNAPSHOT + compile + + + + junit + junit + ${junit.version} + compile + + + + org.testng + testng + ${testng.version} + compile + + + + xml-apis + xml-apis + 1.4.01 + compile + + + + com.googlecode.json-simple + json-simple + ${json-simple.version} + compile + + + + org.apache.commons + commons-jci-core + ${commons-jci-core.version} + compile + + + + org.sikuli + sikuli-api + 1.2.0 + + + + org.sikuli + sikuli-core + 1.2.2 + + + + commons-codec + commons-codec + ${commons-codec} + compile + + + + com.aventstack + extentreports + 3.0.6 + compile + + + + net.lightbody.bmp + + browsermob-core + 2.1.4 + + + + com.github.markusbernhardt + proxy-vole + 1.0.2 + + + + com.paulhammant + ngwebdriver + 0.9.7 + compile + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.7 + + true + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.5.5 + + + create.jar.with.dependencies + package + + single + + + + + org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest + + + + jar-with-dependencies + + + + + + + + + + + Fortify + + false + + + + + + + + + + com.fortify.ps.maven.plugin + sca-maven-plugin + 4.30 + + false + true + + + + + + + diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java new file mode 100644 index 0000000000..a8e6501dff --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java @@ -0,0 +1,415 @@ +/*- + * ============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.ci.tests.US; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ToscaArtifactsPage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +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.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + + +public class AddComponentInstancesArtifactsInCsar extends SetupCDTest { + + private String filePath; + @BeforeClass + public void beforeClass(){ + filePath = System.getProperty("filepath"); + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath() + "AddComponentInstancesArtifactsInCsar"+ File.separator; + } + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator + "AddComponentInstancesArtifactsInCsar"+ File.separator; + } + } + + // US847439 - Story [BE] - Add Component Instance's artifacts in CSAR + // TC1521795 - VF CSAR - The Flow + @Test + public void vfAndServicerCsarTheFlow() throws Exception{ + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "FDNT.zip"; + String snmpFile = "Fault-alarms-ASDC-vprobes-vLB.zip"; + + OnboardingUtils.createVendorLicense(getUser()); + Pair> createVSP = OnboardingUtils.createVSP(vnfFile, filePath, getUser()); + String vspName = createVSP.left; + resourceMetaData.setName(vspName); + Map resourceMeta = createVSP.right; + String vspid = resourceMeta.get("vspId"); + OnboardingUtils.addVFCArtifacts(filePath, snmpFile, null, vspid, getUser()); + OnboardingUtils.prepareVspForUse(getUser(), vspid); + + HomePage.showVspRepository(); + OnboardingUtils.importVSP(createVSP); + resourceMetaData.setVersion("0.1"); + Resource vfResource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), resourceMetaData.getVersion()); + + + Map artifacts = getArtifactsOfComponentAndComponentsInstance(vfResource); + + List> artifactsUploadedToComponentInstance = new LinkedList<>(); + Random random = new Random(); + for(int i=0; i uploadArtifactOnRandomVfc = uploadArtifactOnRandomRI(vfResource); + + if(uploadArtifactOnRandomVfc.getRight().getArtifactName() != null) { + artifactsUploadedToComponentInstance.add(uploadArtifactOnRandomVfc); + } + } + + if(artifactsUploadedToComponentInstance.size() > 0) { + Map artifactsOfResourceInstance = getArtifactsOfResourceInstance(artifactsUploadedToComponentInstance); + artifacts.put("Resources", artifactsOfResourceInstance); + } + + + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + ToscaArtifactsPage.downloadCsar(); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + Map combineHeatArtifacstWithFolderArtifacsToMap = ArtifactFromCsar.getVFCArtifacts(latestFilefromDir.getAbsolutePath()); + + compareArtifactFromFileStructureToArtifactsFromJavaObject(artifacts, combineHeatArtifacstWithFolderArtifacsToMap); + + +// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// // Submit for testing + certify +// DeploymentArtifactPage.clickSubmitForTestingButton(vspName); +// +// reloginWithNewRole(UserRoleEnum.TESTER); +// GeneralUIUtils.findComponentAndClick(vspName); +// TesterOperationPage.certifyComponent(vspName); +// +// reloginWithNewRole(UserRoleEnum.DESIGNER); +// // create service +// ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); +// ServiceUIUtils.createService(serviceMetadata, getUser()); +// serviceMetadata.setVersion("0.1"); +// +// +// // Upload informationl artifact to service +// ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); +// +// String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; +// String DESCRIPTION = "kuku"; +// String ARTIFACT_LABEL = "artifact3"; +// +// ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,"OTHER"); +// CompositionPage.showDeploymentArtifactTab(); +// CompositionPage.clickAddArtifactButton(); +// ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); +// +// ArtifactInfo informationArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "GUIDE"); +// CompositionPage.showInformationArtifactTab(); +// CompositionPage.clickAddArtifactButton(); +// ArtifactUIUtils.fillAndAddNewArtifactParameters(informationArtifact, CompositionPage.artifactPopup()); +// +// +// +// // Add component instance to canvas of the service +// CompositionPage.searchForElement(vspName); +// CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); +// CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); +// +// Service service = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), serviceMetadata.getVersion()); +// +//// ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "OTHER", true, false); +//// RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(service, getUser(), artifactReqDetails); +//// Integer responseCode = restResponse.getErrorCode(); +//// Assert.assertEquals(responseCode, (Integer)200, "Response code is not correct."); +//// +//// service = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), serviceMetadata.getVersion()); +// +// Map artifactsService = getArtifactsOfComponentAndComponentsInstance(service); +// +// System.out.println("12354"); +// +// artifactsService.put(vfResource.getToscaResourceName(), artifacts); +// +// System.out.println("1234"); + + } + + public void compareArtifactFromFileStructureToArtifactsFromJavaObject(Map artifactFromJavaObject, Map artifactsFromFileStructure) { + for(String key: artifactFromJavaObject.keySet()) { + if((!key.equals("Deployment")) && (!key.equals("Informational"))) { + Map newArtifactFromJavaObject = (Map) artifactFromJavaObject.get(key); + Map newArtifactsFromFileStructure = (Map) artifactsFromFileStructure.get(key); + compareArtifactFromFileStructureToArtifactsFromJavaObject(newArtifactFromJavaObject, newArtifactsFromFileStructure); + } else { + compareArtifacts(artifactFromJavaObject.get(key), artifactsFromFileStructure.get(key)); + } + + + + + } + } + + + private void compareArtifacts(Object artifactFromJavaObject, Object artifactsFromFileStructure) { + Map> artifactsMap = (Map>) artifactFromJavaObject; + List artifactsList = (List) artifactsFromFileStructure; + + for(HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition: artifactsList) { + Assert.assertTrue(artifactsMap.get(heatMetaFirstLevelDefinition.getType()).contains(heatMetaFirstLevelDefinition.getFileName()), + "Expected that artifacts will be the same. Not exists: " + heatMetaFirstLevelDefinition.getFileName() + " of type: " + heatMetaFirstLevelDefinition.getType()); + } + + for(String key: artifactsMap.keySet()) { + List artifacts = artifactsMap.get(key); + + for(HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition: artifactsList) { + if(heatMetaFirstLevelDefinition.getType().equals(key)) { + if(artifacts.contains(heatMetaFirstLevelDefinition.getFileName())) { + artifacts.remove(heatMetaFirstLevelDefinition.getFileName()); + } + } + } + + Assert.assertEquals(artifacts.size(), 0, "Expected that all artifacts equal. There is artifacts which not equal: " + artifacts.toString()); + } + } + + + public Map getArtifactsOfResourceInstance(List> riList) { + Map artifacts = new HashMap<>(); + + for(ImmutablePair ri: riList) { + ArtifactDefinition artifactDefinition = ri.getRight(); + ComponentInstance componentInstance = ri.getLeft(); + if(artifacts.containsKey(componentInstance.getNormalizedName())) { + if( ((Map>)((Map)artifacts.get(componentInstance.getNormalizedName())).get("Deployment")).containsKey(artifactDefinition.getArtifactType()) ) { + + ((Map>)((Map) artifacts.get(componentInstance.getNormalizedName())).get("Deployment")).get(artifactDefinition.getArtifactType()).add(artifactDefinition.getArtifactName()); + + } else { + ArrayList list = new ArrayList(); + list.add(artifactDefinition.getArtifactName()); + ((Map>)((Map) artifacts.get(componentInstance.getNormalizedName())).get("Deployment")).put(artifactDefinition.getArtifactType(), list); + } + + } else { + try { + + + ArrayList list = new ArrayList(); + list.add(artifactDefinition.getArtifactName()); + + Map> map = new HashMap<>(); + map.put(artifactDefinition.getArtifactType(), list); + + Map>> addMap = new HashMap<>(); + addMap.put("Deployment", map); + + artifacts.put(componentInstance.getNormalizedName(), addMap); + +// if(artifacts.size() == 0) { +// artifacts.put("Deployment", addMap); +// } else { +// ((Map>>) artifacts.get("Deployment")).putAll(addMap); +// } + } catch (Exception e) { + Assert.fail("Artifact name is null for componentInstance: " + componentInstance.getNormalizedName()); + } + } + } + return artifacts; + } + + public Map getArtifactsOfComponentAndComponentsInstance(Component component) { + Map artifacts = getArtifacstOfComponent(component); + + for(ComponentInstance componentInstance: component.getComponentInstances()) { + Map artifacstOfComponentInstance = getArtifacstOfComponentInstance(componentInstance); + if(artifacstOfComponentInstance.size() > 0) { + artifacts.put(componentInstance.getToscaComponentName() + "." + componentInstance.getComponentVersion(), artifacstOfComponentInstance); + } + } + + return artifacts; + } + + public Map getArtifacstOfComponentInstance(ComponentInstance componentInstance) { + Map map = new HashMap<>(); + + if(componentInstance.getArtifacts() != null) { + Map informationalArtifacts = getArtifacts(componentInstance.getArtifacts()); + if(informationalArtifacts.size() > 0) { + map.put("Informational", informationalArtifacts); + } + } + + if(componentInstance.getDeploymentArtifacts() != null) { + Map deploymentArtifacts = getArtifacts(componentInstance.getDeploymentArtifacts()); + if(deploymentArtifacts.size() > 0) { + map.put("Deployment", deploymentArtifacts); + } + } + + return map; + } + + public Map getArtifacstOfComponent(Component component) { + Map map = new HashMap<>(); + + if(component.getArtifacts() != null) { + Map informationalArtifacts = getArtifacts(component.getArtifacts()); + if(informationalArtifacts.size() > 0) { + map.put("Informational", informationalArtifacts); + } + } + + if(component.getDeploymentArtifacts() != null) { + Map deploymentArtifacts = getArtifacts(component.getDeploymentArtifacts()); + if(deploymentArtifacts.size() > 0) { + map.put("Deployment", deploymentArtifacts); + } + } + + return map; + } + + public Map getArtifacts(Map artifacts) { + Map map = new HashMap<>(); + + for(String artifact: artifacts.keySet()) { + ArtifactDefinition artifactDefinition = artifacts.get(artifact); + if((artifactDefinition.getEsId() != null) && (!artifactDefinition.getEsId().equals("")) && (!artifactDefinition.getArtifactType().equals("HEAT_ENV"))) { + if(map.containsKey(artifactDefinition.getArtifactType())) { + ((List) map.get(artifactDefinition.getArtifactType())).add(artifactDefinition.getArtifactName()); + } else { + ArrayList list = new ArrayList(); + list.add(artifactDefinition.getArtifactName()); + map.put(artifactDefinition.getArtifactType(), list); + } + } + } + + return map; + } + + public ImmutablePair uploadArtifactOnRandomRI(Component component) throws IOException, Exception { + ArtifactReqDetails artifactReqDetails = getRandomArtifact(); + Random random = new Random(); + int randInt = random.nextInt(component.getComponentInstances().size()); + User defaultUser = ElementFactory.getDefaultUser(getRole()); + ComponentInstance componentInstance = component.getComponentInstances().get(randInt); + + RestResponse uploadArtifactRestResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, defaultUser, artifactReqDetails, componentInstance); + + // Check response of external API + Integer responseCode = uploadArtifactRestResponse.getErrorCode(); + Assert.assertEquals(responseCode, (Integer)200, "Response code is not correct."); + + ImmutablePair pair = ImmutablePair.of(componentInstance, ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse())); + + return pair; + } + + public ImmutablePair uploadArtifactOnRandomRI(Resource resource) throws IOException, Exception { + ArtifactReqDetails artifactReqDetails = getRandomVfcArtifact(); + Random random = new Random(); + int randInt = random.nextInt(resource.getComponentInstances().size()); + User defaultUser = ElementFactory.getDefaultUser(getRole()); + ComponentInstance componentInstance = resource.getComponentInstances().get(randInt); + + RestResponse uploadArtifactRestResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resource, defaultUser, artifactReqDetails, componentInstance); + + + + // Check response of external API + Integer responseCode = uploadArtifactRestResponse.getErrorCode(); + + if(responseCode.equals(404)) { + getExtendTest().log(Status.SKIP, String.format("DE271521")); + throw new SkipException("DE271521"); + } + + Assert.assertEquals(responseCode, (Integer)200, "Response code is not correct."); + + ImmutablePair pair = ImmutablePair.of(componentInstance, ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse())); + + return pair; + } + + public ArtifactReqDetails getRandomArtifact() throws IOException, Exception { + List artifactsTypeList = Arrays.asList("Other"); + return getRandomArtifact(artifactsTypeList); + } + + public ArtifactReqDetails getRandomVfcArtifact() throws IOException, Exception { + List vfcArtifactsTypeList = Arrays.asList("DCAE_INVENTORY_TOSCA", "DCAE_INVENTORY_JSON", "DCAE_INVENTORY_POLICY", "DCAE_INVENTORY_DOC", + "DCAE_INVENTORY_BLUEPRINT", "DCAE_INVENTORY_EVENT", "SNMP_POLL", "SNMP_TRAP"); + return getRandomArtifact(vfcArtifactsTypeList); + } + + public ArtifactReqDetails getRandomArtifact(List artifactType) throws IOException, Exception { + Random random = new Random(); + + ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType.get(random.nextInt(artifactType.size())), true, false); + return artifactReqDetails; + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java new file mode 100644 index 0000000000..913064b7fd --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java @@ -0,0 +1,343 @@ +/*- + * ============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.ci.tests.US; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.testng.SkipException; +import org.testng.annotations.Test; + +public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest { + + private String folder ="US747946"; + + // US747946 - Import artifacts to component instances + // TC1407822 - Import VFC Artifacts - Deployment Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfvArtifactsDeploymentArtifactsMultipleArtifactsMultipleTypes() throws Exception { + + if(true){ + throw new SkipException("Open bug 197126"); + } + + String filePath = FileHandling.getFilePath(folder); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String fileName = "TC1407822.csar"; + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + List snmpPollArtifactList = Stream + .of("base_cgi_frwl.mib", "base_vIECCF_volume.yml", "node_userdata_script.sh", "vendor-license-model.xml") + .collect(Collectors.toList()); + List snmpTrapArtifactList = Stream + .of("module_1_ixlt.mib", "module_1_ixlt.yaml") + .collect(Collectors.toList()); + + + List filteredArtifactNames = + //Stream of component Instances + resource.getComponentInstances().stream() + //Stream of all the artifacts on all the component instances + .flatMap( e -> e.getDeploymentArtifacts().values().stream()) + //filter relevant artifact types + .filter( e -> e.getArtifactType().equals(ArtifactTypeEnum.SNMP_TRAP.getType()) || e.getArtifactType().equals(ArtifactTypeEnum.SNMP_POLL.getType())) + //collect to list + .collect(Collectors.toList()); + + + assertTrue("Not contain all SNMP TRAP artifacts.", filteredArtifactNames.stream() + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.SNMP_TRAP.getType())) + .map(e -> e.getArtifactName()) + .collect(Collectors.toList()) + .containsAll(snmpTrapArtifactList)); + + assertTrue("Not contain all SNMP POLL artifacts.", filteredArtifactNames.stream() + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.SNMP_POLL.getType())) + .map(e -> e.getArtifactName()) + .collect(Collectors.toList()) + .containsAll(snmpPollArtifactList)); + + filteredArtifactNames.stream() + .map(e->e.getArtifactDisplayName()) + .collect(Collectors.toList()) + .forEach(e -> { + assertTrue("Wrong artifact appear on deployment artifact UI page.", + !GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + e)); + }); + + } + + + + // US747946 - Import artifacts to component instances + // TC1408044 - Import VFC Artifacts - Informational Artifacts on Single VFC + @Test + public void importVfcArtifactsInformationalArtifactsOnSingleVfc() throws Exception { + + if(true){ + throw new SkipException("Open bug 197126"); + } + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1408044.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if(e.getToscaComponentName().endsWith("heat.ltm")) { + Map> artifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.GUIDE.getType(), Arrays.asList("module_1_ldsa.yaml", "vendor-license-model.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("module_2_ldsa.yaml", "vf-license-model.xml")); + } + }; + + validateInformationalArtifactOnComponetInstance(e, artifactsMap, "heat.ltm"); + } + }); + } + + // TODO: Note there is performance issue with this CSAR + // US747946 - Import artifacts to component instances + // TC1407998 - Import VFC Artifacts - Deployment & Informational Artifacts - Multiple VFCs + @Test + public void importVfcArtifactsDeploymentAndInformationalArtifactsMultipleVfcs() throws Exception { + + if(true){ + throw new SkipException("Open bug 197126"); + } + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1407998.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + +// resourceMetaData.setName("TC1407998"); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if(e.getToscaComponentName().endsWith("heat.ps")) { + Map> deployArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("PS_DEPL_Poll1.mib", "PS_DEPL_Poll2.xml", "PS_DEPL_Poll3.yaml")); + put(ArtifactTypeEnum.SNMP_TRAP.getType(), Arrays.asList("PS_DEPL_Trap1.mib", "PS_DEPL_Trap2.xml", "PS_DEPL_Trap3.sh", "PS_DEPL_Trap4.yml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ps"); + + Map> infoArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.GUIDE.getType(), Arrays.asList("PS_INFO_GUIDE1.yaml", "PS_INFO_GUIDE2.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("PS_INFO_OTHER1.yaml", "PS_INFO_OTHER2.xml")); + } + }; + validateInformationalArtifactOnComponetInstance(e, infoArtifactsMap, "heat.ps"); + + + } else if (e.getToscaComponentName().endsWith("heat.sm")) { + Map> deployArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("SM_DEPL_Poll1.mib", "SM_DEPL_Poll2.mib", "SM_DEPL_Poll3.xml")); + put(ArtifactTypeEnum.SNMP_TRAP.getType(), Arrays.asList("SM_DEPL_Trap1.mib", "SM_DEPL_Trap2.xml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.sm"); + + Map> infoArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.GUIDE.getType(), Arrays.asList("SM_INFO_GUIDE1.yaml", "SM_INFO_GUIDE2.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("SM_INFO_OTHER1.yaml", "SM_INFO_OTHER2.xml")); + } + }; + validateInformationalArtifactOnComponetInstance(e, infoArtifactsMap, "heat.sm"); + } + }); + + } + + // US747946 - Import artifacts to component instances + // TC1410352 - Import VFC Artifacts - Deployment Artifacts - Extra folder Under VFC-Identification + @Test + public void importVfcArtifactsDeploymentArtifactsExtraFolderUnderVfcIdentification() throws Exception { + + if(true){ + throw new SkipException("Open bug 197126"); + } + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1410352.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + +// resourceMetaData.setName("TC1410352"); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if(e.getToscaComponentName().endsWith("heat.ltm")) { + Map> deployArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("Poll1.mib", "Poll2.xml", "Poll3.sh", "Poll4.yml")); + put(ArtifactTypeEnum.SNMP_TRAP.getType(), Arrays.asList("Trap1.mib", "Trap2.yaml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ltm"); + + Map> infoArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.GUIDE.getType(), Arrays.asList("GUIDE1.yaml", "GUIDE2.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("OTHER1.yaml", "OTHER2.xml")); + } + }; + validateInformationalArtifactOnComponetInstance(e, infoArtifactsMap, "heat.ltm"); + } + }); + } + + + // US747946 - Import artifacts to component instances + // TC1410352 - Import VFC Artifacts - Deployment Artifacts - Invalid Artifact Type + @Test + public void importVfcArtifactsDeploymentArtifactsInvalidArtifactType() throws Exception { + + if(true){ + throw new SkipException("Open bug 197126"); + } + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1425032.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + +// resourceMetaData.setName("TC1425032"); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if(e.getToscaComponentName().endsWith("heat.ltm")) { + Map> deployArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("DeploySNMPPoll1.mib", "DeploySNMPPoll2.yml", "DeploySNMPPoll3.sh", "DeploySNMPPoll4.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("DeploySNMPTrapB1.mib", "DeploySNMPTrapB2.yaml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ltm"); + + Map> infoArtifactsMap = new HashMap>() { + { + put(ArtifactTypeEnum.GUIDE.getType(), Arrays.asList("InfoGuide1.yaml", "InfoGuide2.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("InfoOther1.yaml", "InfoOther2.xml", "InfoInvalid1.yaml")); + } + }; + validateInformationalArtifactOnComponetInstance(e, infoArtifactsMap, "heat.ltm"); + } + }); + } + + + private void validateInformationalArtifactOnComponetInstance(ComponentInstance instacne, Map> artifactsMap, String endswith){ + if(instacne.getToscaComponentName().endsWith(endswith) ){ + Set types = artifactsMap.keySet(); + + Map> collect = instacne.getArtifacts().values().stream() + .filter( a -> types.contains(a.getArtifactType())) + .collect(Collectors.groupingBy( e -> e.getArtifactType())); + + types.forEach(m -> { + if(collect.containsKey(m)){ + List found = collect.get(m).stream().map(e -> e.getArtifactName()).collect(Collectors.toList()); + boolean isValid = found.containsAll(artifactsMap.get(m)) && artifactsMap.get(m).containsAll(found); + assertTrue("Not contain all artifact of type: " + m, isValid); + } else{ + assertTrue("Contains informational artifact which not in provided list", false); + } + }); + } + } + + private void validateDeploymentArtifactOnComponetInstance(ComponentInstance instacne, Map> artifactsMap, String endswith){ + if(instacne.getToscaComponentName().endsWith(endswith) ){ + Set types = artifactsMap.keySet(); + + Map> collect = instacne.getDeploymentArtifacts().values().stream() + .filter( a -> types.contains(a.getArtifactType())) + .collect(Collectors.groupingBy( e -> e.getArtifactType())); + + types.forEach(m -> { + if(collect.containsKey(m)){ + List found = collect.get(m).stream().map(e -> e.getArtifactName()).collect(Collectors.toList()); + boolean isValid = found.containsAll(artifactsMap.get(m)) && artifactsMap.get(m).containsAll(found); + assertTrue("Not contain all artifact of type: " + m, isValid); + } else{ + assertTrue("Contains deployment artifact which not in provided list", false); + } + }); + } + } + + + + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Inputs.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Inputs.java new file mode 100644 index 0000000000..dff10dba49 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Inputs.java @@ -0,0 +1,226 @@ +/*- + * ============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.ci.tests.US; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.InputsPage; +import org.openecomp.sdc.ci.tests.pages.PropertyPopup; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.TestException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class Inputs extends SetupCDTest { + + private static final String DESCRIPTION = "kuku"; + private static final String ARTIFACT_LABEL = "artifact3"; + private static final String ARTIFACT_LABEL_UPDATE = "artifactUpdate"; + private static final String GET_ARTIFACT_LIST_BY_CLASS_NAME = "i-sdc-designer-sidebar-section-content-item-artifact"; + private static final String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; + private static final String HEAT_FILE_YAML_UPDATE_NAME = "Heat-File-Update.yaml"; + private String filePath; + + @BeforeMethod + public void beforeTest(){ + filePath = FileHandling.getFilePath(""); + } + + // TODO: There is defect that imported VFC checkin not appear in service until refresh + // TODO: add support for CP (there is no normative CP's with complex properties which can be selected - import one) - importVFCWithComplexProperty.yml + // TC1508249 + // Delete Input declared from VLi/CPi in service level - Deleting an Input that was declared from Complex property. + @Test + public void deletingAnInputThatWasDeclaredFromComplexProperty() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + Map> resourceInstanceToProperty = new HashMap<>(); + CompositionPage.searchForElement("ExtVL"); + CanvasElement computeElement = canvasManager.createElementOnCanvas("ExtVL"); + canvasManager.clickOnCanvaElement(computeElement); + resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), Arrays.asList("network_homing", "instance_node_target")); + +// CompositionPage.searchForElement("ExtCP"); +// computeElement = canvasManager.createElementOnCanvas("ExtCP"); +// canvasManager.clickOnCanvaElement(computeElement); +// resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), "order"); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToInputsScreen(); + + + for(String element: resourceInstanceToProperty.keySet()) { + String propertyName = resourceInstanceToProperty.get(element).get(0); + String innerPropertyName = resourceInstanceToProperty.get(element).get(1); + String dataTestIdPropertyCheckbox = DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + propertyName; + + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + + InputsPage.clickOnProperty(propertyName); + + PropertyPopup propertyPopup = new PropertyPopup(); + propertyPopup.selectPropertyRadioButton(innerPropertyName); + propertyPopup.clickSave(); + + InputsPage.clickOnAddInputButton(); + + // Verify that input checkbox selected + verifyPropertyCheckBoxSelected(dataTestIdPropertyCheckbox); + + InputsPage.deleteServiceInput(element, propertyName + "_" + innerPropertyName); + + // Trying to find deleted service input + try{ + InputsPage.getServiceInput(element, propertyName + "_" + innerPropertyName); + assert(false); + } catch(TestException e){ + System.out.println("Verfied that service input deleted"); + } + + // Verify that input checkbox not selected + verifyPropertyCheckBoxNotSelected(dataTestIdPropertyCheckbox); + + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + } + + } + + + // TC1508248 + // Delete inputs who come from CP/VL properties + @Test + public void deleteInputsWhoComeFromCpVlProperties() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + Map resourceInstanceToProperty = new HashMap<>(); + CompositionPage.searchForElement("ExtVL"); + CanvasElement computeElement = canvasManager.createElementOnCanvas("ExtVL"); + canvasManager.clickOnCanvaElement(computeElement); + resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), "network_role"); + + CompositionPage.searchForElement("ExtCP"); + computeElement = canvasManager.createElementOnCanvas("ExtCP"); + canvasManager.clickOnCanvaElement(computeElement); + resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), "order"); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToInputsScreen(); + + + for(String element: resourceInstanceToProperty.keySet()) { + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + + WebElement webElementByTestID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + resourceInstanceToProperty.get(element)); + InputsPage.clickOnVFInputCheckbox(webElementByTestID); + + InputsPage.clickOnAddInputButton(); + + // Verify that input checkbox selected + verifyPropertyCheckBoxSelected(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + resourceInstanceToProperty.get(element)); + + InputsPage.deleteServiceInput(element, resourceInstanceToProperty.get(element)); + + // Trying to find deleted service input + try{ + InputsPage.getServiceInput(element, resourceInstanceToProperty.get(element)); + assert(false); + } catch(TestException e){ + System.out.println("Verfied that service input deleted"); + } + + // Verify that input checkbox not selected + verifyPropertyCheckBoxNotSelected(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + resourceInstanceToProperty.get(element)); + + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + } + + } + + + + + + + + public String verifyPropertyCheckBox(String dataTestId) { + WebElement webElementByTestID = GeneralUIUtils.getWebElementByTestID(dataTestId); + webElementByTestID = webElementByTestID.findElement(By.className("tlv-checkbox-i")); + if(webElementByTestID.getAttribute("checked") == null) { + return "false"; + } + return "true"; + } + + public void verifyPropertyCheckBoxSelected(String dataTestId) { + if(!verifyPropertyCheckBox(dataTestId).equals("true")) { + Assert.assertEquals(true, false, "Expected that checkbox will be selected."); + } + } + + public void verifyPropertyCheckBoxNotSelected(String dataTestId) { + if(!verifyPropertyCheckBox(dataTestId).equals("false")) { + Assert.assertEquals(false, true, "Expected that checkbox will not be selected."); + } + } + + public String getNormalizedName(String notNormalizedName) { + String normalizedName = notNormalizedName.toLowerCase(); + normalizedName = normalizedName.replaceAll(" ", ""); + + return normalizedName; + } + + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java new file mode 100644 index 0000000000..fb1798d0c9 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java @@ -0,0 +1,99 @@ +/*- + * ============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.ci.tests.US; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.json.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; + +import com.clearspring.analytics.util.Pair; + +public class LocalGeneralUtilities { + + public LocalGeneralUtilities() { + // TODO Auto-generated constructor stub + } + public static final String FILE_PATH = FileHandling.getBasePath() + "\\src\\main\\resources\\Files\\VNFs\\"; + public static final String Env_FILE_PATH = FileHandling.getBasePath() + "\\src\\main\\resources\\Files\\Env_files\\"; + public static String downloadPath = "C:\\Users\\th0695\\Downloads"; + +public static String getValueFromJsonResponse(String response, String fieldName) { + try { + JSONObject jsonResp = (JSONObject) JSONValue.parse(response); + Object fieldValue = jsonResp.get(fieldName); + return fieldValue.toString(); + + } catch (Exception e) { + return null; + } + +} + +public static List getValuesFromJsonArray(RestResponse message) throws Exception { + List artifactTypesArrayFromApi = new ArrayList(); + + org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse()); + JSONArray jArr = responseObject.getJSONArray("componentInstances"); + + for (int i = 0; i < jArr.length(); i++) { + org.json.JSONObject jObj = jArr.getJSONObject(i); + String value = jObj.get("uniqueId").toString(); + + artifactTypesArrayFromApi.add(value); + } + return artifactTypesArrayFromApi; +} + +public static String simpleOnBoarding(String fileName, String filePath,User user) throws Exception { + OnboardingUtils.createVendorLicense(user); + Pair> createVendorSoftwareProduct = OnboardingUtils + .createVendorSoftwareProduct(fileName, filePath, user); + String vspName = createVendorSoftwareProduct.left; + HomePage.showVspRepository(); + OnboardingUtils.importVSP(createVendorSoftwareProduct); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()).click(); + GeneralUIUtils.waitForLoader(); + return vspName; +} + +//check if file downloaded successfully. +public static boolean isFileDownloaded(String downloadPath, String fileName) { + boolean flag = false; + File dir = new File(downloadPath); + File[] dir_contents = dir.listFiles(); + for (int i = 0; i < dir_contents.length; i++) { + if (dir_contents[i].getName().equals(fileName)) + return flag = true; + } + return flag; +} +} 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 new file mode 100644 index 0000000000..949a20b4a9 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java @@ -0,0 +1,269 @@ +/*- + * ============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.ci.tests.US; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.UploadArtifactPopup; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +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.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + + +public class MIBsArtifactsOnResourceInstance extends SetupCDTest { + + private String folder =""; + + @DataProvider(name="mibsArtifactCRUDUi") + public static Object[][] dataProviderMibsArtifactCRUDUi() { + return new Object[][] { + {"mibsvFW_VFC.yml", ResourceTypeEnum.VFC}, + {"mibsVL.yml", ResourceTypeEnum.VL}, + {"mibsCP.yml", ResourceTypeEnum.CP} + }; + } + + // US820414 + // Artifact UI CRUD on VFC/VL/CP + // TODO: Change download validation from download artifact via external API to UI + @Test(dataProvider="mibsArtifactCRUDUi") + public void mibsArtifactCRUDUi(String fileName, ResourceTypeEnum resourceTypeEnum) throws Exception { + 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()); + + // get resourceUUID from BE + String resourceUUID = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1").getUUID(); + + // 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL. + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "SNMP_TRAP")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "SNMP_POLL")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + + assertTrue("Only created artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + + String artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + deploymentArtifact.getArtifactLabel()).getText(); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(deploymentArtifact.getArtifactLabel(), null, "1", deploymentArtifact.getArtifactType(), true, true, true, false); + + // Verify that uploaded correct file by download artifact via external api + RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE.toString()); + File file = new File(deploymentArtifact.getFilepath() + deploymentArtifact.getFilename()); + String readFileToString = FileUtils.readFileToString(file); + Assert.assertEquals(restResponse.getResponse(), readFileToString); + + DeploymentArtifactPage.clickEditArtifact(deploymentArtifact.getArtifactLabel()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filePath, "CP.yml"); + artifactPopup.clickDoneButton(); + + assertTrue("Only updated artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + Assert.assertNotEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + deploymentArtifact.getArtifactLabel()).getText(), artifactUUID); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(deploymentArtifact.getArtifactLabel(), null, "2", deploymentArtifact.getArtifactType(), true, true, true, false); + + // Verify that updated correct file by download artifact via external api + artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + deploymentArtifact.getArtifactLabel()).getText(); + restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE.toString()); + file = new File(deploymentArtifact.getFilepath() + "CP.yml"); + readFileToString = FileUtils.readFileToString(file); + Assert.assertEquals(restResponse.getResponse(), readFileToString); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifact.getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + + assertTrue("No artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(0)); + } + + } + + @DataProvider(name="mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption") + public static Object[][] dataProviderMibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption() { + return new Object[][] { + {"mibs1vFW_VFC.yml", ResourceTypeEnum.VFC}, + // TODO: delete comment below when we will have support for VL on canvas +// {"mibs1VL.yml", ResourceTypeEnum.VL}, + {"mibs1CP.yml", ResourceTypeEnum.CP} + }; + } + + // US820414 + // Import VFC/VL/CP, upload MIBs artifacts then drag it on VF & verify that deployment artifact have only download option + @Test(dataProvider="mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption") + public void mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption(String fileName, ResourceTypeEnum resourceTypeEnum) throws Exception { + + setLog("mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption"); + + String filePath = FileHandling.getFilePath(folder); + + // import Resource + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser()); + ResourceUIUtils.importVfc(resourceMetaData, filePath, fileName, getUser()); + + // 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL. + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "SNMP_TRAP")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "SNMP_POLL")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + // 3. Check-in DataProvider resource. + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + // 4. Create VF. + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + // 5. Click on composition. + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + // 6. Drag created DataProvider resource to canvas. + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(resourceMetaData.getName()); + CanvasElement resourceInstance = vfCanvasManager.createElementOnCanvas(resourceMetaData.getName()); + + // 7. Click on DataProvider resource. + vfCanvasManager.clickOnCanvaElement(resourceInstance); + + // 8. Click on deployment artifacts in right menu. + CompositionPage.showDeploymentArtifactTab(); + + // 9. Verify that each uploaded MIBs artifacts shows in deployment artifacts. + // 10. Verify that only have download option. + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + // Hover over webelement -> check that only dowload button displayed + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + deploymentArtifact.getArtifactLabel()).isDisplayed(), true); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + deploymentArtifact.getArtifactLabel()), false); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false); + } + + + } + + // US820414 + // Create VF, upload MIBs artifacts then drag it on service & verify that deployment artifact have only download option + @Test + public void mibsArtifacsOnVFInstanceShouldOnlyHaveDownloadOption() throws Exception { + String filePath = FileHandling.getFilePath(folder); + + // 1. Create VF. + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + + // 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL. + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "SNMP_TRAP")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "SNMP_POLL")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + // 3. Check-in VF. + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + // 4. Create service. + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + // 5. Click on composition. + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + // 6. Drag created DataProvider s to canvas. + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(resourceMetaData.getName()); + CanvasElement resourceInstance = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + + // 7. Click on DataProvider resource. + canvasManager.clickOnCanvaElement(resourceInstance); + + // 8. Click on deployment artifacts in right menu. + CompositionPage.showDeploymentArtifactTab(); + + // 9. Verify that each uploaded MIBs artifacts shows in deployment artifacts. + // 10. Verify that only have download option. + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + // Hover over webelement -> check that only dowload button displayed + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + deploymentArtifact.getArtifactLabel()).isDisplayed(), true); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + deploymentArtifact.getArtifactLabel()), false); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false); + } + } + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MobProxy.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MobProxy.java new file mode 100644 index 0000000000..179c300a18 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MobProxy.java @@ -0,0 +1,144 @@ +/*- + * ============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.ci.tests.US; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.List; + +import java.net.Proxy; + +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.remote.CapabilityType; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.testng.AssertJUnit; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.github.markusbernhardt.proxy.ProxySearch; +import com.github.markusbernhardt.proxy.ProxySearch.Strategy; + +import net.lightbody.bmp.BrowserMobProxyServer; +import net.lightbody.bmp.client.ClientUtil; +import net.lightbody.bmp.core.har.Har; +import net.lightbody.bmp.proxy.CaptureType; + +public class MobProxy { + public static WebDriver driver; + public static BrowserMobProxyServer server; + + @BeforeClass + public void setup() throws Exception { + + ProxySearch proxySearch = new ProxySearch(); + proxySearch.addStrategy(Strategy.OS_DEFAULT); + proxySearch.addStrategy(Strategy.JAVA); + proxySearch.addStrategy(Strategy.BROWSER); + ProxySelector proxySelector = proxySearch.getProxySelector(); + + ProxySelector.setDefault(proxySelector); + URI home = URI.create("http://www.google.com"); + System.out.println("ProxySelector: " + proxySelector); + System.out.println("URI: " + home); + List proxyList = proxySelector.select(home); + String host = null; + String port = null; + if (proxyList != null && !proxyList.isEmpty()) { + for (Proxy proxy : proxyList) { + System.out.println(proxy); + SocketAddress address = proxy.address(); + if (address instanceof InetSocketAddress) { + host = ((InetSocketAddress) address).getHostName(); + port = Integer.toString(((InetSocketAddress) address).getPort()); + System.setProperty("http.proxyHost", host); + System.setProperty("http.proxyPort", port); + } + } + } + + server = new BrowserMobProxyServer(); + InetSocketAddress address = new InetSocketAddress(host, Integer.parseInt(port)); + server.setChainedProxy(address); + server.start(); + int port1 = server.getPort(); + DesiredCapabilities seleniumCapabilities = new DesiredCapabilities(); + seleniumCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + seleniumCapabilities.setCapability(CapabilityType.PROXY, ClientUtil.createSeleniumProxy(server)); + driver = new FirefoxDriver(seleniumCapabilities); + server.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT); + System.out.println("Port started:" + port1); + } + + @Test + public void first_test1() throws InterruptedException { + + server.newHar("asdc.har"); + + driver.get("https://www.e-access.att.com/QA-SCRUM1/sdc1/portal#/dashboard"); + driver.manage().window().maximize(); + + WebElement userNameTextbox = driver.findElement(By.name("userid")); + userNameTextbox.sendKeys("m99121"); + WebElement passwordTextbox = driver.findElement(By.name("password")); + passwordTextbox.sendKeys("66-Percent"); + + WebElement submitButton = driver.findElement(By.name("btnSubmit")); + submitButton.click(); + Thread.sleep(300); + WebElement buttonOK = driver.findElement(By.name("successOK")); + AssertJUnit.assertTrue(buttonOK.isDisplayed()); + buttonOK.click(); + Thread.sleep(2000); + driver.findElement(By.xpath(getXpath("main-menu-button-catalog"))).click(); + Thread.sleep(2000); + driver.findElement(By.xpath(getXpath("checkbox-service"))).click(); + Thread.sleep(2000); + } + + public static String getXpath(String dataTestId){ + return String.format("//*[@data-tests-id='%s']", dataTestId); + } + + @AfterClass + public void shutdown() { + try { + + // Get the HAR data + Har har = server.getHar(); + File harFile = new File("C:\\temp\\asdc.har"); + har.writeTo(harFile); + + } catch (IOException ioe) { + ioe.printStackTrace(); + } + driver.quit(); + server.stop(); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/NewArtifactTypeGuide.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/NewArtifactTypeGuide.java new file mode 100644 index 0000000000..9d460b0b0c --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/NewArtifactTypeGuide.java @@ -0,0 +1,123 @@ +/*- + * ============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.ci.tests.US; + +import static org.testng.AssertJUnit.assertTrue; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.UploadArtifactPopup; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + + +public class NewArtifactTypeGuide extends SetupCDTest { + + private String folder =""; + + // US820276 + // Upload information artifact of type GUIDE to VF + @Test + public void crudGuideInformationArtifactForVf() throws Exception { + String filePath = FileHandling.getFilePath(folder); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "GUIDE"); + + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationArtifact); + + assertTrue("Only created artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + + String artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "1", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickEditArtifact(informationArtifact.getArtifactLabel()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + artifactPopup.loadFile(filePath, "CP.yml"); + artifactPopup.clickDoneButton(); + + assertTrue("Only updated artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + Assert.assertNotEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(), artifactUUID); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "2", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickDeleteArtifact(informationArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + } + + // US820276 + // Upload information artifact of type GUIDE to VFC + @Test + public void crudGuideInformationArtifactForVfc() throws Exception { + String filePath = FileHandling.getFilePath(folder); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC, getUser()); + ResourceUIUtils.importVfc(resourceMetaData, filePath, "guidevFW_VFC.yml", getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "GUIDE"); + + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationArtifact); + + assertTrue("Only created artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + String artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "1", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickEditArtifact(informationArtifact.getArtifactLabel()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + artifactPopup.loadFile(filePath, "CP.yml"); + artifactPopup.clickDoneButton(); + + assertTrue("Only updated artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + Assert.assertNotEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(), artifactUUID); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "2", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickDeleteArtifact(informationArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + } + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java new file mode 100644 index 0000000000..1f85ec21fb --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java @@ -0,0 +1,117 @@ +/*- + * ============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.ci.tests.US; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.pages.UploadArtifactPopup; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.testng.annotations.Test; + + +public class RemoveRestrictionOfDeploymentArtifacts extends SetupCDTest { + + private String folder =""; + + // US833330 - Story [BE] - remove restriction of deployment artifacts + // Create service without resource instance and without deployment artifacts and verify it can submit for testing + @Test + public void createServiceWithoutRIAndArtifacts() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + } + + + // US833330 - Story [BE] - remove restriction of deployment artifacts + // Create service with VL resource instance and without deployment artifacts and verify it can submit for testing + @Test + public void createServiceWithVlAndWithoutArtfiacts() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.NETWORK); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.NETWORK); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.NETWORK); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + } + + // US833330 - Story [BE] - remove restriction of deployment artifacts + // Create service with VF with informational artifacts and verify it can submit for testing + @Test + public void createServiceWithInformationalArtifacts() throws Exception { + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + String filePath = FileHandling.getFilePath(folder); + List informationalArtifactList = new ArrayList(); + informationalArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + informationalArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "GUIDE")); + for (ArtifactInfo informationalArtifact : informationalArtifactList) { + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact, new UploadArtifactPopup(true)); + } + ResourceGeneralPage.clickSubmitForTestingButton(resourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + TesterOperationPage.certifyComponent(resourceMetaData.getName()); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement resourceInstance = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java new file mode 100644 index 0000000000..80801afafb --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java @@ -0,0 +1,107 @@ +/*- + * ============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.ci.tests.US; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.sanity.Onboard; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; +import org.testng.annotations.Test; + +import com.clearspring.analytics.util.Pair; + +public class Service_Tests_UI extends SetupCDTest{ + + public Service_Tests_UI() { + // TODO Auto-generated constructor stub + } + + // US839610 - E2E Declare VL / CP properties as inputs in service level + @Test + public void declareVL_CP_InputsInServiceLevel() throws Exception { + String vnfFile = "FDNT.zip"; + Pair> VspName =OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + ServiceReqDetails servicemetadata = ElementFactory.getDefaultService(getUser()); + ServiceUIUtils.createService(servicemetadata, getUser()); + GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION); + CanvasManager service_CanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(VspName.left); + GeneralUIUtils.waitForLoader(); + CanvasElement vfi_Element = service_CanvasManager.createElementOnCanvas(VspName.left); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()) + .click(); + GeneralUIUtils.findComponentAndClick(servicemetadata.getName()); + GeneralUIUtils.moveToStep(StepsEnum.INPUTS); + GeneralUIUtils.getWebElementByTestID("inputs-vf-instance-1").click(); +// GeneralUIUtils.onNameClicked(input); + } + @Test + public void CreateServiceWithCpInstance() throws Exception { + String vnfFile = "FDNT.zip"; + Pair> VspName =OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + ServiceReqDetails servicemetadata = ElementFactory.getDefaultService(getUser()); + ServiceUIUtils.createService(servicemetadata, getUser()); + GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION); + CanvasManager service_CanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(VspName.left); + GeneralUIUtils.waitForLoader(); + CanvasElement vfi_Element = service_CanvasManager.createElementOnCanvas(VspName.left); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()) + .click(); + GeneralUIUtils.findComponentAndClick(servicemetadata.getName()); + GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_VIEW); + String version = GeneralUIUtils.getWebElementByTestID("versionHeader").getText(); + RestResponse service = ServiceRestUtils.getServiceByNameAndVersion(getUser(), servicemetadata.getName(), + version.substring(1)); + List serviceResponseArray = new ArrayList(); + serviceResponseArray =LocalGeneralUtilities.getValuesFromJsonArray(service); + servicemetadata.setUniqueId(serviceResponseArray.get(0)); + RestResponse serviceResponse = ServiceRestUtils.getService(servicemetadata, getUser()); + if (serviceResponseArray.get(0).contains("VL")) { + System.out.println("OK"); + } + + } + + @Override + protected UserRoleEnum getRole() { + // TODO Auto-generated method stub + return UserRoleEnum.DESIGNER; + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java new file mode 100644 index 0000000000..089ad9580f --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java @@ -0,0 +1,125 @@ +/*- + * ============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.ci.tests.US; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils; +import org.testng.Assert; + + + + + + +public class Testing { + + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + + File path = new File("C:\\Users\\rp955r\\Desktop\\US\\US831517\\TCExport\\TC1459238.yml"); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path); + + Map vl_us831517_1 = new HashMap(); + vl_us831517_1.put("property_1", true); + vl_us831517_1.put("property_2", "init_value_2"); + vl_us831517_1.put("property_3", "init_value_3"); + + + Map vl_us831517_2 = new HashMap(); + vl_us831517_2.put("property_1", false); + vl_us831517_2.put("property_2", "init_value_2"); + vl_us831517_2.put("property_3", "new_value_3"); + + Map vl_us831517_3 = new HashMap(); + vl_us831517_3.put("property_1", true); + vl_us831517_3.put("property_2", "init_value_2"); + vl_us831517_3.put("property_3", "init_value_3"); + vl_us831517_3.put("property_4", false); + vl_us831517_3.put("property_5", "init_value_5"); + + Map> predefinedProperties = new HashMap>(); + predefinedProperties.put("VL_US831517_1", vl_us831517_1); + predefinedProperties.put("VL_US831517_2", vl_us831517_2); + predefinedProperties.put("VL_US831517_3", vl_us831517_3); + + validateNodeTemplatesProperties(predefinedProperties, toscaDefinition); + + + + } + + + + private static void validateNodeTemplatesProperties(Map> predefinedMap, ToscaDefinition toscaDefinition) { + + for(String key: predefinedMap.keySet()) { + Map nodeTemplateProperties = getNodeTemplatePropertiesByNodeTemplateType(key, toscaDefinition); + + predefinedMap.get(key).forEach((i,j) -> { + Assert.assertEquals(nodeTemplateProperties.get(i), j, "Expected that the properties will be equal"); + }); + } + + } + + // Get properties by type + private static Map getNodeTemplatePropertiesByNodeTemplateType(String nodeTemplateType, ToscaDefinition toscaDefinition) { + Map propertiesMap = null; + + Set nodeTemplates = getNodeTemplates(toscaDefinition); + + for(String nodeTemplate: nodeTemplates) { + String currentNodeTemplateType = getNodeTemplateType(toscaDefinition, nodeTemplate); + currentNodeTemplateType = currentNodeTemplateType.substring(currentNodeTemplateType.lastIndexOf(".") + 1); + if(currentNodeTemplateType.equals(nodeTemplateType)) { + propertiesMap = getNodeTemplateProperties(toscaDefinition, nodeTemplate); + break; + } + } + + return propertiesMap; + } + + // Get node templates + private static Set getNodeTemplates(ToscaDefinition toscaDefinition) { + Set resourceInstanceArray = toscaDefinition.getTopology_template().getNode_templates().keySet(); + return resourceInstanceArray; + } + + // Get type of node template + private static String getNodeTemplateType(ToscaDefinition toscaDefinition, String nodeTemplate) { + return toscaDefinition.getTopology_template().getNode_templates().get(nodeTemplate).getType(); + } + + // Get properties of node template + private static Map getNodeTemplateProperties(ToscaDefinition toscaDefinition, String nodeTemplate) { + Map propertiesMap = toscaDefinition.getTopology_template().getNode_templates().get(nodeTemplate).getProperties(); + return propertiesMap; + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java new file mode 100644 index 0000000000..a038c284e1 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java @@ -0,0 +1,156 @@ +/*- + * ============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.ci.tests.US; + +import static org.testng.AssertJUnit.assertNotNull; + +import java.awt.AWTException; +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ToscaArtifactsScreenEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.DownloadManager; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.CsarParserUtils; +import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.ci.tests.verificator.VfModuleVerificator; +import org.testng.annotations.Test; + +import com.clearspring.analytics.util.Pair; +import com.aventstack.extentreports.Status; + +/** + * @author al714h + * + */ + +public class VfModule extends SetupCDTest { + + + @Test + public void checkVfModulesCountAndStructure() throws Exception, AWTException { + +// String filepath = "src\\main\\resources\\Files\\VNFs"; + String filepath = FileHandling.getVnfRepositoryPath(); +// String vnfFile = "LDSA.zip"; + String vnfFile = "FDNT.zip"; + getExtendTest().log(Status.INFO, String.format("Going to onboard the VNF %s......", vnfFile)); + System.out.println(String.format("Going to onboard the VNF %s......", vnfFile)); + + OnboardingUtils.createVendorLicense(getUser()); + Pair> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(vnfFile, filepath, getUser()); + String vspName = createVendorSoftwareProduct.left; + // + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId")); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + List listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(latestFilefromDir); + // + getExtendTest().log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); + HomePage.showVspRepository(); + getExtendTest().log(Status.INFO, String.format("Going to import %s......", vnfFile.substring(0, vnfFile.indexOf(".")))); + + OnboardingUtils.importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + // Verify deployment artifacts + Map combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); + LinkedList deploymentArtifacts = ((LinkedList) combinedMap.get("Deployment")); + for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { + if(deploymentArtifact.getType().equals("HEAT_ENV")) { + continue; + } + System.out.println("--------------"); + System.out.println(deploymentArtifact.getFileName()); + System.out.println(deploymentArtifact.getType()); +// System.out.println(deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."))); + if(deploymentArtifact.getFileName().contains(".")) { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")), "1", deploymentArtifact.getType()); + } else { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim(), "1", deploymentArtifact.getType()); + } + + } + + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); + + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.searchForElement(vspName); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); + assertNotNull(vfElement); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue()); + latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + +// verification + Service service = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), serviceMetadata.getVersion()); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(latestFilefromDir); + +// compare number of vf modules defined in HEAT.meta file vs Service TOSCA yaml + VfModuleVerificator.compareNumberOfVfModules(listTypeHeatMetaDefinition, toscaDefinition); + VfModuleVerificator.verifyGroupMetadata(toscaDefinition, service); + + getExtendTest().log(Status.INFO, String.format("Onboarding %s test is passed ! ", vnfFile)); + + } + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Vf_Tests_UI.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Vf_Tests_UI.java new file mode 100644 index 0000000000..71c2612a82 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Vf_Tests_UI.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.US; + +import java.awt.AWTException; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ArtifactPageEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.sanity.Onboard; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class Vf_Tests_UI extends SetupCDTest{ + + public Vf_Tests_UI() { + // TODO Auto-generated constructor stub + } + public void uploadHeatEnvVFLevel() throws Exception { + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + } + +// @Test +// // Download ENV file from VF level. +// public void downloadEnvVFLevel() throws AWTException, Exception { +// String firstEnvArtifact = "base_stsi_dnt_frwl.env"; +// String secondEnvArtifact = "mod_vmsi_dnt_fw_parent.env"; +// String filePath=Config.instance().getWindowsDownloadDirectory(); +// String vnfFile = "FDNT.zip"; +// OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); +// Map mD5OfFilesToValidate = new HashMap(); +// mD5OfFilesToValidate.put(firstEnvArtifact,new File(FileHandling.getResourcesEnvFilesPath() + firstEnvArtifact)); +// mD5OfFilesToValidate.put(secondEnvArtifact,new File(FileHandling.getResourcesEnvFilesPath() + secondEnvArtifact)); +// ListfilesToBeDeleted=new ArrayList<>(mD5OfFilesToValidate.values()); +// FileHandling.deleteLastDowloadedFiles(filesToBeDeleted); +// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); +// List allDisplayedArtifcats = DeploymentArtifactPage.getDeploymentArtifactsNamesWorkSpace(); +// for (int i=0;i assetsName = importThreeAsset(fileName_vl1, fileName_vl2, fileName_vl3, resourceTypeEnum); + + if(ComponentTypeEnum.SERVICE == componentTypeEnum) { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + } else { + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + } + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement resourceInstance1 = canvasManager.createElementOnCanvas(assetsName.get(0)); + CanvasElement resourceInstance2 = canvasManager.createElementOnCanvas(assetsName.get(1)); + CanvasElement resourceInstance3 = canvasManager.createElementOnCanvas(assetsName.get(2)); + + canvasManager.clickOnCanvaElement(resourceInstance1); + CompositionPage.showPropertiesAndAttributesTab(); + PropertiesUIUtils.changePropertyDefaultValueInComposition("property_1", "false"); + + canvasManager.clickOnCanvaElement(resourceInstance2); + CompositionPage.showPropertiesAndAttributesTab(); + PropertiesUIUtils.changePropertyDefaultValueInComposition("property_3", "customize"); + + canvasManager.clickOnCanvaElement(resourceInstance3); + CompositionPage.showPropertiesAndAttributesTab(); + PropertiesUIUtils.changePropertyDefaultValueInComposition("property_2", "customize derived"); + PropertiesUIUtils.changePropertyDefaultValueInComposition("property_5", "customize new"); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue()); + + // TODO: Replace it by automatic download to path + // TODO: After it remove + File path = new File("C:\\Users\\rp955r\\Desktop\\US\\US831517\\TCExport\\TC1459238.yml"); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path); + + Map vl_us831517_1 = new HashMap(); + vl_us831517_1.put("property_1", false); + vl_us831517_1.put("property_2", "init_value_2"); + vl_us831517_1.put("property_3", "init_value_3"); + + + Map vl_us831517_2 = new HashMap(); + vl_us831517_2.put("property_1", false); + vl_us831517_2.put("property_2", "init_value_2"); + vl_us831517_2.put("property_3", "customize"); + + Map vl_us831517_3 = new HashMap(); + vl_us831517_3.put("property_1", true); + vl_us831517_3.put("property_2", "customize derived"); + vl_us831517_3.put("property_3", "init_value_3"); + vl_us831517_3.put("property_4", false); + vl_us831517_3.put("property_5", "customize new"); + + Map> predefinedProperties = new HashMap>(); + predefinedProperties.put("VL_US831517_1", vl_us831517_1); + predefinedProperties.put("VL_US831517_2", vl_us831517_2); + predefinedProperties.put("VL_US831517_3", vl_us831517_3); + + validateNodeTemplatesProperties(predefinedProperties, toscaDefinition); + + RestCDUtils.deleteOnDemand(); + } + + @DataProvider(name="serviceVfUsedVlsCps") + public static Object[][] dataProviderServiceVfUsedVlsCps() { + return new Object[][] { + {"VL_US831517_1.yml", "VL_US831517_2.yml", "VL_US831517_3.yml", ResourceTypeEnum.VL, ComponentTypeEnum.SERVICE}, + {"CP_US831517_1.yml", "CP_US831517_2.yml", "CP_US831517_3.yml", ResourceTypeEnum.CP, ComponentTypeEnum.SERVICE}, + {"VL_US831517_1.yml", "VL_US831517_2.yml", "VL_US831517_3.yml", ResourceTypeEnum.VL, ComponentTypeEnum.RESOURCE}, + {"CP_US831517_1.yml", "CP_US831517_2.yml", "CP_US831517_3.yml", ResourceTypeEnum.CP, ComponentTypeEnum.RESOURCE}, + }; + } + + + // US831517 - Story [BE] - Extend node_template properties with default values + @Test(dataProvider="serviceVfUsedVlsCps") + public void serviceVfUsedVlsCps(String fileName_vl1, String fileName_vl2, String fileName_vl3, ResourceTypeEnum resourceTypeEnum, ComponentTypeEnum componentTypeEnum) throws Exception { + setLog("Extend node_template properties with default values"); + + // import Resource + LinkedList assetsName = importThreeAsset(fileName_vl1, fileName_vl2, fileName_vl3, resourceTypeEnum); + + if(ComponentTypeEnum.SERVICE == componentTypeEnum) { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + } else { + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + } + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.createElementOnCanvas(assetsName.get(0)); + canvasManager.createElementOnCanvas(assetsName.get(1)); + canvasManager.createElementOnCanvas(assetsName.get(2)); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue()); + + // TODO: Replace it by automatic download to path + // TODO: After it remove + File path = new File("C:\\Users\\rp955r\\Desktop\\US\\US831517\\TCExport\\TC1459238.yml"); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path); + + Map vl_us831517_1 = new HashMap(); + vl_us831517_1.put("property_1", true); + vl_us831517_1.put("property_2", "init_value_2"); + vl_us831517_1.put("property_3", "init_value_3"); + + + Map vl_us831517_2 = new HashMap(); + vl_us831517_2.put("property_1", false); + vl_us831517_2.put("property_2", "init_value_2"); + vl_us831517_2.put("property_3", "new_value_3"); + + Map vl_us831517_3 = new HashMap(); + vl_us831517_3.put("property_1", true); + vl_us831517_3.put("property_2", "init_value_2"); + vl_us831517_3.put("property_3", "init_value_3"); + vl_us831517_3.put("property_4", false); + vl_us831517_3.put("property_5", "init_value_5"); + + Map> predefinedProperties = new HashMap>(); + predefinedProperties.put("VL_US831517_1", vl_us831517_1); + predefinedProperties.put("VL_US831517_2", vl_us831517_2); + predefinedProperties.put("VL_US831517_3", vl_us831517_3); + + validateNodeTemplatesProperties(predefinedProperties, toscaDefinition); + + RestCDUtils.deleteOnDemand(); + } + + private LinkedList importThreeAsset(String fileName_vl1, String fileName_vl2, String fileName_vl3, ResourceTypeEnum resourceTypeEnum) throws Exception { + LinkedList assetsNames = new LinkedList(); + + String filePath = System.getProperty("filepath"); + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath() + File.separator + "US831517" + File.separator; + } + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator + "US831517" + File.separator; + } + + // import Resource + ResourceReqDetails resourceMetaDataVl1 = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser()); + assetsNames.add(resourceMetaDataVl1.getName()); + ResourceUIUtils.importVfc(resourceMetaDataVl1, filePath, fileName_vl1, getUser()); + GeneralPageElements.clickSubmitForTestingButton(resourceMetaDataVl1.getName()); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(resourceMetaDataVl1.getName()); + TesterOperationPage.certifyComponent(resourceMetaDataVl1.getName()); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + ResourceReqDetails resourceMetaDataVl2 = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser()); + assetsNames.add(resourceMetaDataVl2.getName()); + ResourceUIUtils.importVfc(resourceMetaDataVl2, filePath, fileName_vl2, getUser()); + GeneralPageElements.clickCheckinButton(resourceMetaDataVl2.getName()); + + ResourceReqDetails resourceMetaDataVl3 = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser()); + assetsNames.add(resourceMetaDataVl3.getName()); + ResourceUIUtils.importVfc(resourceMetaDataVl3, filePath, fileName_vl3, getUser()); + GeneralPageElements.clickCheckinButton(resourceMetaDataVl2.getName()); + + return assetsNames; + } + + + private static void validateNodeTemplatesProperties(Map> predefinedMap, ToscaDefinition toscaDefinition) { + + for(String key: predefinedMap.keySet()) { + Map nodeTemplateProperties = getNodeTemplatePropertiesByNodeTemplateType(key, toscaDefinition); + + predefinedMap.get(key).forEach((i,j) -> { + Assert.assertEquals(nodeTemplateProperties.get(i), j, "Expected that the properties will be equal"); + }); + } + + } + + // Get properties by type + private static Map getNodeTemplatePropertiesByNodeTemplateType(String nodeTemplateType, ToscaDefinition toscaDefinition) { + Map propertiesMap = null; + + Set nodeTemplates = getNodeTemplates(toscaDefinition); + + for(String nodeTemplate: nodeTemplates) { + String currentNodeTemplateType = getNodeTemplateType(toscaDefinition, nodeTemplate); + currentNodeTemplateType = currentNodeTemplateType.substring(currentNodeTemplateType.lastIndexOf(".") + 1); + if(currentNodeTemplateType.equals(nodeTemplateType)) { + propertiesMap = getNodeTemplateProperties(toscaDefinition, nodeTemplate); + break; + } + } + + return propertiesMap; + } + + // Get node templates + private static Set getNodeTemplates(ToscaDefinition toscaDefinition) { + Set resourceInstanceArray = toscaDefinition.getTopology_template().getNode_templates().keySet(); + return resourceInstanceArray; + } + + // Get type of node template + private static String getNodeTemplateType(ToscaDefinition toscaDefinition, String nodeTemplate) { + return toscaDefinition.getTopology_template().getNode_templates().get(nodeTemplate).getType(); + } + + // Get properties of node template + private static Map getNodeTemplateProperties(ToscaDefinition toscaDefinition, String nodeTemplate) { + Map propertiesMap = toscaDefinition.getTopology_template().getNode_templates().get(nodeTemplate).getProperties(); + return propertiesMap; + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/businesslogic/ArtifactBusinessLogic.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/businesslogic/ArtifactBusinessLogic.java new file mode 100644 index 0000000000..6dce83fd40 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/businesslogic/ArtifactBusinessLogic.java @@ -0,0 +1,208 @@ +/*- + * ============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.ci.tests.businesslogic; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.ci.tests.datatypes.HeatAndHeatEnvNamesPair; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.HeatWithParametersDefinition; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; + +import com.clearspring.analytics.util.Pair; + +public class ArtifactBusinessLogic { + + private final static String[] okFileExtensions = new String[] {"yaml", "yml", "env"}; + private static final String PARAMETERS = "parameters"; + private static final String DEPLOYMENT = "Deployment"; + + public static synchronized Map createEnvFilesListFromCsar(String vspName, String filePath) throws Exception{ + Map generatedEnvFiles = new HashMap<>(); + File csarFile= HomePage.downloadVspCsarToDefaultDirectory(vspName); + FileHandling.unzip(csarFile.toString(), filePath); + List yamlList = getHeatFilesCreatedFromCsar(csarFile, filePath); + Map filesPairMap = getFilesPairMap(yamlList); + generatedEnvFiles = generateDefaultEnvFiles(filesPairMap, filePath); + return generatedEnvFiles; + } + + public static synchronized List getHeatFilesCreatedFromCsar(File pathToDirectory, String filePath) throws Exception { + List fileList = new ArrayList<>(); + String artifactsFilePath = filePath + "Artifacts" + File.separator; + List fileListFromArtifactsDirectory = FileHandling.getHeatAndHeatEnvArtifactsFromZip(new File(artifactsFilePath), okFileExtensions); + Map combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(pathToDirectory.toString()); + LinkedList deploymentArtifacts = ((LinkedList) combinedMap.get(DEPLOYMENT)); + for(HeatMetaFirstLevelDefinition deploymentArtifact : deploymentArtifacts){ + String type = deploymentArtifact.getType(); + if(type.equals(ArtifactTypeEnum.HEAT.getType()) || + type.equals(ArtifactTypeEnum.HEAT_ENV.getType()) || + type.equals(ArtifactTypeEnum.HEAT_VOL.getType()) || + type.equals(ArtifactTypeEnum.HEAT_NET.getType())){ + File file = (new File(artifactsFilePath + deploymentArtifact.getFileName())); + if(fileListFromArtifactsDirectory.contains(file)){ + fileList.add(file); + }else{ + assertTrue("File " + file + " does not exist", false); + } + } + } + return fileList; + } + public static synchronized Map getFilesPairMap(List generatedEnvFiles) { + + Map heatAndHeatEnvPairs= new HashMap<>(); + for(File file : generatedEnvFiles){ + String[] fileName = file.getName().split("\\."); + String currentKey = fileName[0]; + String currentExtension = fileName[1]; + HeatAndHeatEnvNamesPair pair; + if(!heatAndHeatEnvPairs.containsKey(currentKey)){ + pair = new HeatAndHeatEnvNamesPair(); + heatAndHeatEnvPairs.put(currentKey, pair); + }else{ + pair = heatAndHeatEnvPairs.get(currentKey); + } + setFileToPair(file, currentExtension, pair); + } + return heatAndHeatEnvPairs; + } + + /** + * The method fill list of HeatWithParametersDefinition parameters + * @param deploymentArtifacts + * @return + */ + public static synchronized List extractHeatWithParametersDefinition(Map deploymentArtifacts) { + + List heatAndEnvLabelList = new ArrayList<>(); + + for (Entry artifactDefinitionChild : deploymentArtifacts.entrySet()){ + if(artifactDefinitionChild.getValue().getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())){ + for(Entry artifactDefinitionParent : deploymentArtifacts.entrySet()){ + if(artifactDefinitionChild.getValue().getGeneratedFromId().equals(artifactDefinitionParent.getValue().getUniqueId())){ + String heatLabel = artifactDefinitionParent.getValue().getArtifactLabel(); + String heatArtifactType = artifactDefinitionParent.getValue().getArtifactType(); + String heatArtifactDisplayName = artifactDefinitionParent.getValue().getArtifactDisplayName(); + List heatParameterDefinition = artifactDefinitionParent.getValue().getHeatParameters(); + String heatEnvLabel = artifactDefinitionChild.getValue().getArtifactLabel(); + String heatEnvArtifactType = artifactDefinitionChild.getValue().getArtifactType(); + heatAndEnvLabelList.add(new HeatWithParametersDefinition(heatLabel, heatEnvLabel, heatArtifactType, heatEnvArtifactType, heatArtifactDisplayName, heatParameterDefinition)); + break; + } + } + } + } + return heatAndEnvLabelList; + } + + + public static synchronized void setFileToPair(File file, String currentExtension, HeatAndHeatEnvNamesPair pair) { + if(!currentExtension.equals("env")){ + pair.setHeatFileName(file); + }else{ + pair.setHeatEnvFileName(file); + } + } + + public static synchronized Map generateDefaultEnvFiles(Map filesPairMap, String filePath) throws Exception { + + Map generatedEnvFilesMap = new HashMap<>(); + for(Entry pair : filesPairMap.entrySet()){ + Map> envParametersMap = getEnvParametersMap(pair); + File generatedEnvFile = createEnvFile(envParametersMap, new File(filePath + pair.getKey() + ".env")); + generatedEnvFilesMap.put(pair.getKey(), generatedEnvFile); + } + return generatedEnvFilesMap; + } + + public static synchronized File createEnvFile(Map> envParametersMap, File fileToWrite) throws IOException { + + FileHandling.writeToFile(fileToWrite, PARAMETERS+":", 0); + FileHandling.writeToFile(fileToWrite, envParametersMap, 2); + return fileToWrite; + } + + public static synchronized Map> getEnvParametersMap(Entry pair) throws Exception { + File heatFileName = pair.getValue().getHeatFileName(); + File heatEnvFileName = pair.getValue().getHeatEnvFileName(); + Map> envParametersMap = new HashMap<>(); + fillParametersMapFromHeatFile(heatFileName, envParametersMap); + fillParametersMapFromHeatEnvFile(heatEnvFileName, envParametersMap); + return envParametersMap; + } + + public static synchronized void fillParametersMapFromHeatEnvFile(File heatEnvFileName, Map> envParametersMap) throws Exception { + if(heatEnvFileName != null){ + Map mapHeatEnvFileParameters = FileHandling.parseYamlFileToMapByPattern(heatEnvFileName, PARAMETERS); + for (Map.Entry parameter : mapHeatEnvFileParameters.entrySet()){ + String key = parameter.getKey(); + Pair pair; + if(envParametersMap.containsKey(key)){ + if(envParametersMap.get(key).left.equals("string") && parameter.getValue() != null){ + pair = Pair.create(envParametersMap.get(key).left, "\"" + parameter.getValue() + "\""); + }else if(envParametersMap.get(key).left.equals("string") && parameter.getValue() == null){ + pair = Pair.create(envParametersMap.get(key).left, ""); + }else if(parameter.getValue() == null){ + pair = Pair.create(envParametersMap.get(key).left, ""); + }else{ + pair = Pair.create(envParametersMap.get(key).left, parameter.getValue()); + } + envParametersMap.put(key, pair); + } + } + } + } + + @SuppressWarnings("unchecked") + public static synchronized void fillParametersMapFromHeatFile(File heatFileName, Map> envParametersMap) throws Exception { + Map mapHeatFileParameters = FileHandling.parseYamlFileToMapByPattern(heatFileName, PARAMETERS); + for (Map.Entry parameter : mapHeatFileParameters.entrySet()){ + Map value = (Map) parameter.getValue(); + Pair pair; + if(value.get("type").toString().equals("string") && value.get("default") != null ){ + pair = Pair.create(value.get("type").toString(), "\"" + value.get("default") + "\""); + }else if(value.get("type").toString().equals("string") && value.get("default") == null){ + pair = Pair.create(value.get("type").toString(), ""); + }else if(value.get("default") == null){ + pair = Pair.create(value.get("type").toString(), ""); + }else{ + pair = Pair.create(value.get("type").toString(), value.get("default")); + } + envParametersMap.put(parameter.getKey(), pair); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java new file mode 100644 index 0000000000..1302cb52af --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactInfo.java @@ -0,0 +1,105 @@ +/*- + * ============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.ci.tests.datatypes; + +public class ArtifactInfo { + + private String filepath; + private String filename; + private String description; + private String artifactType; + private String artifactLabel; + private String artifactVersion; + + public ArtifactInfo(String filepath, String filename, String description, String artifactLabel, + String artifactType) { + super(); + this.filepath = filepath; + this.filename = filename; + this.description = description; + this.artifactType = artifactType; + this.artifactLabel = artifactLabel; + } + + public ArtifactInfo(String filepath, String filename, String description, String artifactLabel, + String artifactType, String artifactVersion) { + super(); + this.filepath = filepath; + this.filename = filename; + this.description = description; + this.artifactType = artifactType; + this.artifactLabel = artifactLabel; + this.artifactVersion = artifactVersion; + } + + public ArtifactInfo() { + super(); + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getFilepath() { + return filepath; + } + + public void setFilepath(String filepath) { + this.filepath = filepath; + } + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java new file mode 100644 index 0000000000..818b488d64 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java @@ -0,0 +1,65 @@ +/*- + * ============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.ci.tests.datatypes; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; + +public final class CanvasElement { + private final String uniqueId; + private ImmutablePair location; + private LeftPanelCanvasItems normativeElementType; + private String elementType; + + CanvasElement(String name, ImmutablePair location, LeftPanelCanvasItems canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + normativeElementType = canvasItem; + } + + CanvasElement(String name, ImmutablePair location, String canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + elementType = canvasItem; + } + + public String getUniqueId() { + return uniqueId; + } + + public ImmutablePair getLocation() { + return location; + } + + public void setLocation(ImmutablePair location) { + this.location = location; + } + + public LeftPanelCanvasItems getNormativeElementType() { + return normativeElementType; + } + + public String getElementType() { + return elementType; + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java new file mode 100644 index 0000000000..25ed4c2d91 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java @@ -0,0 +1,268 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.StaleElementReferenceException; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class CanvasManager { + private Map canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + private CanvasElement canvasElement; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_ELEMENT_Y_OFFSET = 30; + private static final int CANVAS_ELEMENT_X_OFFSET = 18; // 14 - 27 + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair newLocation) + throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveToFreeLocation(String containerName) { + int maxWait = 5000; + int sumOfWaiting = 0; + int napPeriod = 200; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.clickAndHold(); + actions.release(); + actions.perform(); + isKeepWaiting = GeneralUIUtils.getWebElementByTestID("selectedCompTitle").getText() + .equals(containerName); + sumOfWaiting += napPeriod; + if (sumOfWaiting > maxWait) { + Assert.fail("Can't click on VF"); + } + } + } + + public void clickOnCanvaElement(CanvasElement canvasElement) { + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.release(); + actions.perform(); + actions.click().perform(); + GeneralUIUtils.ultimateWait(); + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s selected", canvasElement.getElementType())); + } + + public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.ultimateWait(); + if (canvasElement.getElementType().contains("-")){ + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s removed", canvasElement.getElementType().split("-")[4])); + } + else{ + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s removed", canvasElement.getElementType())); + } + } + + private WebElement findClickElement(String dataTestId) { + int attempts = 0; + while (attempts < 2) { + try { + return GeneralUIUtils.getWebElementByTestID(dataTestId); + } catch (StaleElementReferenceException e) { + } + attempts++; + } + return null; + } + + public CanvasElement createElementOnCanvas(String elementName) throws Exception { + String actionDuration = GeneralUIUtils.getActionDuration(() -> { + try { + canvasElement = createElementOnCanvasWithoutDuration(elementName); + } catch (Exception e) { + e.printStackTrace(); + } + }); + + if (canvasElement != null){ + ExtentTestActions.log(Status.INFO, String.format("The element %s should now be on the canvas", elementName), actionDuration); + } + return canvasElement; + } + + private CanvasElement createElementOnCanvasWithoutDuration(String elementDataTestId) throws Exception { + try { + WebElement element = findClickElement(elementDataTestId); + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(element, 20, 20); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + String uniqueId = elementDataTestId + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, elementDataTestId); + addCanvasElement(canvasElement); + GeneralUIUtils.ultimateWait(); + return canvasElement; + } + catch (Exception e) { + System.out.println("Can't create element on canvas"); + e.printStackTrace(); + } + return null; + } + + public CanvasElement createElementOnCanvas(LeftPanelCanvasItems canvasItem) throws Exception { + return createElementOnCanvas(canvasItem.getValue()); + } + + private ImmutablePair getFreePosition() { + ImmutablePair randomPosition = null; + boolean freePosition = false; + int minSpace = 150; + while (!freePosition) { + ImmutablePair tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair getRandomPosition() { + int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair(xElement, yElement); + } + + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Linking between the %s instance and the %s instance.", firstElement.getElementType(), secondElement.getElementType())); + drawSimpleLink(firstElement, secondElement); + selectReqAndCapAndConnect(); + ExtentTestActions.log(Status.INFO, String.format("The instances %s and %s should now be connected.", firstElement.getElementType(), secondElement.getElementType())); + } + + private void selectReqAndCapAndConnect() throws Exception { + // Select First Cap + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0).click(); + // Select First Req + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0).click(); + // Connect + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click(); + + GeneralUIUtils.waitForLoader(); + } + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + int yOffset = CANVAS_ELEMENT_Y_OFFSET; + int xOffset = CANVAS_ELEMENT_X_OFFSET; + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + } + + public String updateElementNameInCanvas(CanvasElement canvasElement, String newInstanceName) throws Exception { + GeneralUIUtils.ultimateWait();; + clickOnCanvaElement(canvasElement); + WebElement updateInstanceName = GeneralUIUtils.getWebElementBy(By.id("editPencil")); + updateInstanceName.click(); + WebElement instanceNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.INSTANCE_NAME_FIELD.getValue()); + String oldInstanceName = instanceNameField.getAttribute("value"); + instanceNameField.clear(); + instanceNameField.sendKeys(newInstanceName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("w-sdc-modal-resource-instance-name")); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Name of element instance changed from %s to %s", oldInstanceName, newInstanceName)); + return oldInstanceName; + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java new file mode 100644 index 0000000000..1335b51788 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CatalogFilterTitlesEnum.java @@ -0,0 +1,37 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum CatalogFilterTitlesEnum { + + TYPE("typeFilterTitle"), CATEGORIES("categoriesFilterTitle"), STATUS("statusFilterTitle"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogFilterTitlesEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java new file mode 100644 index 0000000000..ffa17ee607 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CheckBoxStatusEnum.java @@ -0,0 +1,50 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum CheckBoxStatusEnum { + CHECKOUT("", "checkbox-checkout"), + CHECKIN("", "checkbox-checkin"), + READY_FOR_TESTING("checkbox-readyfortesting","checkbox-1"), + IN_TESTING("checkbox-intesting", "checkbox-2"), + WAITING_FOR_DISTRIBUTION("", "checkbox-waitingforapproval"), + DISTRIBUTION_REJECTED("", "checkbox-distributionrejected"), + DISTRIBUTION_APPROVED("", "checkbox-distributionapproved"), + CERTIFIED("checkbox-certified", "checkbox-3"), + DISTRIBUTED("", "checkbox-4"), + IN_DESIGN("", "checkbox-0"); + + private String value; + private String value2; + + public String getValue() { + return value; + } + + public String getCatalogValue() { + return value2; + } + + private CheckBoxStatusEnum(String value, String value2) { + this.value = value; + this.value2 = value2; + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java new file mode 100644 index 0000000000..a49c5024a6 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CreateAndImportButtonsEnum.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes; + +public enum CreateAndImportButtonsEnum { + + IMPORT_VF, IMPORT_VFC, IMPORT_CP, IMPORT_VL, CREATE_VF, CREATE_SERVICE, CREATE_PRODUCT; + +} 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 new file mode 100644 index 0000000000..ef510b8a12 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java @@ -0,0 +1,835 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.Arrays; +import java.util.List; + +public final class DataTestIdEnum { + private DataTestIdEnum() { + } + + public enum Dashboard { + IMPORT_AREA("importButtonsArea"), + ADD_AREA("AddButtonsArea"), + BUTTON_ADD_VF("createResourceButton"), + BUTTON_ADD_SERVICE("createServiceButton"), + IMPORT_VFC("importVFCbutton"), + IMPORT_VF("importVFbutton"), + IMPORT_VFC_FILE("file-importVFCbutton"), + IMPORT_VF_FILE("file-importVFbutton"), + BUTTON_ADD_PRODUCT("createProductButton"); + + private String value; + + public String getValue() { + return value; + } + + private Dashboard(String value) { + this.value = value; + } + } + + public enum LifeCyleChangeButtons { + CREATE("create/save"), + CHECK_IN("check_in"), + SUBMIT_FOR_TESTING("submit_for_testing"), + START_TESTING("start_testing"), + ACCEPT("accept"), + CHECKOUT("check_out"); + + private String value; + + public String getValue() { + return value; + } + + private LifeCyleChangeButtons(String value) { + this.value = value; + } + } + + public enum DistributionChangeButtons { + APPROVE("approve"), + REJECT("reject"), + DISTRIBUTE("distribute"), + MONITOR("monitor"), + APPROVE_MESSAGE("checkindialog"), + RE_DISTRIBUTE("redistribute"); + + private String value; + + public String getValue() { + return value; + } + + private DistributionChangeButtons(String value) { + this.value = value; + } + } + + public enum InformationalArtifactsPlaceholders { + CLOUD_QUESTIONNAIRE("Cloud Questionnaire (completed)"), + FEATURES("Features"), + VENDOR_TEST_RESULT("Vendor Test Result"), + TEST_SCRIPTS("Test Scripts"), + RESOURCE_SECURITY_TEMPLATE("Resource Security Template"), + HEAT_TEMPLATE_FROM_VENDOR("HEAT Template from Vendor"), + CAPACITY("Capacity"); + + private String value; + + public String getValue() { + return value; + } + + private InformationalArtifactsPlaceholders(String value) { + this.value = value; + } + } + + public enum ModalItems { + BROWSE_BUTTON("browseButton"), + ADD("Add"), + DESCRIPTION("description"), + SUMBIT_FOR_TESTING_MESSAGE("changeLifeCycleMessage"), + OK("OK"), + CANCEL("Cancel"), + ACCEP_TESTING_MESSAGE("checkindialog"); + + private String value; + + public String getValue() { + return value; + } + + private ModalItems(String value) { + this.value = value; + } + } + + public enum LeftPanelCanvasItems { + BLOCK_STORAGE("BlockStorage"), + CINDER_VOLUME("CinderVolume"), + COMPUTE("Compute"), + LOAD_BALANCER("LoadBalancer"), + NOVA_SERVER("NovaServer"), + OBJECT_STORAGE("ObjectStorage"), + NEUTRON_PORT("NeutronPort"), + PORT("Port"), DATABASE("Database"), + NETWORK("Network"); + + private String value; + + public String getValue() { + return value; + } + + private LeftPanelCanvasItems(String value) { + this.value = value; + } + } + + public enum LinkMenuItems { + CANCEL_BUTTON("link-menu-button-cancel"), + CONNECT_BUTTON("link-menu-button-connect"), + LINK_ITEM_CAP("link-item-capabilities"), + LINK_ITEM_REQ("link-item-requirements"), + LINK_MENU("link-menu-open"); + + private String value; + + public String getValue() { + return value; + } + + private LinkMenuItems(String value) { + this.value = value; + } + } + + public enum GeneralCanvasItems { + CANVAS("canvas"), + CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), + DELETE_INSTANCE_BUTTON("e-sdc-small-icon-delete"), + UPDATE_INSTANCE_NAME("e-sdc-small-icon-update"), + INSTANCE_NAME_FIELD("instanceName"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralCanvasItems(String value) { + this.value = value; + } + } + + public enum ResourceMetadataEnum { + RESOURCE_NAME("name"), + DESCRIPTION("description"), + CATEGORY("selectGeneralCategory"), + VENDOR_NAME("vendorName"), + VENDOR_RELEASE("vendorRelease"), + TAGS("i-sdc-tag-input"), + CONTACT_ID("contactId"), + ICON(" iconBox"), + TAGS_TABLE("i-sdc-tag-text"); + private String value; + + public String getValue() { + return value; + } + + private ResourceMetadataEnum(String value) { + this.value = value; + } + } + + public enum GeneralElementsEnum { + CREATE_BUTTON("create/save"), + CHECKIN_BUTTON("check_in"), + CHECKOUT_BUTTON("check_out"), + SUBMIT_FOR_TESTING_BUTTON("submit_for_testing"), + DELETE_VERSION_BUTTON("delete_version"), + REVERT_BUTTON("revert"), + LIFECYCLE_STATE("formlifecyclestate"), + VERSION_HEADER("versionHeader"), + OK("OK"), + UPLOAD_FILE_INPUT("browseButton"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralElementsEnum(String value) { + this.value = value; + } + } + + public enum ArtifactPageEnum { + ADD_DEPLOYMENT_ARTIFACT("add-deployment-artifact-button"), + ADD_INFORMATIONAL_ARTIFACT("add-information-artifact-button"), + DOWNLOAD_ARTIFACT_ENV("download_env_"), + ADD_ANOTHER_ARTIFACT("add-another-artifact-button"), + EDIT_ARTIFACT("edit_"), //upload env file by its label(via deployment artifact view)/displayName(via Canvas) + DELETE_ARTIFACT("delete_"), + DOWNLOAD_ARTIFACT("download_"), + GET_DEPLOYMENT_ARTIFACT_DESCRIPTION("description"), + GET_INFORMATIONAL_ARTIFACT_DESCRIPTION("Description"), + OK("OK"), + TYPE("artifactType_"), + DEPLOYMENT_TIMEOUT("timeout_"), + VERSION("artifactVersion_"), + UUID("artifactUUID_"), + EDIT_PARAMETERS_OF_ARTIFACT("edit-parameters-of-"), + ARTIFACT_NAME("artifactDisplayName_"), + UPLOAD_HEAT_ENV_PARAMETERS("uplaodEnv_"), + VERSION_ENV("artifactEnvVersion_"); + private String value; + + public String getValue() { + return value; + } + + private ArtifactPageEnum(String value) { + this.value = value; + } + } + + public enum PropertiesPageEnum { + + ADD_NEW_PROPERTY("addGrey"), + EDIT_PROPERTY("edit_"), + DELETE_PROPERTY("delete_"), + PROPERTY_NAME("propertyName_"), + PROPERTY_DESCRIPTION("propertyDescription_"), + PROPERTY_TYPE("propertyType_"), + ENTRY_SCHEMA("propertySchema_"), + ADD("Add"), CANCEL("Cancel"), + DONE("Done"), + PROPERTY_ROW("propertyRow"), + SAVE("Save"), + POPUP_FORM("sdc-edit-property-container"); + private String value; + + public String getValue() { + return value; + } + + private PropertiesPageEnum(String value) { + this.value = value; + } + } + + public enum PropertiesPopupEnum { + + PROPERTY_NAME("propertyName"), + PROPERTY_VALUE("defaultvalue"), + PROPERTY_BOOLEAN_VALUE("booleantype"), + PROPERTY_DESCRIPTION("description"), + PROPERTY_TYPE("propertyType"), + ENTRY_SCHEMA("schema-type"), + CANCEL("Cancel"), + SAVE("Save"), + POPUP_FORM("sdc-edit-property-container"), + ADD("Add"), + DONE("Done"), + PROPERTY_RADIO_BUTTON_CONTAINER("propertyRadioButton_"), + RADIO_BUTTON_CLASS("tlv-radio-label"); + private String value; + + public String getValue() { + return value; + } + + private PropertiesPopupEnum(String value) { + this.value = value; + } + } + + public enum AdminPageTabs { + USER_MANAGEMENT("usermanagmenttab"), + CATEGORY_MANAGEMENT("categorymanagmenttab"); + + private String value; + + public String getValue() { + return value; + } + + private AdminPageTabs(String value) { + this.value = value; + } + } + + public enum UserManagementEnum { + + SEARCH_BOX("searchbox"), + NEW_USER_FIELD("newuserId"), + ROLE_SELECT("selectrole"), + CREATE_BUTTON("creategreen"), + CLASS__USER_MANAGEMENT_TABLE("sdc-user-management-table"), + ROW_TABLE("row_"), + FIRST_NAME("firstName_"), + LAST_NAME("lastName__"), + USER_ID("userId_"), + EMAIL("email_"), + ROLE("role_"), + LAST_ACTIVE("lastActive_"), + UPDATE_ROLE("selectRole_"), + UPDATE_USER_BUTTON("updateUser_"), + SAVE_USER("save_"), + DELETE_USER("delete_"), + ; + + + private String value; + + public String getValue() { + return value; + } + + private UserManagementEnum(String value) { + this.value = value; + } + } + + public enum CategoryManagement { + + SERVICE_CATEGORY_HEADER("servicecategoryheader"), + RESOURCE_CATEGORY_HEADER("resourcecategoryheader"), + SERVICE_CATEGORY_LIST("servicecategory"), + RESOURCE_CATEGORY_LIST("resourcecategory"), + NEW_CATEGORY_BUTTON("newcategory"), + NEW_SUB_CATEGORY_BUTTON("newsubcategory"), + NEW_CATEGORY_NAME("i-sdc-form-input"); + + private String value; + + public String getValue() { + return value; + } + + private CategoryManagement(String value) { + this.value = value; + } + } + + + + public enum MainMenuButtons { + HOME_BUTTON("main-menu-button-home"), + CATALOG_BUTTON("main-menu-button-catalog"), + ONBOARD_BUTTON("main-menu-button-onboard"), + SEARCH_BOX("main-menu-input-search"), + REPOSITORY_ICON("repository-icon"); + private String value; + + public String getValue() { + return value; + } + + private MainMenuButtons(String value) { + this.value = value; + } + } + + public enum MainMenuButtonsFromInsideFrame { + HOME_BUTTON("breadcrumbs-button-0"); + private String value; + + public String getValue() { + return value; + } + + private MainMenuButtonsFromInsideFrame(String value) { + this.value = value; + } + } + + public enum MenuOptionsEnum { + EDIT("Edit"), + CHECK_IN("Check in"), + CHECK_OUT("Check out"), + VIEW("View"), + SUBMIT_FOR_TEST("Submit For Test"), + ACCEPT("Accept"), + REJECT("Reject"), + START_TEST("Start test"), + DISTREBUTE("Distribute"); + + private String value; + + public String getValue() { + return value; + } + + private MenuOptionsEnum(String value) { + this.value = value; + } + } + + public enum StepsEnum { + GENERAL("Generalstep"), + 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"), + MONITOR("Monitor step"), + MANAGEMENT_WORKFLOW("Management Workflowstep"), + INPUTS("Inputsstep"), + HIERARCHY("Hierarchystep"); + + private String value; + + public String getValue() { + return value; + } + + private StepsEnum(String value) { + this.value = value; + } + } + + public enum ArtifactPopup { + + BROWSE("browseButton"), + ARTIFACT_DESCRIPTION("description"), + ARTIFACT_LABEL("artifactLabel"), + ARTIFACT_TYPE("artifacttype"), + OK("OK"), + SAVE("Save"), + DONE_BUTTON("Done"), + CANCEL_BUTTON("Cancel"), + URL("input[class^='i-sdc-form-input']"), + MODAL_WINDOW("sdc-add-artifact"); + + private String value; + + public String getValue() { + return value; + } + + private ArtifactPopup(String value) { + this.value = value; + } + } + + public enum ServiceMetadataEnum { + SERVICE_NAME("name"), DESCRIPTION("description"), CATEGORY("selectGeneralCategory"), PROJECT_CODE("projectCode"), TAGS("i-sdc-tag-input"), CONTACT_ID("contactId"), ICON(" iconBox"); + + private String value; + + public String getValue() { + return value; + } + + private ServiceMetadataEnum(String value) { + this.value = value; + } + } + + public enum ProductMetadataEnum { + PRODUCT_NAME("name"), + FULL_NAME("fullName"), + DESCRIPTION("description"), + PROJECT_CODE("projectCode"), + TAGS("i-sdc-tag-input"), + ATT_CONTACT("attContact"), + ICON(" iconBox"); + + private String value; + + public String getValue() { + return value; + } + + private ProductMetadataEnum(String value) { + this.value = value; + } + } + + public enum DashboardCardEnum { + ASSET_TYPE("asset-type"), LIFECYCLE_STATE("span[class^='w-sdc-dashboard-card-info-lifecycleState']"), + INFO_NAME("div.sdc-tile-content-info-item-name"), + VERSION("div[class^='w-sdc-dashboard-card-info-user']"), + DASHBOARD_CARD("div[class^='w-sdc-dashboard-card ']"), + ASSET_TYPE_CSS("span[data-tests-id='asset-type']"); + + private String value; + + public String getValue() { + return value; + } + + private DashboardCardEnum(String value) { + this.value = value; + } + } + + public enum CatalogPageLeftPanelCategoryCheckbox { + GENERIC_CHECKBOX("span[data-tests-id='checkbox-resourcenewcategory.generic']"), + NETWORK_L2_3("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3']"), + NETWORK_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.networkl4+']"), + NETWORK_CONNECTIVITY("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity']"), + APPLICATION_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+']"), + DCAE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent']"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogPageLeftPanelCategoryCheckbox(String value) { + this.value = value; + } + } + + public enum CatalogPageLeftPanelFilterTitle { + TYPE("span[data-tests-id='typeFilterTitle']"), + CATEGORIES("span[data-tests-id='categoriesFilterTitle']"), + STATUS("span[data-tests-id='statusFilterTitle']"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogPageLeftPanelFilterTitle(String value) { + this.value = value; + } + } + + public enum CatalogPageLeftPanelSubCategoryCheckbox { + COMMON_NETWORK_RESOURCES("span[data-tests-id='checkbox-resourcenewcategory.networkl4+.commonnetworkresources']"), + ROUTER("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.router']"), + WAN_CONNECTORS("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.wanconnectors']"), + LAN_CONNECTORS("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.lanconnectors']"), + INFRASTRUCTERE_NETWORKl2_3("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.infrastructure']"), + GATEWAY("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.gateway']"), + NETWORK_ELEMENTS("span[data-tests-id='checkbox-resourcenewcategory.generic.networkelements']"), + ABSTRACT("span[data-tests-id='checkbox-resourcenewcategory.generic.abstract']"), + RULES("span[data-tests-id='checkbox-resourcenewcategory.generic.rules']"), + DATABASE("span[data-tests-id='checkbox-resourcenewcategory.generic.database']"), + INFRASTRUCTERE_GENERIC("span[data-tests-id='checkbox-resourcenewcategory.generic.infrastructure']"), + VIRTUAL_LINKS("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity.virtuallinks']"), + CONNECTION_POINTS("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity.connectionpoints']"), + APPLICATION_SERVER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.applicationserver']"), + CALL_CONTROL("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.callcontrol']"), + MEDIASERVERS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.mediaservers']"), + WEBSERVER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.webserver']"), + LOAD_BALANCER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.loadbalancer']"), + BORDER_ELEMENT("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.borderelement']"), + DATABASE_APPLIVATION_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.database']"), + FIREWALL("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.firewall']"), + DATABASE_DCAE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.database']"), + POLICY("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.policy']"), + MICROSERVICE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.microservice']"), + SOURCE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.source']"), + COLLECTOR("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.collector']"), + UTILITY("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.utility']"), + ANALYTICS("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.analytics']"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogPageLeftPanelSubCategoryCheckbox(String value) { + this.value = value; + } + } + + public enum CompositionScreenEnum { + + CHANGE_VERSION("changeVersion", Arrays.asList()), + DEPLOYMENT_ARTIFACT_TAB("deployment-artifact-tab", Arrays.asList("Deployment Artifacts")), + ADD_ARTIFACT("add_Artifact_Button", Arrays.asList()), + SEARCH_ASSET("searchAsset", Arrays.asList()), + PROPERTIES_AND_ATTRIBUTES_TAB("properties-and-attributes-tab",Arrays.asList()), + MENU_INPUTS("sub-menu-button-inputs",Arrays.asList()), + MENU_TRIANGLE_DROPDOWN("triangle-dropdown", Arrays.asList()), + ARTIFACTS_LIST("artifactName", Arrays.asList()), + INFORMATION_ARTIFACTS("button[tooltip-content='Information Artifacts']", Arrays.asList("Informational Artifacts")), + API("button[tooltip-content='API']", Arrays.asList("API Artifacts")), + INFORMATION("button[tooltip-content='Information']", Arrays.asList("General Info", "Additional Information", "Tags")), + COMPOSITION("button[tooltip-content='Composition']", Arrays.asList("Composition")), + INPUTS("button[tooltip-content='Inputs']", Arrays.asList("")), + REQUIREMENTS_AND_CAPABILITIES("button[tooltip-content='Requirements and Capabilities']", Arrays.asList()), + INFORMATION_TAB("information-tab", Arrays.asList()), + CUSTOMIZATION_UUID("rightTab_customizationModuleUUID", Arrays.asList()); + + private String value; + private List title; + + public String getValue() { + return value; + } + + public List getTitle() { + return title; + } + + private CompositionScreenEnum(String value, List title) { + this.value = value; + this.title = title; + } + } + + public enum ToscaArtifactsScreenEnum { + + TOSCA_MODEL("download-Tosca Model"), + TOSCA_TEMPLATE("download-Tosca Template"), + ARTIFACT_VERSION("version-"), + ARTIFACT_NAME("name-"), + ARTIFACT_TYPE("type-"), + ARTIFACT_DETAILS("details-"), + DOWNLOAD_ARTIFACT("download-"), + DOWNLOAD_CSAR("download-Tosca Model"); + + private String value; + + public String getValue() { + return value; + } + + private ToscaArtifactsScreenEnum(String value) { + this.value = value; + } + } + + public enum InformationalArtifactsService { + AFFINITY_RULES("artifact_Display_Name-Affinity Rules"), + CONTROL_LOOP_FUNCTIONS("artifact_Display_Name-Control Loop Functions"), + DEPLOYMENT_VOTING_RECORD("artifact_Display_Name-Deployment Voting Record"), + DIMENSIONING_INFO("artifact_Display_Name-Dimensioning Info"), + DISTRIBUTION_INSTRUCTION("artifact_Display_Name-Distribution Instructions"), + ENGINEERING_RULES("artifact_Display_Name-Engineering Rules (ERD)"), + OPERATIONAL_POLICES("artifact_Display_Name-Operational Policies"), + SERVICE_ARTIFACT_PLAN("artifact_Display_Name-Service Artifact Plan"), + SERVICE_QUESTIONNAIRE("artifact_Display_Name-Service Questionnaire"), + SERVICE_SECURITY_TEMPLATE("artifact_Display_Name-Service Security Template"), + SERVICE_SPECIFIC_POLICIES("artifact_Display_Name-Service-specific Policies"), + SUMMARY_OF_IMPACTS_TO_ECOMP("artifact_Display_Name-Summary of impacts to ECOMP elements,OSSs, BSSs"), + TD_CERTIFICATION_TEST_RESULTS("artifact_Display_Name-TD Certification Test Results"); + + private String value; + + public String getValue() { + return value; + } + + private InformationalArtifactsService(String value) { + this.value = value; + } + } + + public enum APIArtifactsService { + + CONFIGURATION("artifact_Display_Name-Configuration"), + INSTANTIATION("artifact_Display_Name-Instantiation"), + LOGGING("artifact_Display_Name-Logging"), + MONITORING("artifact_Display_Name-Monitoring"), + REPORTING("artifact_Display_Name-Reporting"), + TESTING("artifact_Display_Name-Testing"); + + private String value; + + public String getValue() { + return value; + } + + private APIArtifactsService(String value) { + this.value = value; + } + } + + public enum DeploymentArtifactCompositionRightMenu { + ARTIFACT_NAME("artifactName-"), + ARTIFACT_DISPLAY_NAME("artifact_Display_Name-"), + DOWNLOAD("download_"), + DELETE("delete_"), + ADD_ARTIFACT_BUTTON("add_Artifact_Button"), + EDIT_PARAMETERS_OF_ARTIFACT("edit-parameters-of-"), + ARTIFACT_ITEM("artifact-item-"), + ARTIFACT_ENV("heat_env_"); + + private String value; + + public String getValue() { + return value; + } + + private DeploymentArtifactCompositionRightMenu(String value) { + this.value = value; + } + + } + + public enum InputsScreenService { + ADD_SELECTED_INPUTS_BTN("add-inputs-to-service-button"), + VF_INSTANCE_ROWS("expand-collapse[expanded-selector^='.vf-instance-list.']"), + VF_INSTANCE_ROW_NAME("span[class^='title-text']"), + VF_INSTANCE_INPUTS("div[class^='vf-instance-list ']"), + VF_INSTANCE_INPUT("div[class^='input-row ng-scope']"), + VF_INSTNCE_PROPERTY_NAME("div[class^='title-text']"), + INPUT_CHECKBOX("span[class^='tlv-checkbox-label']"), + SERVICE_INPUT_ROW("div[class^='service-input-row input-row']"), + DELETE_INPUT_BTN("span[class$='remove-input-icon']"), + RESOURCE_INSTANCE_PROPERTY_NAME("propertyName_"), + RESOURCE_INSTANCE_PROPERTY_TYPE("propertyType_"), + RESOURCE_INSTANCE_PROPERTY_CHECKBOX("propertyCheckbox_"), + SERVICE_INPUTS_DELETE_BUTTON("deleteInput_") + ; + + private String value; + + public String getValue() { + return value; + } + + private InputsScreenService(String value) { + this.value = value; + } + + } + + public enum DeploymentScreen { + MODULES("span[class^='expand-collapse-title-text']"), + MEMBERS("div[class^='expand-collapse-sub-title']"), + PROPERTIES("list-of-Properties"), + ARTIFACTS("list-of-Artifacts"), + BUTTON_PROPERTIES("div[data-tests-id='list-of-Properties'] span[class^='hand']"), + BUTTON_ARTIFACTS("div[data-tests-id='list-of-Artifacts'] span[class^='hand']"), + PROPERTY_NAMES("div[data-tests-id='selected-module-property-name'] span"), + PROPERTY_TYPES("selected-module-property-type"), + PROPERTY_SCHEMA_TYPE("selected-module-property-schema-type"), + ARTIFACT_NAME("selected-module-artifact-name"), + ARTIFACT_UUID("selected-module-artifact-uuid"), + ARTIFACT_VERSION("selected-module-artifact-version"), + PENCIL_ICON("edit-name-popover-icon"), + MODULE_NAME("selected-module-name"), + MODULE_ID("selected-module-group-uuid"), + RESOURCE_NAME_ON_POPOVER("popover-vfinstance-name"), + MODULE_NAME_ON_POPOVER("popover-module-name"), + NAME_INPUT("popover-heat-name"), + SAVE("popover-save-button"), + CANCEL("popover-close-button"), + X_BUTTON("popover-x-button"); + + private String value; + + public String getValue() { + return value; + } + + private DeploymentScreen(String value) { + this.value = value; + } + } + + public enum ImportVfRepository { + SEARCH("onboarding-search"), + IMPORT_VSP("import-csar"), + DOWNLOAD_CSAR("download-csar"), + UPDATE_VSP("update-csar"); + + private String value; + + public String getValue() { + return value; + } + + private ImportVfRepository(String value) { + this.value = value; + } + } + + public enum EnvParameterView { + SEARCH_ENV_PARAM_NAME("search-env-param-name"), + ENV_CURRENT_VALUE("value-field-of-"),//value-field-of-oam_volume_name_0 - parameter name + ENV_DEFAULT_VALUE("default-value-of-");// default-value-of-vnf_name + + private String value; + + public String getValue() { + return value; + } + + private EnvParameterView(String value) { + this.value = value; + } + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ErrorMessageProperties.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ErrorMessageProperties.java new file mode 100644 index 0000000000..a7d2551683 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ErrorMessageProperties.java @@ -0,0 +1,53 @@ +/*- + * ============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.ci.tests.datatypes; + +public class ErrorMessageProperties { + + private String messageId ; + private String code; + + public ErrorMessageProperties() { + + } + + public ErrorMessageProperties(String messageId, String code) { + this.messageId = messageId; + this.code = code; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java new file mode 100644 index 0000000000..e708fb8ee4 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GeneralCanvasItemsEnum.java @@ -0,0 +1,38 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum GeneralCanvasItemsEnum { + CANVAS("canvas"), + CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), + DELETE_INSTANCE_BUTTON("e-sdc-small-icon-delete"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralCanvasItemsEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java new file mode 100644 index 0000000000..1df61b734c --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java @@ -0,0 +1,62 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.io.File; + +public class HeatAndHeatEnvNamesPair { + + private File heatFileName; + private File heatEnvFileName; + + public HeatAndHeatEnvNamesPair() { + super(); + } + + public HeatAndHeatEnvNamesPair(File heatFileName, File heatEnvFileName) { + super(); + this.heatFileName = heatFileName; + this.heatEnvFileName = heatEnvFileName; + } + + public File getHeatFileName() { + return heatFileName; + } + + public void setHeatFileName(File heatFileName) { + this.heatFileName = heatFileName; + } + + public File getHeatEnvFileName() { + return heatEnvFileName; + } + + public void setHeatEnvFileName(File heatEnvFileName) { + this.heatEnvFileName = heatEnvFileName; + } + + @Override + public String toString() { + return "HeatHeatEnvNamesPair [heatFileName=" + heatFileName + ", heatEnvFileName=" + heatEnvFileName + "]"; + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatWithParametersDefinition.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatWithParametersDefinition.java new file mode 100644 index 0000000000..5ff173ee87 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/HeatWithParametersDefinition.java @@ -0,0 +1,102 @@ +/*- + * ============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.ci.tests.datatypes; + +import java.util.List; + +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; + +public class HeatWithParametersDefinition { + + private String heatLabel; + private String heatEnvLabel; + private String heatArtifactType; + private String heatEnvArtifactType; + private String heatArtifactDisplayName; + private List heatParameterDefinition; + + public HeatWithParametersDefinition(String heatLabel, String heatEnvLabel, String heatArtifactType, String heatEnvArtifactType, String heatArtifactDisplayName, List heatParameterDefinition) { + super(); + this.heatLabel = heatLabel; + this.heatEnvLabel = heatEnvLabel; + this.heatArtifactType = heatArtifactType; + this.heatEnvArtifactType = heatEnvArtifactType; + this.heatArtifactDisplayName = heatArtifactDisplayName; + this.heatParameterDefinition = heatParameterDefinition; + } + + public String getHeatArtifactDisplayName() { + return heatArtifactDisplayName; + } + + public void setHeatArtifactDisplayName(String heatArtifactDisplayName) { + this.heatArtifactDisplayName = heatArtifactDisplayName; + } + + public String getHeatLabel() { + return heatLabel; + } + + public void setHeatLabel(String heatLabel) { + this.heatLabel = heatLabel; + } + + public String getHeatEnvLabel() { + return heatEnvLabel; + } + + public void setHeatEnvLabel(String heatEnvLabel) { + this.heatEnvLabel = heatEnvLabel; + } + + public String getHeatArtifactType() { + return heatArtifactType; + } + + public void setHeatArtifactType(String heatArtifactType) { + this.heatArtifactType = heatArtifactType; + } + + public String getHeatEnvArtifactType() { + return heatEnvArtifactType; + } + + public void setHeatEnvArtifactType(String heatEnvArtifactType) { + this.heatEnvArtifactType = heatEnvArtifactType; + } + + public List getHeatParameterDefinition() { + return heatParameterDefinition; + } + + public void setHeatParameterDefinition(List heatParameterDefinition) { + this.heatParameterDefinition = heatParameterDefinition; + } + + @Override + public String toString() { + return "HeatWithParametersDefinition [heatLabel=" + heatLabel + ", heatEnvLabel=" + heatEnvLabel + ", heatArtifactType=" + heatArtifactType + ", heatEnvArtifactType=" + heatEnvArtifactType + ", heatArtifactDisplayName=" + + heatArtifactDisplayName + ", heatParameterDefinition=" + heatParameterDefinition + "]"; + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java new file mode 100644 index 0000000000..773cb57b2e --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/LifeCycleStateEnum.java @@ -0,0 +1,47 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum LifeCycleStateEnum { + + CHECKOUT("IN DESIGN CHECK OUT"), + CHECKIN("IN DESIGN CHECK IN"), + READY_FOR_TESTING("READY FOR TESTING"), + IN_TESTING("IN TESTING"), + WAITING_FOR_DISTRIBUTION("WAITING FOR DISTRIBUTION"), + DISTRIBUTION_REJECTED("DISTRIBUTION REJECTED"), + DISTRIBUTION_APPROVED("DISTRIBUTION APPROVED"), + CERTIFIED("CERTIFIED"), + DISTRIBUTED("DISTRIBUTED"), + IN_DESIGN("IN DESIGN"); + + private String value; + private String value2; + + public String getValue() { + return value; + } + + private LifeCycleStateEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java new file mode 100644 index 0000000000..63171a6c78 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/MenuOptionsEnum.java @@ -0,0 +1,37 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum MenuOptionsEnum { + + EDIT("Edit"), CHECK_IN("Check in"), CHECK_OUT("Check out"), VIEW("View"), SUBMIT_FOR_TEST("Submit For Test"), ACCEPT("Accept"), REJECT("Reject"), START_TEST("Start test"), DISTREBUTE("Distribute"); + + private String value; + + public String getValue() { + return value; + } + + private MenuOptionsEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java new file mode 100644 index 0000000000..785a355e13 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyInfo.java @@ -0,0 +1,76 @@ +/*- + * ============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.ci.tests.datatypes; + +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; + +public class PropertyInfo { + + public PropertyInfo() { + super(); + } + + public PropertyInfo(PropertyTypeEnum prop) { + super(); + this.name = prop.getName(); + this.value = prop.getValue(); + this.type = prop.getType(); + this.description = prop.getDescription(); + } + + private String name; + private String value; + private String type; + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java new file mode 100644 index 0000000000..2c49c8718b --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceCategoriesNameEnum.java @@ -0,0 +1,45 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum ResourceCategoriesNameEnum { + + GENERIC("checkbox-resourcenewcategory.generic"), NETWORK_CONNECTIVITY("checkbox-resourcenewcategory.networkconnectivity"), NETWORK_ELEMENTS("checkbox-resourcenewcategory.generic.networkelements"), + ABSTRACT("checkbox-resourcenewcategory.generic.abstract"), DATABASE_GENERIC("checkbox-resourcenewcategory.generic.database"), INFRASTRUCTURE("checkbox-resourcenewcategory.generic.infrastructure"), + VIRTUAL_LINKS("checkbox-resourcenewcategory.networkconnectivity.virtuallinks"), CONNECTION_POINTS("checkbox-resourcenewcategory.networkconnectivity.connectionpoints"), NETWORKL4("checkbox-resourcenewcategory.networkl4+"), + COMMON_NETWORK_RESOURCES("checkbox-resourcenewcategory.networkl4+.commonnetworkresources"), APPLICATIONL4("checkbox-resourcenewcategory.applicationl4+"), WEB_SERVER("checkbox-resourcenewcategory.applicationl4+.webserver"), + APPLICATION_SERVER("checkbox-resourcenewcategory.applicationl4+.applicationserver"), CALL_CONTROL("checkbox-resourcenewcategory.applicationl4+.callcontrol"), BORDER_ELEMENT("checkbox-resourcenewcategory.applicationl4+.borderelement"), + MEDIA_SERVERS("checkbox-resourcenewcategory.applicationl4+.mediaservers"), DATABASE("checkbox-resourcenewcategory.applicationl4+.database"), FIREWALL("checkbox-resourcenewcategory.applicationl4+.firewall"), + LOAD_BALANCER("checkbox-resourcenewcategory.applicationl4+.loadbalancer"), NETWORK_L23("checkbox-resourcenewcategory.networkl2-3"), Router("checkbox-resourcenewcategory.networkl2-3.router"), + WAN_Connectors("checkbox-resourcenewcategory.networkl2-3.wanconnectors"), LAN_CONNECTORS("checkbox-resourcenewcategory.networkl2-3.lanconnectors"), GATEWAY("checkbox-resourcenewcategory.networkl2-3.gateway"), + INFRASTRUCTUREL23("checkbox-resourcenewcategory.networkl2-3.infrastructure"); + + private String value; + + public String getValue() { + return value; + } + + private ResourceCategoriesNameEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java new file mode 100644 index 0000000000..b90e311f72 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceCategoriesNameEnum.java @@ -0,0 +1,36 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum ServiceCategoriesNameEnum { + + NETWORK_L13("checkbox-servicenewcategory.networkl1-3"), VOIPCALL_CONTROL("checkbox-servicenewcategory.voipcallcontrol"), NETWORKL4("checkbox-servicenewcategory.networkl4+"), MOBILITY("checkbox-servicenewcategory.mobility"); + + private String value; + + public String getValue() { + return value; + } + + private ServiceCategoriesNameEnum(String value) { + this.value = value; + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java new file mode 100644 index 0000000000..9e81505111 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java @@ -0,0 +1,38 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum TopMenuButtonsEnum { + + HOME("main-menu-button-home"), CATALOG("main-menu-button-catalog"), ON_BOARDING("main-menu-button-onboard"); + + private String value; + private String value2; + + public String getButton() { + return value; + } + + private TopMenuButtonsEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java new file mode 100644 index 0000000000..d27eb0c150 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypesEnum.java @@ -0,0 +1,36 @@ +/*- + * ============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.ci.tests.datatypes; + +public enum TypesEnum { + + RESOURCE("checkbox-resource"), VF("checkbox-vf"), VFC("checkbox-vfc"), CP("checkbox-cp"), VL("checkbox-vl"), SERVICE("checkbox-service"), PRODUCT("checkbox-product"); + private String value; + + public String getValue() { + return value; + } + + private TypesEnum(String value) { + this.value = value; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java new file mode 100644 index 0000000000..2de872504f --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserCredentials.java @@ -0,0 +1,58 @@ +/*- + * ============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.ci.tests.datatypes; + +import org.openecomp.sdc.be.model.User; + +public class UserCredentials extends User { + + // private String userName; + private String password; + + public UserCredentials(String userId, String password, String firstname, String lastname, String role) { + super(); + setUserId(userId); + // this.userName = userName; + this.password = password; + setFirstName(firstname); + setLastName(lastname); + setRole(role); + } + + public UserCredentials() { + super(); + } + + // public String getUserName() { + // return userName; + // } + // public void setUserName(String userName) { + // this.userName = userName; + // } + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserManagementTab.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserManagementTab.java new file mode 100644 index 0000000000..0101b430d8 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserManagementTab.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.ci.tests.datatypes; + +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class UserManagementTab { + + public void searchUser(String searchCriterion){ + ExtentTestActions.log(Status.INFO, "Searching a user by the value : " + searchCriterion); + WebElement searchBoxWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.SEARCH_BOX.getValue()); + searchBoxWebElement.clear(); + searchBoxWebElement.sendKeys(searchCriterion); + GeneralUIUtils.ultimateWait(); + } + + public void setNewUserBox(String user){ + ExtentTestActions.log(Status.INFO, "Inserting userid " + user); + WebElement createNewUserWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.NEW_USER_FIELD.getValue()); + createNewUserWebElement.clear(); + createNewUserWebElement.sendKeys(user); + GeneralUIUtils.ultimateWait(); + } + + public void selectUserRole(UserRoleEnum userRole){ + String role = userRole.name().toLowerCase(); + ExtentTestActions.log(Status.INFO, "Selecting role " + userRole.name()); + GeneralUIUtils.getSelectList(role, DataTestIdEnum.UserManagementEnum.ROLE_SELECT.getValue()); + } + + public void updateUserRole(UserRoleEnum userRole, int rowIndx){ + String role = userRole.name().toLowerCase(); + ExtentTestActions.log(Status.INFO, "Updating the user role to " + userRole.name()); + GeneralUIUtils.getSelectList(role, DataTestIdEnum.UserManagementEnum.UPDATE_ROLE.getValue() + rowIndx); + } + + public void clickCreateButton(){ + ExtentTestActions.log(Status.INFO, "Clicking on 'Create' button."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.CREATE_BUTTON.getValue()); + } + + public WebElement getRow(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.ROW_TABLE.getValue() + index); + } + + public WebElement getFirstName(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.FIRST_NAME.getValue() + index); + } + + public WebElement getLastName(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.LAST_NAME.getValue() + index); + } + + public WebElement getUserId(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.USER_ID.getValue() + index); + } + + public WebElement getEmail(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.EMAIL.getValue() + index); + } + + public WebElement getRole(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.ROLE.getValue() + index); + } + + public WebElement getLastActive(int index){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.LAST_ACTIVE.getValue() + index); + } + + public void updateUser(int index){ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.UPDATE_USER_BUTTON.getValue() + index); + } + + public void deleteUser(int index){ + ExtentTestActions.log(Status.INFO, "Deleting the user in row " + (index + 1)); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.DELETE_USER.getValue() + index); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + } + + public void saveAfterUpdateUser(int index){ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.SAVE_USER.getValue() + index); + } + + public List getAllRowsDisplayed(){ + return GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.UserManagementEnum.ROW_TABLE.getValue()); + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VFCArtifact.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VFCArtifact.java new file mode 100644 index 0000000000..540a36ad18 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VFCArtifact.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.datatypes; + +public class VFCArtifact { + + String artifactUUID; + String artifactVersion; + String artifactname; + String artifacttype; + + + public VFCArtifact(String artifactName, String artifactType, String uuid, String version){ + artifactname = artifactName; + artifactUUID = uuid; + artifactVersion = version; + artifacttype = artifactType; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactname() { + return artifactname; + } + + public void setArtifactname(String artifactname) { + this.artifactname = artifactname; + } + + public String getArtifacttype() { + return artifacttype; + } + + public void setArtifacttype(String artifacttype) { + this.artifacttype = artifacttype; + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal new file mode 100644 index 0000000000..ea93ddfe85 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/environmentLocal @@ -0,0 +1,10 @@ +//URL designer +urlDesigner=http://172.20.43.136:8080/sdc1/proxy-designer1#/dashboard +//URL tester +urlTester=http://172.20.43.136:8080/sdc1/proxy-tester1 +//URL Vagrant +urlDesignerVagrant=http://localhost:8181/sdc1/proxy-designer1#/dashboard +//UrlStaging +UrlStaging=https://www.e-access.att.com/sdcpstage/sdc1/portal#/dashboard +//UrlAdmin +UrlAdmin=http://172.20.43.136:8080/sdc1/proxy-admin1#/adminDashboard \ No newline at end of file diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/AdminUserManagment.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/AdminUserManagment.java new file mode 100644 index 0000000000..710188af43 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/AdminUserManagment.java @@ -0,0 +1,289 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import java.io.IOException; +import java.util.List; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +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.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.AdminGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.AdminWorkspaceUIUtilies; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +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.UserRestUtils; +import org.openecomp.sdc.ci.tests.verificator.ErrorMessageUIVerificator; +import org.openecomp.sdc.ci.tests.verificator.UserManagementVerificator; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class AdminUserManagment extends SetupCDTest { + + @DataProvider(name = "searchValues") + private final Object[][] searchString(){ + User newUser = createNewUserUsingAPI(); + return new Object[][]{{newUser.getUserId(), newUser}, {newUser.getFirstName(), newUser}, {newUser.getLastName(), newUser}, {newUser.getEmail(), newUser}}; + } + + //TC915100 + @Test + public void creatNewUserTest() throws Exception { + + String userId = generateValidUserId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + UserManagementVerificator.validateUserCreated(userId, userRole); + } + + //TC922253 + @Test + public void creatNewUser_MacIdTest() throws Exception { + + String macId = generateValidMacId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(macId, userRole); + UserManagementVerificator.validateUserCreated(macId, userRole); + } + + //TC922253 + @Test + public void createExistingUserTest(){ + String userId = generateValidUserId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + ExtentTestActions.log(Status.INFO, "Trying to create the same user once again."); + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.USER_ALREADY_EXIST); + } + + //TC922253 + @Test + public void createInvalidMacIdTest(){ + String macId = generateValidMacId(); + StringBuilder invalidMacId = new StringBuilder(macId); + invalidMacId.setCharAt(0, 'a'); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + ExtentTestActions.log(Status.INFO, "Trying to create an invalid macId."); + AdminWorkspaceUIUtilies.createNewUser(invalidMacId.toString(), userRole); + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.INVALID_USER_ID); + } + + //TC922253 + @Test + public void specialCharInUserIdTest(){ + String expectedErrorMsg = "User id not valid."; + String userId = generateValidUserId(); + StringBuilder invalidUserId = new StringBuilder(userId); + invalidUserId.setCharAt(1, '#'); + ExtentTestActions.log(Status.INFO, String.format("Trying to create an invalid user with special character (%s)", userId)); + AdminGeneralPage.getUserManagementTab().setNewUserBox(invalidUserId.toString()); + ExtentTestActions.log(Status.INFO, "Validating an error message is displayed as a result of invalid character."); + List inputErrors = null; + int inputErrorsSize = 0; + + try{ + WebElement inputField = GeneralUIUtils.getWebElementByClassName("input-error"); + ExtentTestActions.log(Status.INFO, String.format("Validating the message is : '%s'", expectedErrorMsg)); + inputErrors = inputField.findElements(By.className("ng-scope")); + inputErrorsSize = inputErrors.size(); + for (WebElement err : inputErrors){ + String actualErrorMessage = err.getText(); + if (actualErrorMessage.equals(expectedErrorMsg)){ + inputErrorsSize--; + } + } + } + catch(Exception e){ + ExtentTestActions.log(Status.INFO, "Did not find an error input."); + Assert.fail("Did not find an error message input."); + } + + Assert.assertEquals(inputErrors.size() - 1 , inputErrorsSize, "Did not find an error : " + expectedErrorMsg); + } + + //TC915101 + @Test(dataProvider = "searchValues") + public void searchUserByCriterionsTest(String searchCriterion, User user) throws IOException{ + setLog(searchCriterion); + AdminWorkspaceUIUtilies.searchForUser(searchCriterion); + UserManagementVerificator.validateFirstRowDisplayedCorrectly(user); + } + + //TC915101 + @Test + public void searchForUserByRoleTest(){ + String userId = generateValidUserId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + AdminWorkspaceUIUtilies.searchForUser(userRole.name()); + List allRows = GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.UserManagementEnum.USER_ID.getValue()); + ExtentTestActions.log(Status.INFO, String.format("Found %s rows, looking for the user %s.", allRows.size(), userId)); + int rowsCount = allRows.size(); + for (int i = 0 ; i < allRows.size() ; i++){ + String userIdFromTable = GeneralUIUtils.getTextContentAttributeValue(allRows.get(i)); + if (userIdFromTable.equals(userId)){ + rowsCount--; + break; + } + } + Assert.assertEquals(allRows.size() - 1 , rowsCount , "Did not find a row with the userId " + userId); + } + + //TC915102 + @Test + public void modifyUserRoleTest(){ + User user = new User(); + user.setUserId(generateValidUserId()); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(user.getUserId(), userRole); + UserRoleEnum updatedUserRole = UserRoleEnum.TESTER; + AdminWorkspaceUIUtilies.updateUserRole(0, updatedUserRole); + UserManagementVerificator.validateUserRoleUpdated(0, updatedUserRole); + UserManagementVerificator.validateUserRoleUpdatedViaRest(user, getUser(), updatedUserRole); + } + + //TC915103 + @Test + public void deleteUserTest(){ + User user = new User(); + user.setUserId(generateValidUserId()); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(user.getUserId(), userRole); + AdminWorkspaceUIUtilies.deleteFirstRow(); + UserManagementVerificator.validateUserIdNotFound(user.getUserId()); + UserManagementVerificator.validateUserNotFoundViaRest(user, getUser()); + } + + //TC951428 + @Test + public void modifyUserRoleWithTaskInHand_Checkout() throws Exception{ + User newUser = new User(); + newUser.setUserId(generateValidUserId()); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(newUser.getUserId(), userRole); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, newUser); + ExtentTestActions.log(Status.INFO, "Creating a new VF named " + resourceMetaData.getName() + " with the user " + newUser.getUserId()); + RestResponse createResourceResp = ResourceRestUtils.createResource(resourceMetaData, newUser); + Assert.assertEquals(createResourceResp.getErrorCode().intValue(), 201, "Did not succeed to create a VF"); + + UserRoleEnum updatedUserRole = UserRoleEnum.TESTER; + AdminWorkspaceUIUtilies.updateUserRole(0, updatedUserRole); + + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS); + } + + @Test + public void modifyUserRoleWithTaskInHand_InTesting() throws Exception{ + User newTesterUser = new User(); + newTesterUser.setUserId(generateValidUserId()); + UserRoleEnum userTesterRole = UserRoleEnum.TESTER; + userTesterRole.setUserId(newTesterUser.getUserId()); + AdminWorkspaceUIUtilies.createNewUser(newTesterUser.getUserId(), userTesterRole); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ExtentTestActions.log(Status.INFO, "Creating a new VF named " + resourceMetaData.getName()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(resourceMetaData.getName()); + Resource resourceObjectByNameAndVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + ExtentTestActions.log(Status.INFO, "Getting the VF to 'In Testing' state."); + AtomicOperationUtils.changeComponentState(resourceObjectByNameAndVersion, userTesterRole, LifeCycleStatesEnum.STARTCERTIFICATION, true); + ExtentTestActions.log(Status.INFO, "Succeeded - The VF is in testing state."); + + reloginWithNewRole(UserRoleEnum.ADMIN); + UserRoleEnum updatedUserRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.searchForUser(newTesterUser.getUserId()); + AdminWorkspaceUIUtilies.updateUserRole(0, updatedUserRole); + + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS); + } + + + private static String generateValidUserId() { + String charsPattern = "abcdefghijklmnopqrstuvwxyz"; + String digitPatter = "0123456789"; + String chars = ResourceUIUtils.buildStringFromPattern(charsPattern, 2); + String digits = ResourceUIUtils.buildStringFromPattern(digitPatter, 4); + return chars + digits; + } + + private String generateValidMacId() { + String digitPatter = "0123456789"; + String digits = ResourceUIUtils.buildStringFromPattern(digitPatter, 5); + return "m" + digits; + } + + private User createNewUserUsingAPI() { + UserRoleEnum role = UserRoleEnum.DESIGNER; + String userId = generateValidUserId(); + User userByEnv = new User("Tzemer", "Gefen", userId, "userId@intl.sdc.com", role.name(), null); + User adminUser = getUserByEnv(UserRoleEnum.ADMIN); + try { + RestResponse createUserResp = UserRestUtils.createUser(userByEnv, adminUser); + Assert.assertEquals(createUserResp.getErrorCode().intValue(), 201, "Did not succeed to create a new user using API."); + } catch (IOException e) { + e.printStackTrace(); + } + return userByEnv; + } + + + private User getUserByEnv(UserRoleEnum userRole) { + try{ + if (!getConfig().getUrl().contains("localhost") && !getConfig().getUrl().contains("127.0.0.1")) { + return getUserFromFileByRole(userRole); + } + else{ + return getUser(userRole); + } + } + catch (Exception e){ + throw new RuntimeException(e); + } + } + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.ADMIN; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java new file mode 100644 index 0000000000..10389d9331 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java @@ -0,0 +1,236 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.CatalogPageLeftPanelSubCategoryCheckbox; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.TypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.CatalogUIUtilitis; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.CatalogVerificator; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +@Test(singleThreaded = true) +public class CatalogLeftPanelTest extends SetupCDTest{ + + private String filePath; + @BeforeMethod + public void beforeTest(){ + filePath = System.getProperty("filepath"); + + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + } + } + + public static String[] resourceTypes = Arrays.stream(ResourceTypeEnum.class.getEnumConstants()). + map(ResourceTypeEnum::name).toArray(String[]::new); + + public static String[] catalogTypes = {"RESOURCE", "SERVICE", "PRODUCT"}; + + public static Object[][] provideData(String[] arObj) { + Object[][] arObject = new Object[arObj.length][]; + + int index = 0; + for (Object obj : arObj) { + arObject[index++] = new Object[]{obj}; + } + return arObject; + } + + @DataProvider(name = "Resource_Type_List") + private static final Object[][] resourceTypeList(){ + // Extract names of constants from enum as array of Strings + ResourceTypeEnum[] resourceEnums = {ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC, ResourceTypeEnum.VL}; + String[] resourcesForTest = Arrays.stream(resourceEnums).map(ResourceTypeEnum::name).toArray(String[]::new); + return provideData(resourcesForTest); + } + + @DataProvider(name = "Type_List") + private static final Object[][] typeList(){ + // Extract names of constants from enum as array of Strings + Object[][] arObject = new Object[catalogTypes.length][]; + int index = 0; + for (String catalogType : catalogTypes) { + if (catalogType.equals("RESOURCE")){ + arObject[index++] = new Object[]{catalogType, resourceTypes}; + } else { + arObject[index++] = new Object[]{catalogType, new String[] {catalogType}}; + } + } + return arObject; + } + + @DataProvider(name = "Status_List") + private static final Object[][] statusList(){ + CheckBoxStatusEnum[] checkboxes = {CheckBoxStatusEnum.CERTIFIED, + CheckBoxStatusEnum.IN_DESIGN, + CheckBoxStatusEnum.DISTRIBUTED, + CheckBoxStatusEnum.IN_TESTING, + CheckBoxStatusEnum.READY_FOR_TESTING}; + Object[][] arObject = new Object[checkboxes.length][]; + int index = 0; + for (CheckBoxStatusEnum checkbox: checkboxes) { + if (checkbox.equals(CheckBoxStatusEnum.CERTIFIED)){ + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.CERTIFIED, LifeCycleStateEnum.DISTRIBUTED, LifeCycleStateEnum.WAITING_FOR_DISTRIBUTION) }; + } else if (checkbox.equals(CheckBoxStatusEnum.IN_DESIGN)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.CHECKIN, LifeCycleStateEnum.CHECKOUT)}; + } else if (checkbox.equals(CheckBoxStatusEnum.DISTRIBUTED)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.DISTRIBUTED)}; + } else if (checkbox.equals(CheckBoxStatusEnum.IN_TESTING)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.IN_TESTING)}; + } else if (checkbox.equals(CheckBoxStatusEnum.READY_FOR_TESTING)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.READY_FOR_TESTING)}; + } + } + return arObject; + } + + // filter by Type Resource in catalog + @Test(dataProvider = "Type_List") + public void filterByType(String catalogType, String[] classValues ) throws Exception { + setLog(catalogType); +// getExtendTest().setDescription(catalogType); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf(catalogType)); + + CatalogVerificator.validateType(TypesEnum.valueOf(catalogType)); + } + + @Test(dataProvider = "Resource_Type_List") + public void filterByResourceType(String resourceType) throws Exception { + setLog(resourceType); +// getExtendTest().setDescription(resourceType); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf(resourceType)); + + CatalogVerificator.validateType(TypesEnum.valueOf(resourceType)); + } + + @Test(dataProvider = "Status_List") + public void filterByStatus(CheckBoxStatusEnum statusCheckbox, List lifecycleStates) throws Exception{ + setLog(statusCheckbox.name()); +// getExtendTest().setDescription(statusCheckbox.name()); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.CATEGORIES); + CatalogUIUtilitis.catalogFilterStatusChecBox(statusCheckbox); + + CatalogVerificator.validateStatus(lifecycleStates, statusCheckbox.name()); + } + + @Test + public void filterByUpperCategory() throws Exception{ + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.TYPE); + + WebElement categorieCheckbox = CatalogUIUtilitis.clickOnUpperCategoryCheckbox(); + + CatalogVerificator.validateCategory(categorieCheckbox.getAttribute("textContent").trim()); + } + + @Test + public void filterByGenericDtabaseSubCategory() throws Exception{ + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.TYPE); + + WebElement checkboxElement = GeneralUIUtils.getElementsByCSS(CatalogPageLeftPanelSubCategoryCheckbox.DATABASE.getValue()).get(0); + String checkboxElementName = checkboxElement.getAttribute("textContent").trim(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s subcategory ...", checkboxElementName)); + GeneralUIUtils.clickOnAreaJS(checkboxElement); + CatalogVerificator.validateSubCategory("Generic", checkboxElementName); + } + + @Test(priority = 1) + public void lastUpdatedService() throws Exception{ + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + List cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Exepected : %s , Actual: %s", serviceMetadata.getName(), firstElementName), serviceMetadata.getName().equals(firstElementName)); + } + + @Test(priority = 17) + public void lastUpdatedResource() throws Exception{ + // create resource + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + List cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Exepected : %s , Actual: %s", vfMetaData.getName(), firstElementName), vfMetaData.getName().equals(firstElementName)); + } + + @Test(priority = 5) + public void fromCatalogCheckout() throws Exception{ + // create resource + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClickInCatalog(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Categories.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Categories.java new file mode 100644 index 0000000000..d2c787e4e5 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Categories.java @@ -0,0 +1,213 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import java.util.List; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.AdminGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class Categories extends SetupCDTest { + + + @Test + public void createResourceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + GeneralUIUtils.clickSomewhereOnPage(); + List resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + List collect = resourceCategoriesList.stream().map(f -> f.getText()).collect(Collectors.toList()); + collect.contains(newResourceCategory); + + + } + + @Test + public void createServiceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + GeneralUIUtils.clickSomewhereOnPage(); + List serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List collect = serviceCategoriesList.stream().map(f -> f.getText()).collect(Collectors.toList()); + collect.contains(newserviceCategory); + + } + + + @Test + public void createResourceSubCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory , newSubCategory); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickSomewhereOnPage(); + + + } + + + @Test + public void createExistingResourceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + + } + + @Test + public void createExistingServiceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + AdminGeneralPage.selectUserManagmetTab(); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + } + + @Test + public void createExsitingResourceSubCategory() throws Exception { + + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory , newSubCategory); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory , newSubCategory); + GeneralUIUtils.waitForLoader(); + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + } + + + @Test + public void createServiceWithNewCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory , newSubCategory); + GeneralUIUtils.waitForLoader(); + AdminGeneralPage.selectUserManagmetTab(); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + List categories = serviceMetadata.getCategories(); + categories.get(0).setName(newserviceCategory); + + ServiceUIUtils.createService(serviceMetadata, getUser()); + + } + + + @Test + public void createResourceWithNewCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory , newSubCategory); + GeneralUIUtils.waitForLoader(); + AdminGeneralPage.selectUserManagmetTab(); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + List categories = resourceMetaData.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + categoryDefinition.setName(newResourceCategory); + SubCategoryDefinition subCategoryDefinition = categoryDefinition.getSubcategories().get(0); + subCategoryDefinition.setName(newSubCategory); + + ResourceUIUtils.createResource(resourceMetaData, getUser()); + + + } + + + + + + + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.ADMIN; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java new file mode 100644 index 0000000000..2c2b09af22 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java @@ -0,0 +1,383 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +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.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.CustomizationUUIDVerificator; +import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class CustomizationUUID extends SetupCDTest { + + private static final String DESCRIPTION = "kuku"; + private static final String ARTIFACT_LABEL = "artifact3"; + private static final String ARTIFACT_LABEL_UPDATE = "artifactUpdate"; + private static final String GET_ARTIFACT_LIST_BY_CLASS_NAME = "i-sdc-designer-sidebar-section-content-item-artifact"; + private static final String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; + private static final String HEAT_FILE_YAML_UPDATE_NAME = "Heat-File-Update.yaml"; + private String filePath; + + @BeforeMethod + public void beforeTest(){ + filePath = System.getProperty("filepath"); + + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + } + } + + @Test + public void uniqueCustomizationUUIDforeachVFi() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactSubmitForTesting(); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + List customizationUUIDs = new ArrayList(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement2 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement3 = addElemntToCanvas(vfMetaData, canvasManager); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement2); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement3); + + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement4 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement5 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement6 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement4); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement5); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement6); + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + + } + + + @Test + public void uniqueCustomizationUUIDafterArtifactCRUDofVFi() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactSubmitForTesting(); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + List customizationUUIDs = new ArrayList<>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + //add artifact to VFI + + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType()); + + canvasManager.clickOnCanvaElement(VFiElement1); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + + //delete VFI artifacts + + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + canvasManager.clickOnCanvaElement(VFiElement1); + CompositionPage.showDeploymentArtifactTab(); + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ITEM.getValue() + ARTIFACT_LABEL); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to delete " + HEAT_FILE_YAML_NAME + " artifact" + " and check if deleted"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + ARTIFACT_LABEL); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + } + + + @Test + public void uniqueCustomizationUUIDchangeVFiVersion() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactSubmitForTesting(); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + List customizationUUIDs = new ArrayList<>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + //change VF version + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName()); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + //update VFI version + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + canvasManager.clickOnCanvaElement(VFiElement1); + CompositionPage.changeComponentVersion(canvasManager, VFiElement1, "2.0"); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + } + + + @Test + public void uniqueCustomizationUUIDaddRelation() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactSubmitForTesting(); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + List customizationUUIDs = new ArrayList<>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + //change VF version + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName()); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + //update VFI version + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(NormativeTypesEnum.PORT.getFolderName()); + CanvasElement portElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.PORT); + canvasManager.linkElements(portElement, VFiElement1); + + canvasManager.clickOnCanvaElement(VFiElement1); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + } + + + + public CanvasManager findServiceAndNavigateToCanvas(ServiceReqDetails serviceMetadata) throws Exception { + CanvasManager canvasManager; + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + canvasManager = CanvasManager.getCanvasManager(); + return canvasManager; + } + + public ResourceReqDetails createNewResourceWithArtifactSubmitForTesting() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + +// ResourceReqDetails vfcCompute = ElementFactory.getDefaultResource(NormativeTypesEnum.COMPUTE); + CompositionPage.searchForElement(NormativeTypesEnum.COMPUTE.name()); + CanvasManager canvasManagerVF = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = canvasManagerVF.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + + + ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName()); + return vfMetaData; + } + + public void addCanvasElementToList(List customizationUUIDs, CanvasManager canvasManager, CanvasElement VFiElement1) + throws Exception { + canvasManager.clickOnCanvaElement(VFiElement1); + WebElement VFi1customizationUUID = CompositionPage.getCustomizationUUID(); + customizationUUIDs.add(VFi1customizationUUID.getText()); + } + + public CanvasElement addElemntToCanvas(ResourceReqDetails vfMetaData, CanvasManager canvasManager) + throws Exception { + CompositionPage.searchForElement(vfMetaData.getName()); + CanvasElement VFiElement1 = canvasManager.createElementOnCanvas(vfMetaData.getName()); + return VFiElement1; + } + + public static void changeDeleteAndValidateVersionOnGeneralPage(String previousVersion, String currentVersion, String serviceName) throws Exception{ + GeneralPageElements.selectVersion("V" + previousVersion); + ServiceVerificator.verifyVersionUI(previousVersion); + GeneralUIUtils.clickJSOnElementByText("latest version"); + ServiceVerificator.verifyVersionUI(currentVersion); + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(serviceName); + ServiceVerificator.verifyVersionUI(previousVersion); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java new file mode 100644 index 0000000000..87bf7b0506 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java @@ -0,0 +1,286 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.DeploymentViewVerificator; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class DeploymentViewTests extends SetupCDTest { + + private String filePath; + + @BeforeMethod + public void beforeTest(){ + filePath = System.getProperty("filepath"); + + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + } + } + + @DataProvider(name = "CSAR_VF_Files", parallel = false) + public Object[][] createDataX() { + return new Object[][] { { "vSeGWdoubleMembers.csar" }, { "vSeGW.csar" }, {"vSeGWsingleModule.csar"}}; + } + + + @Test(dataProvider = "CSAR_VF_Files") + public void deploymentScreenDCAEAssetImportCSARTest(String baseFileName) throws Exception{ + // + setLog(baseFileName); +// getExtendTest().setDescription(baseFileName); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + List moduleRowsFromTable = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()); + DeploymentViewVerificator verificator = new DeploymentViewVerificator(filePath + baseFileName); + verificator.verifyDeploymentPageModules(moduleRowsFromTable); + for(WebElement moduleRow :moduleRowsFromTable){ + String moduleRowText = moduleRow.getText(); + verificator.verifyDeploymentPageSubElements(moduleRowText.split("\\.\\.")[1]); + DeploymentPage.updateModuleName(moduleRowText, "updatedName"); + String updatedModuleName = DeploymentPage.reconstructModuleName(moduleRowText.split("\\.\\."), "updatedName"); + verificator.verifyComponentNameChanged( moduleRowText, updatedModuleName); + // Close module + GeneralUIUtils.clickOnElementByText(updatedModuleName); + } + } + + @Test + public void deploymentScreenDCAEAssetUpdateWithNewGroupCSAR_TC1368223_Test() throws Exception{ + String baseFileName = "baseUpdateMinusGroupFlowVF.csar"; + String updateFileName = "baseUpdateFlowVF.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 2)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + metaDataFromUI.put("base_ldsa", new HashMap (){ {put("version", "0"); + put("moduleID", "primary");}}); + + // add new group, base_ldsa + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now", 3)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + }; + + @Test + public void deploymentScreenDCAEAssetDeleteGroupFromCSAR_TC1368281_Test() throws Exception{ + String baseFileName = "baseUpdateFlowVF.csar"; + String updateFileName = "baseUpdateMinusGroupFlowVF.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 3)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + // remove group base_ldsa + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group should be removed", 2)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + // validate that group was removed + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + + Map> metaDataFromUI2 = DeploymentPage.collectMetaDataFromUI(); + metaDataFromUI2.put("base_ldsa", new HashMap (){ {put("version", "0"); + put("moduleID", "primary");}}); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // add group base_ldsa + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group should be added", 3)); + ResourceUIUtils.updateVfWithCsar(filePath, baseFileName); + + // validate that group was added + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI2, new DeploymentViewVerificator(filePath + baseFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetUpdateWithNewGroupWithoutMembersCSAR_TC1368280_Test() throws Exception{ + String baseFileName = "baseUpdateMinusGroupFlowVF.csar"; + String updateFileName = "baseUpdateAddGroupNoMembersUpdateFlow.csar"; + String updateFileName2 = "baseUpdateFlowVF.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 2)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + // add new group without members, base_ldsa + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group without members", 3)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + // validate that group was added and no members exist + DeploymentViewVerificator.regularDepoymentScreenVerificator(null, new DeploymentViewVerificator(filePath + updateFileName)); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // add group base_ldsa with members + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group with members", 3)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName2); + + // validate that member was added to base_ldsa group + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName2)); + DeploymentViewVerificator.validateModuleNameUpadate(); + }; + + @Test + public void deploymentScreenDCAEAssetImportCSARWithArtifactSection_TC1368282_1_Test() throws Exception{ + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 4 artifacts in every group ", 3)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(null, new DeploymentViewVerificator(filePath + baseFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + }; + + @Test + public void deploymentScreenDCAEAssetImportCSARRemoveArtifact_TC1368282_2_Test() throws Exception{ + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup.csar"; + String updateFileName = "baseUpdateFlowOneArtifactToGroup.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 4 artifacts in every group ", 3)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // remove artifact from every group + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be 3 artifacts in every group")); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + }; + + @Test + public void deploymentScreenDCAEAssetImportCSARAddArtifact_TC1368282_3_Test() throws Exception{ + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup.csar"; + String updateFileName = "baseUpdateFlowOneArtifactToGroup.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 3 artifacts in every group ", 3)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, updateFileName, getUser()); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // add artifact to every group + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be 4 artifacts in every group")); + ResourceUIUtils.updateVfWithCsar(filePath, baseFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + baseFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + }; + + @Test + public void deploymentScreenDCAEAssetImportCSARMixArtifacts_TC1368282_4_Test() throws Exception{ + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup.csar"; + String updateFileName = "baseUpdateMixedArtifacts.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 4 artifacts in every group ", 3)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + //mix artifacts between groups + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, mixing between artifacts and groups", 3)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator()); + DeploymentViewVerificator.validateModuleNameUpadate(); + }; + + @Test + public void deploymentScreenDCAEAssetUpdateVFModule_TC1296437_Test() throws Exception{ + String baseFileName = "baseUpdateMinusGroupFlowVF.csar"; + String updateFileName = "baseUpdateFlowVF.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 2)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); +// SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating %s group version, should be %s ", moduleRowText, metaDataFromUI.get(moduleRowText.split("\\.\\.")[1]))); + + Map> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + metaDataFromUI.put("base_ldsa", new HashMap (){ {put("version", "0"); + put("moduleID", "primary");}}); + + DeploymentViewVerificator.validateEditPopover(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now", 3)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + assertTrue(resourceMetaData.getName().equals(ResourceGeneralPage.getNameText())); + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java new file mode 100644 index 0000000000..6a80dfe854 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java @@ -0,0 +1,678 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifactsPlaceholders; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ResourceMetadataEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +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.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.InputsPage; +import org.openecomp.sdc.ci.tests.pages.PropertiesPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.pages.ToscaArtifactsPage; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.PropertiesUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class ImportDCAE extends SetupCDTest { + + private String filePath; + @BeforeMethod + public void beforeTest(){ + filePath = System.getProperty("filepath"); + + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + } + } + + @Test + public void updateDCAEAsset() throws Exception { + ResourceReqDetails resourceMetaData = createDCAEAsset(); + + // update Resource + ResourceReqDetails updatedResource = new ResourceReqDetails(); + updatedResource.setName("ciUpdatedNameImportDCAE"); + updatedResource.setDescription("kuku"); + updatedResource.setVendorName("updatedVendor"); + updatedResource.setVendorRelease("updatedRelease"); + updatedResource.setContactId("ab0001"); + updatedResource.setCategories(resourceMetaData.getCategories()); + updatedResource.setVersion("0.1"); + List newTags = resourceMetaData.getTags(); + newTags.remove(resourceMetaData.getName()); + newTags.add(updatedResource.getName()); + updatedResource.setTags(newTags); + ResourceUIUtils.updateResource(updatedResource, getUser()); + + VfVerificator.verifyVFMetadataInUI(updatedResource); + VfVerificator.verifyVFUpdated(updatedResource, getUser()); + } + + @Test + public void vfcLinkedToComputeInDCAEAssetFlowTest() throws Exception { + String fileName = "importVFC_VFC14.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try{ + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceMetaData = createDCAEAsset(); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement cpElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + Assert.assertNotNull(cpElement); + ServiceVerificator.verifyNumOfComponentInstances(resourceMetaData, "0.1", 4, getUser()); + + canvasManager.linkElements(cpElement, computeElement); + + resourceMetaData.setVersion("0.1"); + VfVerificator.verifyLinkCreated(resourceMetaData, getUser(), 1); + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + @Test + public void addUpdateDeleteDeploymentArtifactToDCAEAssetTest() throws Exception { + createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + assertTrue("artifact "+ deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + assertTrue("artifact "+ deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + @Test + public void addUpdateDeleteInformationalArtifactDCAEAssetTest() throws Exception { + createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(1)); + + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifact.getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + assertTrue("artifact "+ informationalArtifact.getArtifactLabel() + "is not deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + } + + @Test + public void addPropertiesToVfcInstanceInDCAEAssetTest() throws Exception { + String fileName = "importVFC_VFC15.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try{ + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + vfCanvasManager.clickOnCanvaElement(vfcElement); + CompositionPage.showPropertiesAndAttributesTab(); + List properties = CompositionPage.getProperties(); + String propertyValue = "abc123"; + for (int i = 0; i < 2; i++) { + WebElement findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label")); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + + findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-value")); + assertTrue(findElement.getText().equals(propertyValue)); + } + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void changeInstanceVersionDCAEAssetTest() throws Exception{ + ResourceReqDetails atomicResourceMetaData = null; + ResourceReqDetails vfMetaData = null; + CanvasManager vfCanvasManager; + CanvasElement vfcElement = null; + String fileName = "importVFC_VFC16.yml"; + try{ + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + vfMetaData = createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + CompositionPage.clickSubmitForTestingButton(vfMetaData.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "1.0"); + + //verfication + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "1.0"); + } + + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + // future removed from ui + @Test(enabled = false) + public void addUpdateDeleteSimplePropertiesToDCAEAssetTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList){ + PropertiesUIUtils.addNewProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + VfVerificator.verifyPropertiesInUI(propertyList); + PropertiesPage.verifyTotalProperitesField(propertiesCount + propertyList.size()); + + PropertyTypeEnum prop = propertyList.get(0); + prop.setDescription("updatedDescription"); + prop.setValue("value"); + PropertiesUIUtils.updateProperty(prop); + + PropertiesPage.clickDeletePropertyArtifact(prop.getName()); + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size() - 1, () -> PropertiesPage.getElemenetsFromTable())); + } + + // future removed from ui + @Test(enabled = false) + public void DCAEAssetInstancesInputScreenTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + + Map elementsIntancesMap = new HashMap(); + for (LeftPanelCanvasItems element : Arrays.asList(LeftPanelCanvasItems.DATABASE)){ + CanvasElement elementOnCanvas = vfCanvasManager.createElementOnCanvas(element); + vfCanvasManager.clickOnCanvaElement(elementOnCanvas); + String selectedInstanceName = CompositionPage.getSelectedInstanceName(); + elementsIntancesMap.put(selectedInstanceName, element.getValue()); + } + + CompositionPage.moveToInputsScreen(); + int canvasElementsSize = vfCanvasManager.getCanvasElements().size() + 2; + List inputsNamesFromTable = InputsPage.getVFCInstancesNamesFromTable(); + assertTrue(String.format("Instances count is not as Expected: %s Actual: %s", canvasElementsSize, inputsNamesFromTable.size()), inputsNamesFromTable.size() == canvasElementsSize); + + for (String instanceName :inputsNamesFromTable){ + String resourceName = instanceName.split(" ")[0]; + ResourceReqDetails resource = new ResourceReqDetails(); + resource.setName(resourceName); + resource.setVersion("1.0"); + if (resourceName.equals("Port")){ + resource.setResourceType(ResourceTypeEnum.CP.toString()); + } else { + resource.setResourceType(ResourceTypeEnum.VFC.toString()); + } + RestResponse restResponse = RestCDUtils.getResource(resource, getUser()); + Map propertiesNameTypeJson = ResponseParser.getPropertiesNameType(restResponse); + + List propertyRowsFromTable = InputsPage.getInstancePropertiesList(resourceName); + assertTrue("Some properties are missing in table. Instance name is : " + resourceName, propertyRowsFromTable.size() == propertiesNameTypeJson.size()); + VfVerificator.verifyVfInputs(instanceName, propertiesNameTypeJson, propertyRowsFromTable); + + GeneralUIUtils.clickOnElementByText(resourceName); + } + } + + @Test + public void addAllInformationalArtifactPlaceholdersInDCAEAssetTest() throws Exception{ + createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + for(InformationalArtifactsPlaceholders informArtifact : InformationalArtifactsPlaceholders.values()){ + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, filePath,"asc_heat 0 2.yaml", informArtifact.getValue()); + } + + assertTrue(InformationalArtifactPage.checkElementsCountInTable(InformationalArtifactsPlaceholders.values().length)); + } + + @Test + public void verifyToscaArtifactsExistDCAEAssetTest() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + + final int numOfToscaArtifacts = 2; + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); + + for(int i = 0; i < numOfToscaArtifacts; i++){ + String typeFromScreen = ToscaArtifactsPage.getArtifactType(i); + assertTrue(typeFromScreen.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) || typeFromScreen.equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())); + } + + ToscaArtifactsPage.clickSubmitForTestingButton(vfMetaData.getName()); + VfVerificator.verifyToscaArtifactsInfo(vfMetaData, getUser()); + } + + @Test + public void DCAEAssetCertificationTest() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + + String vfName = vfMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + ResourceGeneralPage.clickSubmitForTestingButton(vfName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfName); + TesterOperationPage.certifyComponent(vfName); + + vfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void deleteDCAEAssetCheckedoutTest() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + + GeneralPageElements.clickTrashButtonAndConfirm(); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyVfDeleted(vfMetaData, getUser()); + } + + @Test + public void revertDCAEAssetMetadataTest() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + + ResourceReqDetails vfRevertDetails = new ResourceReqDetails(); + vfRevertDetails.setName("ciUpdatedName"); + vfRevertDetails.setDescription("kuku"); + vfRevertDetails.setCategories(vfMetaData.getCategories()); + vfRevertDetails.setVendorName("updatedVendor"); + vfRevertDetails.setVendorRelease("updatedRelease"); + ResourceUIUtils.fillResourceGeneralInformationPage(vfRevertDetails, getUser(), false); + + GeneralPageElements.clickRevertButton(); + + VfVerificator.verifyVFMetadataInUI(vfMetaData); + } + + @Test + public void addDeploymentArtifactInCompositionScreenDCAEAssetTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3","OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className("i-sdc-designer-sidebar-section-content-item-artifact")); + Assert.assertEquals(1, actualArtifactList.size()); + } + + // future removed from ui + @Test(enabled = false) + public void addPropertyInCompositionScreenDCAEAssetTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showPropertiesAndAttributesTab(); + List propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = CompositionPage.getProperties().size(); + for (PropertyTypeEnum prop : propertyList){ + PropertiesUIUtils.addNewProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> CompositionPage.getProperties())); + } + + @Test + public void addDeploymentArtifactAndVerifyInCompositionScreenDCAEAssetTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + assertTrue(DeploymentArtifactPage.checkElementsCountInTable(1)); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showDeploymentArtifactTab(); + List deploymentArtifactsFromScreen = CompositionPage.getDeploymentArtifacts(); + assertTrue(1 == deploymentArtifactsFromScreen.size()); + + String actualArtifactFileName = deploymentArtifactsFromScreen.get(0).getText(); + assertTrue("asc_heat-0-2.yaml".equals(actualArtifactFileName)); + } + + @Test + public void checkoutDCAEAssetTest() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + + vfMetaData.setVersion("0.2"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + vfMetaData.setVersion("1.1"); + vfMetaData.setUniqueId(null); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + } + + @Test + public void deleteInstanceFromDCAEAssetCanvas() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = CompositionPage.addElementToCanvasScreen(LeftPanelCanvasItems.COMPUTE, vfCanvasManager); + + vfCanvasManager.clickOnCanvaElement(computeElement); + vfCanvasManager.deleteElementFromCanvas(computeElement); + + VfVerificator.verifyNumOfComponentInstances(vfMetaData, 2, getUser()); + } + + @Test + public void changeInstanceNameInDCAEAssetTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = CompositionPage.addElementToCanvasScreen(LeftPanelCanvasItems.COMPUTE, vfCanvasManager); + + String updatedInstanceName = "updatedName"; + vfCanvasManager.updateElementNameInCanvas(computeElement, updatedInstanceName); + + String actualSelectedInstanceName = CompositionPage.getSelectedInstanceName(); + assertTrue(updatedInstanceName.equals(actualSelectedInstanceName)); + } + + @Test + public void submitDCAEAssetForTestingWithNonCertifiedAsset() throws Exception{ + String fileName = "importVFC_VFC17.yml"; + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = createDCAEAsset(); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.addElementToCanvasScreen(atomicResourceMetaData.getName(), canvasManager); + + try{ + CompositionPage.clickSubmitForTestingButton(vfMetaData.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void isDisabledAndReadOnlyInCheckinDCAEAssetTest() throws Exception{ + ResourceReqDetails vfMetaData = createDCAEAsset(); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceMetadataEnum[] fieldsForCheck = {ResourceMetadataEnum.RESOURCE_NAME, + ResourceMetadataEnum.DESCRIPTION, + ResourceMetadataEnum.VENDOR_NAME, + ResourceMetadataEnum.VENDOR_RELEASE, + ResourceMetadataEnum.CONTACT_ID, + ResourceMetadataEnum.CATEGORY, + ResourceMetadataEnum.TAGS}; + + for (ResourceMetadataEnum field: fieldsForCheck){ + VfVerificator.verifyIsElementDisabled(field.getValue(), field.name()); + } + VfVerificator.verifyIsElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue(), DataTestIdEnum.LifeCyleChangeButtons.CREATE.name()); + } + + @Test + public void removeFileFromGeneralPageDCAEAssetTest() throws Exception{ + String fileName2 = "service_input_test_VF2.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsarNoCreate(resourceMetaData, filePath, fileName2, getUser()); + GeneralPageElements.clickDeleteFile(); + + try{ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), 30); + assert(false); + } + catch(Exception e){ + assert(true); + } + } + + @Test + public void activityLogDCAEAssetTest() throws Exception{ + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + ResourceGeneralPage.getLeftMenu().moveToActivityLogScreen(); + + int numberOfRows = GeneralUIUtils.getElementsByCSS("div[class^='flex-container']").size(); + assertTrue("Wrong rows number, should be 2", numberOfRows == 2); + } + + @Test + public void checkinCheckoutChangeDeleteVersionDCAEAssetTest() throws Exception{ + ResourceReqDetails atomicResourceMetaData = createDCAEAsset(); + + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + GeneralPageElements.selectVersion("V0.1"); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKIN); + GeneralUIUtils.clickJSOnElementByText("latest version"); + + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()).getText(); + assertTrue("Expected version: V0.1, Actual version: " + actualVersion, actualVersion.equals("V0.1")); + } + + @Test + public void badFileDCAEAssetTest() throws Exception { + String customFileName = "badVF.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + try{ + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, customFileName, getUser()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.CSAR_INVALID.name()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating error messdge...")); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + } + + @Test + public void validContactAfterCreateDCAEAssetTest() throws Exception{ + String fileName2 = "service_input_test_VF2.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating that userID equal to user that was logged in...")); + assertTrue("wrong userId", resourceMetaData.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public ResourceReqDetails createDCAEAsset() throws Exception{ + String fileName2 = "service_input_test_VF2.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + resourceMetaData.setVersion("0.1"); + return resourceMetaData; + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java new file mode 100644 index 0000000000..92e9a2f6c1 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java @@ -0,0 +1,353 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifactsPlaceholders; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.PropertiesPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.pages.UploadArtifactPopup; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.PropertiesUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.verificator.VFCverificator; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class ImportVFCAsset extends SetupCDTest { + + private ResourceReqDetails atomicResourceMetaData; + + private String filePath; + @BeforeClass + public void beforeClass(){ + filePath = System.getProperty("filepath"); + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator + ""; + } + } + + @DataProvider(name = "assetFiles", parallel = false) + public Object[][] createDataX() { + return new Object[][] { { "importVFC_VFC9.yml" }, { "CP.yml" }, {"VL.yml"} }; + } + + @Test + public void importVFCTest() throws Exception { + String fileName = "importVFC_VFC1.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + } + + @Test + public void importDuplicateVFCTest() throws Exception { + String fileName = "importVFC_VFC2.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails atomicResourceMetaDataDup = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_INFRASTRUCTURE, getUser()); + try{ + ResourceUIUtils.importVfc(atomicResourceMetaDataDup, filePath, fileName, getUser()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + } + + @Test + public void badFileVFCTest() throws Exception { + String fileName = "importVFC_VFC3.yml"; + String customFileName = "Heat-File 1.yaml"; + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + try{ + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, customFileName, getUser()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + } + + @Test + public void validContactAfterCreateVFCTest() throws Exception{ + String fileName = "importVFC_VFC4.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + assertTrue("wrong userId", atomicResourceMetaData.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + @Test + public void validContactAfterUpdateVFCTest() throws Exception{ + String fileName = "importVFC_VFC5.yml"; + String userIdUpdated = "up1234"; + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceUIUtils.defineUserId(userIdUpdated); + assertTrue("userId is not updated",userIdUpdated.equals(ResourceGeneralPage.getContactIdText())); + } + + @Test + public void addUpdateDeleteDeploymentArtifactToVFCTest() throws Exception { + String fileName = "importVFC_VFC6.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true) ); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.updateDescription(newDescription, deploymentArtifactList.get(0)); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + assertTrue("artifact "+ deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + assertTrue("artifact "+ deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + @Test + public void addUpdateDeletePlaceholdersInformationalArtefactVFCTest() throws Exception{ + String fileName = "importVFC_VFC7.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + // create artifacts + List informationalArtifactList = new ArrayList(); + informationalArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + informationalArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuuuuku", "artifact3", "HEAT")); + for (ArtifactInfo informationalArtifact : informationalArtifactList) { + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + } + assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(informationalArtifactList.size())); + + // update artifact description + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifactList.get(0).getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifactList.get(0).getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + // delete artifacts + for (ArtifactInfo informationalArtifact : informationalArtifactList) { + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + } + + assertTrue("not all artifacts is deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + + // fill placeholders + for(InformationalArtifactsPlaceholders informArtifact : InformationalArtifactsPlaceholders.values()){ + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, filePath,"asc_heat 0 2.yaml", informArtifact.getValue()); + } + InformationalArtifactPage.checkElementsCountInTable(InformationalArtifactsPlaceholders.values().length); + } + + @Test + public void addSimplePropertiesToVFCTest() throws Exception{ + String fileName = "importVFC_VFC8.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER, PropertyTypeEnum.FLOAT); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList){ + PropertiesUIUtils.addNewProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + + } + + + @Test(dataProvider = "assetFiles") + public void checkinCheckoutChangeDeleteVersionVFCTest(String customfileName) throws Exception{ + setLog(customfileName); +// getExtendTest().setDescription(customfileName); + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, customfileName, getUser()); + + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + GeneralPageElements.selectVersion("V0.1"); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKIN); + GeneralUIUtils.clickJSOnElementByText("latest version"); + + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()).getText(); + assertTrue("Expected version: V0.1, Actual version: " + actualVersion, actualVersion.equals("V0.1")); + } + + @Test + public void certificationVFCTest() throws Exception{ + String fileName = "importVFC_VFC10.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + String vfName = atomicResourceMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + ResourceGeneralPage.clickSubmitForTestingButton(vfName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfName); + TesterOperationPage.certifyComponent(vfName); + + atomicResourceMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(atomicResourceMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void activityLogVFCTest() throws Exception{ + String fileName = "importVFC_VFC11.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + ResourceGeneralPage.getLeftMenu().moveToActivityLogScreen(); + + int numberOfRows = GeneralUIUtils.getElementsByCSS("div[class^='flex-container']").size(); + assertTrue("Wrong rows number, should be 2", numberOfRows == 2); + } + + @Test + public void removeFileFromGeneralPageVFCTest() throws Exception{ + String fileName = "importVFC_VFC12.yml"; + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfcNoCreate(atomicResourceMetaData, filePath, fileName, getUser()); + + GeneralPageElements.clickDeleteFile(); + + try{ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), 30); + assert(false); + } + catch(Exception e){ + assert(true); + } + } + + @Test + public void maxLengthGeneralInformationVFCTest() throws Exception{ + String fileName = "importVFC_VFC13.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceUIUtils.fillMaxValueResourceGeneralInformationPage(atomicResourceMetaData); + GeneralPageElements.clickUpdateButton(); + VFCverificator.verifyVFCUpdatedInUI(atomicResourceMetaData); + GeneralPageElements.clickDeleteVersionButton(); + } + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} 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 new file mode 100644 index 0000000000..39311731c7 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java @@ -0,0 +1,355 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; + +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ArtifactsCorrelationManager; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.GovernorOperationPage; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.OpsOperationPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.clearspring.analytics.util.Pair; +import com.aventstack.extentreports.Status; +import com.aventstack.extentreports.ExtentTest; + +public class Onboard extends SetupCDTest { + + public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) { + Object[][] arObject = new Object[fileNamesFromFolder.length][]; + + int index = 0; + for (Object obj : fileNamesFromFolder) { + arObject[index++] = new Object[] { filepath, obj }; + } + return arObject; + } + + @DataProvider(name = "VNF_List" , parallel = true) + private static final Object[][] VnfList() throws Exception { + String filepath = getFilePath(); + + Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.length)); + return provideData(fileNamesFromFolder, filepath); + } + + public static String getFilePath() { + String filepath = System.getProperty("filepath"); + if (filepath == null && System.getProperty("os.name").contains("Windows")) { + filepath = FileHandling.getResourcesFilesPath() +"VNFs"; + } + + else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator +"VNFs"; + } + return filepath; + } + + @Test + public void onboardVNFTestSanity() throws Exception, Throwable { +// String filepath = getFilePath(); +// String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + String filepath = getFilePath(); + Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + String vnfFile = fileNamesFromFolder[0].toString(); + runOnboardToDistributionFlow(filepath, vnfFile); + } + + public void runOnboardToDistributionFlow(String filepath, String vnfFile) throws Exception, AWTException { + Pair> onboardAndValidate = OnboardingUtils.onboardAndValidate(filepath, vnfFile, getUser()); + String vspName = onboardAndValidate.left; + + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile ,"The topology template for " + vnfFile + " is as follows : "); + + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.searchForElement(vspName); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); + ArtifactsCorrelationManager.addVNFtoServiceArtifactCorrelation(serviceMetadata.getName(), vspName); + + assertNotNull(vfElement); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + ExtentTestActions.addScreenshot(Status.INFO, "ServiceComposition_" + vnfFile ,"The service topology is as follows : "); + + ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GovernorOperationPage.approveSerivce(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + OpsOperationPage.distributeService(); + OpsOperationPage.displayMonitor(); + + List rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable(); + AssertJUnit.assertEquals(1, rowsFromMonitorTable.size()); + + OpsOperationPage.waitUntilArtifactsDistributed(0); + +// validateInputArtsVSouput(serviceMetadata.getName()); + + getExtendTest().log(Status.INFO, String.format("The onboarding %s test is passed ! ", vnfFile)); + } + +// protected synchronized void validateInputArtsVSouput(String serviceName) { +// +// +// String filepath = System.getProperty("filepath"); +// if (filepath == null && System.getProperty("os.name").contains("Windows")) { +// filepath = FileHandling.getResourcesFilesPath() + folder + File.separator; +// } +// +// Set>>> serviceArtifactCorrelationMap = ArtifactsCorrelationManager.getServiceArtifactCorrelationMap(serviceName); +// +// } + + @Test(dataProvider = "VNF_List") + public void onboardVNFTest(String filepath, String vnfFile) throws Exception, Throwable { + setLog(vnfFile); + runOnboardToDistributionFlow(filepath, vnfFile); + } + + + @Test + public void onboardUpdateVNFTest() throws Exception, Throwable { + String filepath = getFilePath(); + Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + String vnfFile = fileNamesFromFolder[0].toString(); + + Pair> vsp = OnboardingUtils.onboardAndValidate(filepath, vnfFile, getUser()); + String vspName = vsp.left; + ResourceGeneralPage.clickSubmitForTestingButton(vspName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.searchForElement(vspName); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); + assertNotNull(vfElement); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + + HomePage.navigateToHomePage(); + + ///update flow + String updatedVnfFile = fileNamesFromFolder[1].toString(); + + getExtendTest().log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); + // update VendorSoftwareProduct + OnboardingUtils.updateVnfAndValidate(filepath, vsp, updatedVnfFile, getUser()); + + ResourceGeneralPage.clickSubmitForTestingButton(vspName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + // replace exiting VFI in service with new updated + + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + serviceCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(serviceCanvasManager, vfElement, "2.0"); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + + ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GovernorOperationPage.approveSerivce(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + OpsOperationPage.distributeService(); + OpsOperationPage.displayMonitor(); + + List rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable(); + AssertJUnit.assertEquals(1, rowsFromMonitorTable.size()); + + OpsOperationPage.waitUntilArtifactsDistributed(0); + + getExtendTest().log(Status.INFO, String.format("onboarding %s test is passed ! ", vnfFile)); + + + } + + @Test + public void threeVMMSCsInServiceTest() throws Exception{ + String filepath = getFilePath(); + + + List vmmscList = new ArrayList(); + vmmscList = Arrays.asList(new File(filepath).list()).stream().filter(e -> e.contains("vmmsc") && e.endsWith(".zip")).collect(Collectors.toList()); + assertTrue("Did not find vMMSCs", vmmscList.size() > 0); + + Map vspNames = new HashMap(); + for (String vnfFile : vmmscList){ + getExtendTest().log(Status.INFO, String.format("going to onboard the VNF %s......", vnfFile)); + System.out.println(String.format("going to onboard the VNF %s......", vnfFile)); + + OnboardingUtils.createVendorLicense(getUser()); + Pair> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(vnfFile, filepath, getUser()); + + getExtendTest().log(Status.INFO, String.format("searching for onboarded %s", vnfFile)); + HomePage.showVspRepository(); + getExtendTest().log(Status.INFO,String.format("going to import %s......", vnfFile.substring(0, vnfFile.indexOf(".")))); + OnboardingUtils.importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); + + String vspName = createVendorSoftwareProduct.left; + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + + vspNames.put(vnfFile, vspName); + } + + reloginWithNewRole(UserRoleEnum.TESTER); + for (String vsp : vspNames.values()){ + GeneralUIUtils.findComponentAndClick(vsp); + TesterOperationPage.certifyComponent(vsp); + } + + reloginWithNewRole(UserRoleEnum.DESIGNER); + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + + for (String vsp : vspNames.values()){ + CompositionPage.searchForElement(vsp); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vsp); + assertNotNull(vfElement); + } + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", vspNames.values().size(), getUser()); + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Info_" + getExtendTest().getModel().getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.INFO, "Three kinds of vMMSC are in canvas now." + getExtendTest().addScreenCaptureFromPath(absolutePath)); + + ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GovernorOperationPage.approveSerivce(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + OpsOperationPage.distributeService(); + OpsOperationPage.displayMonitor(); + + List rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable(); + AssertJUnit.assertEquals(1, rowsFromMonitorTable.size()); + + OpsOperationPage.waitUntilArtifactsDistributed(0); + + } + + + + + + + + + + + + + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java new file mode 100644 index 0000000000..cb647aec6d --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java @@ -0,0 +1,303 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertEquals; + +import java.awt.AWTException; +import java.io.File; +import java.io.FileOutputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.bouncycastle.util.encoders.Base64; +import org.openecomp.sdc.be.model.ComponentInstance; +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.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +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.slf4j.LoggerFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.clearspring.analytics.util.Pair; +import com.google.gson.Gson; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import fj.data.Either; + +public class OnboardViaApis{ + + + private static final String FULL_PATH = "C://tmp//CSARs//"; + + public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) { + Object[][] arObject = new Object[fileNamesFromFolder.length][]; + + int index = 0; + for (Object obj : fileNamesFromFolder) { + arObject[index++] = new Object[] { filepath, obj }; + } + return arObject; + } + + @DataProvider(name = "VNF_List" , parallel = false) + private static final Object[][] VnfList() throws Exception { + String filepath = FileHandling.getVnfRepositoryPath(); + + Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.length)); + return provideData(fileNamesFromFolder, filepath); + } + + +//------------------------------------------------------------------------------------------------------- + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + private static String vendorId; + private static String vendorLicenseName; + private static String vendorLicenseAgreementId; + private static String featureGroupId; + ResourceReqDetails resourceDetails; + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + + + @BeforeMethod + public void before(){ + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.getLogger("org.apache").setLevel(Level.OFF); + lc.getLogger("org.*").setLevel(Level.OFF); + lc.getLogger("org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest").setLevel(Level.OFF); + resourceDetails = ElementFactory.getDefaultResource(); + + } + + @Test(dataProvider = "VNF_List") + public void onboardVNFTestViaApis(String filepath, String vnfFile) throws Exception, Throwable { + Service service = null; + String fullFileName = FULL_PATH + vnfFile + ".csar"; + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + System.err.println(timestamp + " Starting test with VNF: " + vnfFile); + service = runOnboardViaApisOnly(filepath, vnfFile); + timestamp = new Timestamp(System.currentTimeMillis()); + System.err.println(timestamp + " Finished test with VNF: " + vnfFile); + timestamp = new Timestamp(System.currentTimeMillis()); + System.err.println(timestamp + " Starting download service csar file: " + vnfFile); + File file = new File(fullFileName); + downloadToscaCsarToDirectory(service, file); + timestamp = new Timestamp(System.currentTimeMillis()); + System.err.println(timestamp + " Finished download service csar file: " + vnfFile); + System.out.println("end"); + + } + + public static void downloadToscaCsarToDirectory(Service service, File file) { + try { + Either serviceToscaArtifactPayload = AtomicOperationUtils.getServiceToscaArtifactPayload(service, "assettoscacsar"); + if(serviceToscaArtifactPayload.left().value() != null){ + Gson gson = new Gson(); + @SuppressWarnings("unchecked") + Map fromJson = gson.fromJson(serviceToscaArtifactPayload.left().value(), Map.class); + String string = fromJson.get("base64Contents").toString(); + byte[] byteArray = Base64.decode(string.getBytes(StandardCharsets.UTF_8)); + File downloadedFile = new File(file.getAbsolutePath()); + FileOutputStream fos = new FileOutputStream(downloadedFile); + fos.write(byteArray); + fos.flush(); + fos.close(); + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + public Service runOnboardViaApisOnly(String filepath, String vnfFile) throws Exception, AWTException { + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + System.err.println(timestamp + " Starting onboard VNF: " + vnfFile); + Pair> onboardAndValidate = onboardAndValidateViaApi(filepath, vnfFile, sdncDesignerDetails1); + String vspName = onboardAndValidate.left; + timestamp = new Timestamp(System.currentTimeMillis()); + System.err.println(timestamp + " Finished onboard VNF: " + vnfFile); + Resource resource = AtomicOperationUtils.getResourceObject(resourceDetails.getUniqueId()); + + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true); + resource = AtomicOperationUtils.getResourceObject(resource.getUniqueId()); + // create service + + Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); + Either addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + return service; + } + + + + public Pair> onboardAndValidateViaApi(String filepath, String vnfFile, User user) throws Exception { + + createVendorLicense(user); + Pair> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user); + String vspName = createVendorSoftwareProduct.left; + List tags = new ArrayList<>(); + tags.add(vspName); + Map map = createVendorSoftwareProduct.right; + + resourceDetails.setCsarUUID(map.get("vspId")); + resourceDetails.setCsarVersion("1.0"); + resourceDetails.setName(vspName); + resourceDetails.setTags(tags); + resourceDetails.setResourceType(map.get("componentType")); + resourceDetails.setVendorName(map.get("vendorName")); + resourceDetails.setVendorRelease("1.0"); + resourceDetails.setResourceType("VF"); + RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails1); + + return createVendorSoftwareProduct; + } + + public static Pair> createVendorSoftwareProduct(String HeatFileName, String filepath, User user) + throws Exception { + Pair> pair = createVSP(HeatFileName, filepath, user); + + String vspid = pair.right.get("vspId"); + + prepareVspForUse(user, vspid); + + return pair; + } + + public static void prepareVspForUse(User user, String vspid) throws Exception { + RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue()); + + RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue()); + + } + public static void createVendorLicense(User user) throws Exception { + vendorLicenseName = "ciLicense" + UUID.randomUUID().toString().split("-")[0]; + RestResponse vendorLicenseResponse = OnboardingUtils.createVendorLicenseModels_1(vendorLicenseName, user); + assertEquals("did not succeed to create vendor license model", 200, + vendorLicenseResponse.getErrorCode().intValue()); + vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value"); + + RestResponse vendorKeyGroupsResponse = OnboardingUtils.createVendorKeyGroups_2(vendorId, user); + assertEquals("did not succeed to create vendor key groups", 200, + vendorKeyGroupsResponse.getErrorCode().intValue()); + String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value"); + + RestResponse vendorEntitlementPool = OnboardingUtils.createVendorEntitlementPool_3(vendorId, user); + assertEquals("did not succeed to create vendor entitlement pool", 200, + vendorEntitlementPool.getErrorCode().intValue()); + String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), + "value"); + + RestResponse vendorLicenseFeatureGroups = OnboardingUtils.createVendorLicenseFeatureGroups_4(vendorId, keyGroupId, + entitlementPoolId, user); + assertEquals("did not succeed to create vendor license feature groups", 200, + vendorLicenseFeatureGroups.getErrorCode().intValue()); + featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value"); + + RestResponse vendorLicenseAgreement = OnboardingUtils.createVendorLicenseAgreement_5(vendorId, featureGroupId, user); + assertEquals("did not succeed to create vendor license agreement", 200, + vendorLicenseAgreement.getErrorCode().intValue()); + vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), + "value"); + + RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user); + assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); + + RestResponse submitVendorLicense = OnboardingUtils.submitVendorLicense(vendorId, user); + assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); + + } + + + public static Pair> createVSP(String HeatFileName, String filepath, User user) throws Exception { + String vspName = OnboardingUtils.handleFilename(HeatFileName); + + Pair> createNewVspPair = OnboardingUtils.createNewVendorSoftwareProduct(vspName, vendorLicenseName, vendorId, vendorLicenseAgreementId, featureGroupId, user); + RestResponse createNewVendorSoftwareProduct = createNewVspPair.left; + assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue()); + String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId"); + String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId"); + + Map vspMeta = createNewVspPair.right; + Map vspObject = new HashMap(); + Iterator iterator = vspMeta.keySet().iterator(); + while(iterator.hasNext()){ + Object key = iterator.next(); + Object value = vspMeta.get(key); + vspObject.put(key.toString(), value.toString()); + } + vspObject.put("vspId", vspid); + vspObject.put("componentId", componentId); + vspObject.put("vendorName", vendorLicenseName); + vspObject.put("attContact", user.getUserId()); + + RestResponse uploadHeatPackage = OnboardingUtils.uploadHeatPackage(filepath, HeatFileName, vspid, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = OnboardingUtils.validateUpload(vspid, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + Pair> pair = new Pair>(vspName, vspObject); + + return pair; + } + + + + + + + + + +// ---------------------------------------------------------------------------------------------------------------------------------------- + + + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java new file mode 100644 index 0000000000..e0e13b7036 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java @@ -0,0 +1,93 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import java.io.File; + +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ProductGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ProductUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +/** + * @author al714h + * + */ + +public class Product extends SetupCDTest { + + private String filePath; + @BeforeMethod + public void beforeTest(){ + filePath = System.getProperty("filepath"); + + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + } + } + + + @Test + public void createProductAndAddCertifiedServiceInstance() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + + ServiceUIUtils.createService(serviceMetadata, getUser()); + GeneralPageElements.clickSubmitForTestingButton(serviceMetadata.getName()); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + reloginWithNewRole(UserRoleEnum.PRODUCT_MANAGER1); + ProductUIUtils.createProduct(productReqDetails, getUser()); + ProductGeneralPage.getProductLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement canvasElement = CompositionPage.addElementToCanvasScreen(serviceMetadata.getName(), canvasManager); + canvasManager.clickOnCanvaElement(canvasElement); + } + + @Test + public void loginAsProductStrateger() throws Exception { + reloginWithNewRole(UserRoleEnum.PRODUCT_STRATEGIST1); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} 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 new file mode 100644 index 0000000000..86e52a296d --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java @@ -0,0 +1,698 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.CompositionScreenEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ServiceMetadataEnum; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +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.NormativeTypesEnum; +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.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.InputsPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.CatalogUIUtilitis; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; +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.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.verificator.DeploymentViewVerificator; +import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.SkipException; +import org.testng.TestException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class Service extends SetupCDTest { + + private static final String DESCRIPTION = "kuku"; + private static final String ARTIFACT_LABEL = "artifact3"; + private static final String ARTIFACT_LABEL_UPDATE = "artifactUpdate"; + private static final String GET_ARTIFACT_LIST_BY_CLASS_NAME = "i-sdc-designer-sidebar-section-content-item-artifact"; + private static final String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; + private static final String HEAT_FILE_YAML_UPDATE_NAME = "Heat-File-Update.yaml"; + private String filePath; + + @BeforeMethod + public void beforeTest(){ + filePath = FileHandling.getFilePath(""); + } + + + @Test + public void createService() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + } + + @Test + public void validDefaultContactAndTagAfterCreateService() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createServiceWithDefaultTagAndUserId(serviceMetadata, getUser()); + + assertTrue("wrong userId", getUser().getUserId().equals(ResourceGeneralPage.getContactIdText())); + + List actualTags = Arrays.asList(ServiceGeneralPage.getTags()); + assertTrue("wrong tags", (actualTags.size() == 1) && actualTags.get(0).equals(serviceMetadata.getName())); + } + + @Test + public void updateService() throws Exception { + // Create Service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + // Update Service + ServiceGeneralPage.deleteOldTags(serviceMetadata); + serviceMetadata.setName("ciUpdatedNameSanity"); + serviceMetadata.setDescription("updatedDescriptionSanity"); + serviceMetadata.setProjectCode("654321"); + serviceMetadata.setContactId("cs6543"); + serviceMetadata.getTags().addAll(Arrays.asList("updatedTag", "oneMoreUpdatedTag", "lastOne UpdatedTag")); + ServiceUIUtils.setServiceCategory(serviceMetadata, ServiceCategoriesEnum.VOIP); + ServiceUIUtils.fillServiceGeneralPage(serviceMetadata, getUser()); + GeneralPageElements.clickCreateButton(); + + ServiceVerificator.verifyServiceUpdatedInUI(serviceMetadata); + } + + @Test + public void deleteService() throws Exception { + + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + // Delete service + //GeneralUIUtils.HighlightMyElement(GeneralUIUtils.getWebButton("delete_version")); + GeneralPageElements.clickTrashButtonAndConfirm(); + + // Verification + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogSearchBox(serviceMetadata.getName()); + ServiceVerificator.verifyServiceDeletedInUI(serviceMetadata); + } + + @Test + public void checkoutServiceTest() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,"OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GeneralPageElements.clickCheckoutButton(); + + serviceMetadata.setVersion("0.2"); + ServiceVerificator.verifyServiceLifecycle(serviceMetadata, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + ServiceVerificator.verifyVersionUI(serviceMetadata.getVersion()); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + serviceMetadata.setVersion("1.1"); + serviceMetadata.setUniqueId(null); + ServiceVerificator.verifyServiceLifecycle(serviceMetadata, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + ServiceVerificator.verifyVersionUI(serviceMetadata.getVersion()); + } + + @Test + public void submitServiceForTestingWithNonCertifiedAsset() throws Exception{ + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.createResource(atomicResourceMetaData, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + try{ + CompositionPage.clickSubmitForTestingButton(serviceMetadata.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + + } + + @Test + public void addDeploymentArtifactInCompositionScreenTest() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,"OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + AssertJUnit.assertEquals(1, actualArtifactList.size()); + + for(WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()){ + assertTrue(HEAT_FILE_YAML_NAME.equals(actualArtifactFileName.getText())); + } + + } + + @Test + public void addInformationArtifactInCompositionScreenTest() throws Exception{ + String fileName = HEAT_FILE_YAML_NAME; + String descriptionText = DESCRIPTION; + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + ArtifactInfo artifactInfo = new ArtifactInfo(filePath, fileName, descriptionText, ARTIFACT_LABEL,"OTHER"); + CompositionPage.showInformationArtifactTab(); + List beforeArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifactInfo, CompositionPage.artifactPopup()); + + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + assertTrue(String.format("Wrong number of artifacts, Expected: %s Actual: %s", beforeArtifactList.size() + 1, actualArtifactList.size()), + (beforeArtifactList.size() + 1) == actualArtifactList.size()); + for(DataTestIdEnum.InformationalArtifactsService artifact: DataTestIdEnum.InformationalArtifactsService.values()){ + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(artifact, filePath, fileName, descriptionText); + } + int numberOfFiles = CompositionPage.getAllAddedArtifacts().size(); + assertTrue(String.format("Wrong number of artifacts, Expected: %s Actual: %s", (beforeArtifactList.size() + 1), numberOfFiles), (beforeArtifactList.size() + 1) == numberOfFiles); + + for(WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()){ + assertTrue(fileName.equals(actualArtifactFileName.getText())); + } + + } + + @Test + public void addAPIArtifactInCompositionScreenTest() throws Exception{ + + if(true){ + throw new SkipException("Open bug 292017"); + } + + String fileName = HEAT_FILE_YAML_NAME, + descriptionText = DESCRIPTION, + url = "http://kuku.com"; + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + ArtifactInfo artifactInfo = new ArtifactInfo(filePath, fileName, descriptionText, ARTIFACT_LABEL,"OTHER"); + CompositionPage.showAPIArtifactTab(); + + for(DataTestIdEnum.APIArtifactsService artifact: DataTestIdEnum.APIArtifactsService.values()){ + ArtifactUIUtils.fillPlaceHolderAPIArtifact(artifact, filePath, fileName, descriptionText, url); + } + int numberOfFiles = CompositionPage.getAllAddedArtifacts().size(), + numberOfPlacehoders = DataTestIdEnum.APIArtifactsService.values().length; + assertTrue(String.format("Wrong file count, should be %s files", numberOfPlacehoders), numberOfPlacehoders == numberOfFiles); + + for(WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()){ + assertTrue(fileName.equals(actualArtifactFileName.getText())); + } + } + + @Test + public void ManagmentWorkflowTest() throws Exception{ + + if(true){ + throw new SkipException("Open bug 287416"); + } + + String descriptionText = DESCRIPTION, + descriptionTextEdit = "kuku2"; + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ServiceGeneralPage.getServiceLeftMenu().moveToManagmentWorkflow(); + ServiceGeneralPage.fillAndAddNewWorkflow(descriptionText, descriptionText); + ServiceVerificator.verifyManagmentWorkflow(descriptionText, descriptionText); + + ServiceGeneralPage.clickAddWorkflow(); + ServiceGeneralPage.fillAndAddNewWorkflow(descriptionTextEdit, descriptionTextEdit); + } + + @Test + public void deleteChangeVersionTest() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,"OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GeneralPageElements.clickCheckoutButton(); + + changeDeleteAndValidateVersionOnGeneralPage("0.1", "0.2", serviceMetadata.getName()); + + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + changeDeleteAndValidateVersionOnGeneralPage("1.0", "1.1", serviceMetadata.getName()); + } + + @Test + public void compositionScreenRightSideButtonsTest() throws Exception{ + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showInformationTab(); + ServiceVerificator.verifyOpenTabTitle(CompositionScreenEnum.INFORMATION); + + //feature removed from UI +// CompositionPage.showCompositionTab(); +// ServiceVerificator.verifyOpenTabTitle(CompositionScreenEnum.COMPOSITION); + + CompositionPage.showDeploymentArtifactTab(); + ServiceVerificator.verifyOpenTabTitle(CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB); + + CompositionPage.showInputsTab(); + assertTrue(CompositionPage.getOpenTabTitle().size() == 0); + + CompositionPage.showAPIArtifactTab(); + ServiceVerificator.verifyOpenTabTitle(CompositionScreenEnum.API); + + CompositionPage.showInformationArtifactTab(); + ServiceVerificator.verifyOpenTabTitle(CompositionScreenEnum.INFORMATION_ARTIFACTS); + + } + + @Test + public void addDeploymentArtifactToVFInstanceTest() throws Exception{ + + 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()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + checkInService(serviceMetadata); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + } + + @Test + public void deleteDeploymentArtifactFromVFInstanceTest() throws Exception{ + + 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()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + deleteAndVerifyArtifact(actualArtifactList); + + } + + @Test + public void deleteDeploymentArtifactFromVFInstanceNextVersionTest() throws Exception{ + + 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()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + checkInService(serviceMetadata); + ResourceGeneralPage.clickCheckoutButton(); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + deleteAndVerifyArtifact(actualArtifactList); +// change container version + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()); + GeneralPageElements.selectVersion("V0.1"); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + + } + +// service version V0.1 default artifact, service version V0.2 updated artifact + @Test + public void updateDeploymentArtifactOnVFInstanceNextVersionTest() throws Exception{ + + 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()); + ArtifactInfo artifactUpdate = new ArtifactInfo(filePath, HEAT_FILE_YAML_UPDATE_NAME, DESCRIPTION, ARTIFACT_LABEL_UPDATE,ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + checkInService(serviceMetadata); + ResourceGeneralPage.clickCheckoutButton(); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + deleteAndVerifyArtifact(actualArtifactList); +// upload new artifact + addDeploymentArtifact(artifactUpdate, CanvasManager.getCanvasManager(), computeElement); + checkArtifactIfAdded(1, HEAT_FILE_YAML_UPDATE_NAME); +// change container version + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()); + GeneralPageElements.selectVersion("V0.1"); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + + } + + public void clickOncanvasElement(CanvasElement computeElement) { + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.clickOnCanvaElement(computeElement); + } + + public void checkInService(ServiceReqDetails serviceMetadata) throws Exception { + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + } + + public static void deleteAndVerifyArtifact(List actualArtifactList) { + if (actualArtifactList.size()>0){ + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ITEM.getValue() + ARTIFACT_LABEL); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to delete " + HEAT_FILE_YAML_NAME + " artifact" + " and check if deleted"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + ARTIFACT_LABEL); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + assertTrue("Artifact does not deleted", !GeneralUIUtils.waitForElementInVisibilityByTestId(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME))); + } + } + + + public void checkArtifactIfAdded(Integer expectedNumOfARtifacts, String expectedArtifactName) { + + List actualArtifactList; + actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + assertTrue("Expected artifact count is: " + expectedNumOfARtifacts + ", but was " + actualArtifactList.size(),expectedNumOfARtifacts==actualArtifactList.size()); + + if(expectedNumOfARtifacts != 0){ + for(WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()){ + assertTrue("Artifact name does not match, expected " + expectedArtifactName + ", but was " + actualArtifactFileName.getText(), expectedArtifactName.equals(actualArtifactFileName.getText())); + } + } + + } + + + public CanvasElement createServiceWithRiArtifact(ResourceReqDetails atomicResourceMetaData, ServiceReqDetails serviceMetadata, ArtifactInfo artifact) throws Exception, AWTException { + ResourceUIUtils.createResource(atomicResourceMetaData, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + ServiceUIUtils.createService(serviceMetadata, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement computeElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + addDeploymentArtifact(artifact, canvasManager, computeElement); + + return computeElement; + } + + + public void addDeploymentArtifact(ArtifactInfo artifact, CanvasManager canvasManager, CanvasElement computeElement) throws Exception { + canvasManager.clickOnCanvaElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + } + + @Test + public void isDisabledAndReadOnlyInCheckin() throws Exception{ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + GeneralPageElements.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + + ServiceMetadataEnum[] fieldsForCheck = {ServiceMetadataEnum.SERVICE_NAME, + ServiceMetadataEnum.CONTACT_ID, + ServiceMetadataEnum.DESCRIPTION, + ServiceMetadataEnum.PROJECT_CODE, + ServiceMetadataEnum.TAGS}; + for (ServiceMetadataEnum field: fieldsForCheck){ + assertTrue(GeneralUIUtils.isElementReadOnly(field.getValue())); + } + + assertTrue(GeneralUIUtils.isElementDisabled(ServiceMetadataEnum.CATEGORY.getValue())); + assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue())); + } + + // future removed from ui + @Test(enabled = false) + public void inputsTest() throws Exception{ + String fileName = "service_input_test_VF2.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + GeneralPageElements.clickCheckinButton(resourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + String selectedInstanceName = addResourceToServiceInCanvas(resourceMetaData); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToInputsScreen(); + + InputsPage.addInputToService(selectedInstanceName, "volume_id"); + InputsPage.deleteServiceInput(selectedInstanceName, "volume_id"); + + // Trying to find deleted service input + try{ + InputsPage.getServiceInput(selectedInstanceName, "volume_id"); + assert(false); + } + catch(TestException e){ + } + } + + @Test + public void deploymentViewServiceTest() throws Exception{ + + if(true){ + throw new SkipException("Open bug 295220, 295180"); + } + + String fileName2 = "vSeGW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + addResourceToServiceInCanvas(resourceMetaData); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToDeploymentViewScreen(); + + serviceMetadata.setVersion("0.1"); + List instanceRowsFromTable = GeneralUIUtils.getElementsByCSS("div[data-tests-id^='hierarchy-instance'] span[class^='expand-collapse-title-text']"); + for(WebElement instanceRow: instanceRowsFromTable){ + String instanceRowText = instanceRow.getText(); + List instanceModulesList = DeploymentPage.getInstanceModulesList(instanceRowText); + for (WebElement instanceModule: instanceModulesList){ + String instanceModuleText = instanceModule.getText(); + ResourceUIUtils.clickOnElementByText(instanceModuleText, "instance"); + + ServiceVerificator.verifyDeploymentPageSubElements(instanceModuleText.split("\\.\\.")[1], new DeploymentViewVerificator(filePath + fileName2)); + + ServiceVerificator.verifyDisabledServiceProperties(); + String isBaseValue = ServiceVerificator.getVFModulePropertieValue(serviceMetadata, "isBase", instanceModuleText); + if (isBaseValue.equals("false")) + ServiceVerificator.verifyEnabledServiceProperties(); + + ResourceUIUtils.clickOnElementByText(instanceModuleText, "instance"); + } + } + } + + @Test + public void vfModuleCustomizationUUIDServiceTest() throws Exception{ + String fileName2 = "vSeGW.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + addResourceToServiceInCanvas(resourceMetaData); + + serviceMetadata.setVersion("0.1"); + ServiceVerificator.verifyVFModuleCustomizationUUID(serviceMetadata); + } + + @Test + public void checkoutCertifyRemainSameCustomizationUUIDServiceTest() throws Exception{ + String fileName2 = "vSeGW.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(resourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + TesterOperationPage.certifyComponent(resourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata, getUser()); + + addResourceToServiceInCanvas(resourceMetaData); + + serviceMetadata.setVersion("0.1"); + ServiceVerificator.verifyVFModuleCustomizationUUID(serviceMetadata); + List allVFModuleCustomizationUUIDs = ServiceVerificator.getAllVFModuleCustomizationUUIDs(serviceMetadata); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GeneralPageElements.clickCheckoutButton(); + + serviceMetadata.setVersion("0.2"); + assertTrue(ServiceVerificator.isEqualCustomizationUUIDsAfterChanges(allVFModuleCustomizationUUIDs, ServiceVerificator.getAllVFModuleCustomizationUUIDs(serviceMetadata))); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + serviceMetadata.setVersion("1.1"); + serviceMetadata.setUniqueId(null); + assertTrue(ServiceVerificator.isEqualCustomizationUUIDsAfterChanges(allVFModuleCustomizationUUIDs, ServiceVerificator.getAllVFModuleCustomizationUUIDs(serviceMetadata))); + } + + + public synchronized String addResourceToServiceInCanvas(ResourceReqDetails resourceMetaData) throws Exception { + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(resourceMetaData.getName()); + CanvasElement computeElement = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + canvasManager.clickOnCanvaElement(computeElement); + String selectedInstanceName = CompositionPage.getSelectedInstanceName(); + return selectedInstanceName; + } + + public static void changeDeleteAndValidateVersionOnGeneralPage(String previousVersion, String currentVersion, String serviceName) throws Exception{ + GeneralPageElements.selectVersion("V" + previousVersion); + ServiceVerificator.verifyVersionUI(previousVersion); + GeneralUIUtils.clickJSOnElementByText("latest version"); + ServiceVerificator.verifyVersionUI(currentVersion); + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(serviceName); + ServiceVerificator.verifyVersionUI(previousVersion); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java new file mode 100644 index 0000000000..2c7dc9868d --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java @@ -0,0 +1,402 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +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.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.utilities.DownloadManager; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.verificator.VFCArtifactVerificator; +import org.testng.SkipException; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +public class VFCArtifacts extends SetupCDTest { + + private static final String DEPLOYMENT = "Deployment"; + private static final String INFORMATIONAL = "Informational"; + private static final String ARTIFACTS = "artifacts"; + private static final String DEPLOYMENT_ARTIFACTS = "deploymentArtifacts"; + private String filePath; + private Object object; + @BeforeClass + public void beforeClass(){ + filePath = System.getProperty("filepath"); + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath() + "VFCArtifacts"+ File.separator; + } + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator + "VFCArtifacts"+ File.separator; + } + } + + @Test + public void ImportMultiVFCTest_TC1407998() throws Exception{ + + String csarFile = "Import_Multi_VFC.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + RestResponse getResponse = RestCDUtils.getResource(resourceMetaData, getUser()); + assertTrue(getResponse.getErrorCode().intValue() == 200); + + Map> expectedArtifactMap = verifyVfcArtifacts(filePath, csarFile, resourceMetaData, getResponse); + + VFCArtifactVerificator.verifyVFCArtifactsNotInVFArtifactList(resourceMetaData, getUser(), getResponse, expectedArtifactMap); + + + } + + @Test + public void updateCsarWithVFCArtifacts_ModifyArtifacts_TC1449482() throws Exception{ + + String csarFile = "LDSA-ORIG.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + Map artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + csarFile); + List vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys){ + VFCArtifactVerificator.setActualVfcArtifactList(key, resourceMetaData, getUser()); + } + + String updatedCsarFile = "LDSA-MODIFY.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + Map updatedArtifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + updatedCsarFile); + List updatedVfcKeys = updatedArtifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : updatedVfcKeys){ + verifyVfcInstanceArtifacts(resourceMetaData, null, updatedArtifactsFromCsar, key); + VFCArtifactVerificator.verifyVfcArtifactUpdated(key, resourceMetaData, getUser()); + } + } + + @Test + public void updateCsarWithVFCArtifacts_DeleteAndAddArtifacts_TC1449473() throws Exception{ + String csarFile = "LDSA-ORIG.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + String updatedCsarFile = "LDSA-DELETE-ADD.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + verifyVfcArtifacts(filePath, updatedCsarFile, resourceMetaData, null); + } + + @Test + public void updateCsarWithVFCArtifacts_AddFirstVFCIdentifier_TC1425896() throws Exception{ + + String csarFile = "LDSA-ORIG-OLD_STRUCTURE.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + VFCArtifactVerificator.verifyNoVfcArtifacts(resourceMetaData, getUser(), null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + String[] artifactNamesFromFile = ArtifactFromCsar.getArtifactNamesFromCsar(filePath, csarFile); + String[] artifactsFromFileBeforeUpdate = DeploymentArtifactPage.verifyArtifactsExistInTable(artifactNamesFromFile); + DeploymentArtifactPage.getLeftMenu().moveToGeneralScreen(); + + String updatedCsarFile = "LDSA-ADD.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + verifyVfcArtifacts(filePath, updatedCsarFile, resourceMetaData, null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(artifactsFromFileBeforeUpdate); + } + + + @Test + public void updateCsarWithVFCArtifacts_AddAdditionalVFCIdentifier_TC1425898() throws Exception{ + + String csarFile = "LDSA-SINGLE.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + Map artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + csarFile); + List vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys){ + VFCArtifactVerificator.setActualVfcArtifactList(key, resourceMetaData, getUser()); + } + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + String[] artifactNamesFromFile = ArtifactFromCsar.getArtifactNamesFromCsar(filePath, csarFile); + String[] artifactsFromFileBeforeUpdate = DeploymentArtifactPage.verifyArtifactsExistInTable(artifactNamesFromFile); + DeploymentArtifactPage.getLeftMenu().moveToGeneralScreen(); + + String updatedCsarFile = "LDSA-MULTI.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + Map updatedArtifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + updatedCsarFile); + List updatedVfcKeys = updatedArtifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : updatedVfcKeys){ + verifyVfcInstanceArtifacts(resourceMetaData, null, updatedArtifactsFromCsar, key); + if (vfcKeys.contains(key)){ + VFCArtifactVerificator.verifyVFCArtifactNotChanged(key, resourceMetaData, getUser()); + } + } + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(artifactsFromFileBeforeUpdate); + } + + @Test + public void updateCsarWithVFCArtifacts_DeleteAll_TC1425581() throws Exception{ + String csarFile = "LDSA-ORIG.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + String[] artifactNamesFromFile = ArtifactFromCsar.getArtifactNamesFromCsar(filePath, csarFile); + String[] artifactsFromFileBeforeUpdate = DeploymentArtifactPage.verifyArtifactsExistInTable(artifactNamesFromFile); + DeploymentArtifactPage.getLeftMenu().moveToGeneralScreen(); + + String updatedCsarFile = "LDSA-DELETE-ALL.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + VFCArtifactVerificator.verifyNoVfcArtifacts(resourceMetaData, getUser(), null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(artifactsFromFileBeforeUpdate); + } + + @Test + public void importComplexVFCArtifacts_Onboarding_TC1484153() throws Exception{ + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "vProbes_FE.zip"; + String snmpFile = "Fault-alarms-ASDC-vprobes-vLB.zip"; + + OnboardingUtils.createVendorLicense(getUser()); + Pair> createVSP = OnboardingUtils.createVSP(vnfFile, filePath, getUser()); + String vspName = createVSP.left; + resourceMetaData.setName(vspName); + Map resourceMeta = createVSP.right; + String vspid = resourceMeta.get("vspId"); + OnboardingUtils.addVFCArtifacts(filePath, snmpFile, null, vspid, getUser()); + OnboardingUtils.prepareVspForUse(getUser(), vspid); + + String downloadDirectory = getWindowTest().getDownloadDirectory(); + String csarFile = vspid + ".csar"; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUtils.importVSP(createVSP); + resourceMetaData.setVersion("0.1"); + + verifyVfcArtifacts(downloadDirectory, csarFile, resourceMetaData, null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, vnfFile); + + } + + @Test + public void updateComplexVFCArtifacts_AddRemove_Onboarding_TC1484185() throws Exception{ + + //check of version is 1 + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "vProbes_FE.zip"; + String snmpPollFile = "vprobes-vLB.zip"; + String updatedSnmpPollFile = "vprobes-vLBAgent.zip"; + + OnboardingUtils.createVendorLicense(getUser()); + Pair> createVSP = OnboardingUtils.createVSP(vnfFile, filePath, getUser()); + String vspName = createVSP.left; + resourceMetaData.setName(vspName); + Map resourceMeta = createVSP.right; + String vspid = resourceMeta.get("vspId"); + String montoringComponentId = OnboardingUtils.addVFCArtifacts(filePath, snmpPollFile, null, vspid, getUser()); + OnboardingUtils.prepareVspForUse(getUser(), vspid); + + String downloadDirectory = getWindowTest().getDownloadDirectory(); + String csarFile = vspid + ".csar"; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUtils.importVSP(createVSP); + + ResourceGeneralPage.clickSubmitForTestingButton(vspName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + OnboardingUtils.updateVspWithVfcArtifacts(filePath, vspid, updatedSnmpPollFile, null, montoringComponentId, getUser()); + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUtils.updateVSP(createVSP); + resourceMetaData.setVersion("1.1"); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, vnfFile); + + verifyVfcArtifacts(downloadDirectory, csarFile, resourceMetaData, null); + + } + + @Test + public void updateComplexVFCArtifacts_Modify_Onboarding_TC1484195() throws Exception{ + + //check of version is 2 + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "vProbes_FE.zip"; + String snmpFile = "vprobes-vLB.zip"; + String updatedSnmpFile = "vprobes-vLB-Modified.zip"; + + OnboardingUtils.createVendorLicense(getUser()); + Pair> createVSP = OnboardingUtils.createVSP(vnfFile, filePath, getUser()); + String vspName = createVSP.left; + resourceMetaData.setName(vspName); + Map resourceMeta = createVSP.right; + String vspid = resourceMeta.get("vspId"); + String monitoringId = OnboardingUtils.addVFCArtifacts(filePath, snmpFile, null, vspid, getUser()); + OnboardingUtils.prepareVspForUse(getUser(), vspid); + + String downloadDirectory = getWindowTest().getDownloadDirectory(); + String csarFile = vspid + ".csar"; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUtils.importVSP(createVSP); + + Map artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(downloadDirectory + csarFile); + List vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys){ + resourceMetaData.setVersion("0.1"); + VFCArtifactVerificator.setActualVfcArtifactList(key, resourceMetaData, getUser()); + } + + ResourceGeneralPage.clickSubmitForTestingButton(vspName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + OnboardingUtils.updateVspWithVfcArtifacts(filePath, vspid, updatedSnmpFile, null, monitoringId, getUser()); + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUtils.updateVSP(createVSP); + resourceMetaData.setVersion("1.1"); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, vnfFile); + + Map artifactsFromCsarAfterUpdate = ArtifactFromCsar.getVFCArtifacts(downloadDirectory + csarFile); + List vfcKeysAfterUpdate = artifactsFromCsarAfterUpdate.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeysAfterUpdate){ + verifyVfcInstanceArtifacts(resourceMetaData, null, artifactsFromCsarAfterUpdate, key); + VFCArtifactVerificator.verifyVfcArtifactUpdated(key, resourceMetaData, getUser()); + } + + } + + + + + + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + + private Map> verifyVfcArtifacts(String filepath, String csarFile, + ResourceReqDetails resourceMetaData, RestResponse getResponse) throws Exception { + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts"); + Map> expectedArtifactMap = null; + ExtentTestActions.log(Status.INFO, "Reading artifacts in CSAR file"); + Map artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filepath + csarFile); + List vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys){ + expectedArtifactMap = verifyVfcInstanceArtifacts(resourceMetaData, getResponse, artifactsFromCsar, key); + } + return expectedArtifactMap; + } + + private Map> verifyVfcInstanceArtifacts( + ResourceReqDetails resourceMetaData, RestResponse getResponse, Map artifactsFromCsar, String key) { + + Map> expectedArtifactMap; + Map> vfcDeploymentArtifacts = (Map>)artifactsFromCsar.get(key); + LinkedList deploymentList = vfcDeploymentArtifacts.get(DEPLOYMENT); + LinkedList informationalList = (LinkedList) artifactsFromCsar.get(INFORMATIONAL); + + expectedArtifactMap = new HashMap>(); + if(deploymentList == null){ + expectedArtifactMap.put(DEPLOYMENT_ARTIFACTS, new LinkedList()); + }else{ + expectedArtifactMap.put(DEPLOYMENT_ARTIFACTS, deploymentList); + } + if(informationalList == null){ + expectedArtifactMap.put(ARTIFACTS, new LinkedList()); + }else{ + expectedArtifactMap.put(ARTIFACTS, informationalList); + } + + + VFCArtifactVerificator.verifyVfcArtifacts(resourceMetaData, getUser(), key, expectedArtifactMap, getResponse); + return expectedArtifactMap; + } +} 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 new file mode 100644 index 0000000000..078bc69001 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java @@ -0,0 +1,687 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import java.awt.AWTException; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifactsPlaceholders; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ResourceMetadataEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ToscaArtifactsScreenEnum; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +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.execute.setup.AttFtpClient; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.InputsPage; +import org.openecomp.sdc.ci.tests.pages.PropertiesPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.TesterOperationPage; +import org.openecomp.sdc.ci.tests.pages.ToscaArtifactsPage; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utilities.PropertiesUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +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.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.ci.tests.verificator.VfModuleVerificator; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.SkipException; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + + +public class Vf extends SetupCDTest { + + private String filePath; + @BeforeClass + public void beforeClass(){ + filePath = System.getProperty("filepath"); + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath(); + } + else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + } + } + + @BeforeMethod + public void beforeTest(){ + System.out.println("File repository is : " + filePath); + getExtendTest().log(Status.INFO, "File repository is : " + filePath); + } + + + @Test + public void updateVF() throws Exception { + + // create Resource + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(resourceMetaData, getUser()); + + // update Resource + ResourceReqDetails updatedResource = new ResourceReqDetails(); + updatedResource.setName("ciUpdatedName"); + updatedResource.setDescription("kuku"); + updatedResource.setVendorName("updatedVendor"); + updatedResource.setVendorRelease("updatedRelease"); + updatedResource.setContactId("ab0001"); + updatedResource.setCategories(resourceMetaData.getCategories()); + updatedResource.setVersion("0.1"); + updatedResource.setResourceType(ResourceTypeEnum.VF.getValue()); + List newTags = resourceMetaData.getTags(); + newTags.remove(resourceMetaData.getName()); + newTags.add(updatedResource.getName()); + updatedResource.setTags(newTags); + ResourceUIUtils.updateResource(updatedResource, getUser()); + + VfVerificator.verifyVFMetadataInUI(updatedResource); + VfVerificator.verifyVFUpdated(updatedResource, getUser()); + } + + @Test + public void vfcLinkedToComputeInVfFlow() throws Exception { + String fileName = "vFW_VFC2.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try{ + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(String.format("%s %s", LeftPanelCanvasItems.COMPUTE.getValue() , "1.0")); + CanvasElement computeElement = canvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement cpElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + AssertJUnit.assertNotNull(cpElement); + ServiceVerificator.verifyNumOfComponentInstances(vfMetaData, "0.1", 2, getUser()); + canvasManager.linkElements(cpElement, computeElement); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyLinkCreated(vfMetaData, getUser(), 1); + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + @Test + public void addUpdateDeleteDeploymentArtifactToVfTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List deploymentArtifactList = new ArrayList(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact "+ deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + AssertJUnit.assertTrue("artifact "+ deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + + @Test + public void addUpdateDeleteInformationalArtifact() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(1)); + + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifact.getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact "+ informationalArtifact.getArtifactLabel() + "is not deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + } + + + @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()); + + try{ + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + vfCanvasManager.clickOnCanvaElement(vfcElement); + CompositionPage.showPropertiesAndAttributesTab(); + List properties = CompositionPage.getProperties(); + String propertyValue = "abc123"; + for (int i = 0; i < 2; i++) { + WebElement findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label")); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + + + findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-value")); + AssertJUnit.assertTrue(findElement.getText().equals(propertyValue)); + } + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void changeInstanceVersionTest() throws Exception{ + + if(true){ + throw new SkipException("Open bug 291567"); + } + + ResourceReqDetails atomicResourceMetaData = null; + ResourceReqDetails vfMetaData = null; + CanvasManager vfCanvasManager; + CanvasElement vfcElement = null; + String fileName = "vFW_VFC3.yml"; + try{ + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + + CompositionPage.clickSubmitForTestingButton(vfMetaData.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "1.0"); + + //verfication + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "1.0"); + } + + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + // future removed from ui + @Test(enabled = false) + public void addUpdateDeleteSimplePropertiesToVfTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList){ + PropertiesUIUtils.addNewProperty(prop); + } + AssertJUnit.assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + VfVerificator.verifyPropertiesInUI(propertyList); + PropertiesPage.verifyTotalProperitesField(propertiesCount + propertyList.size()); + + + PropertyTypeEnum prop = propertyList.get(0); + prop.setDescription("updatedDescription"); + prop.setValue("value"); + PropertiesUIUtils.updateProperty(prop); + + PropertiesPage.clickDeletePropertyArtifact(prop.getName()); + AssertJUnit.assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size() - 1, () -> PropertiesPage.getElemenetsFromTable())); + } + + // future removed from ui + @Test(enabled = false) + public void vfcInstancesInputScreenTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + + Map elementsIntancesMap = new HashMap(); + for (LeftPanelCanvasItems element : Arrays.asList(LeftPanelCanvasItems.DATABASE, LeftPanelCanvasItems.BLOCK_STORAGE)){ + CanvasElement elementOnCanvas = vfCanvasManager.createElementOnCanvas(element); + vfCanvasManager.clickOnCanvaElement(elementOnCanvas); + String selectedInstanceName = CompositionPage.getSelectedInstanceName(); + elementsIntancesMap.put(selectedInstanceName, element.getValue()); + } + + CompositionPage.moveToInputsScreen(); + int canvasElementsSize = vfCanvasManager.getCanvasElements().size(); + AssertJUnit.assertTrue("Instances count is not as expected: " + canvasElementsSize, InputsPage.checkElementsCountInTable(canvasElementsSize)); + + for (String element : elementsIntancesMap.keySet()){ + String resourceName = elementsIntancesMap.get(element); + ResourceReqDetails resource = new ResourceReqDetails(); + resource.setName(resourceName); + resource.setVersion("1.0"); + resource.setResourceType(ResourceTypeEnum.VFC.toString()); + RestResponse restResponse = RestCDUtils.getResource(resource, getUser()); + Map propertiesNameTypeJson = ResponseParser.getPropertiesNameType(restResponse); + + List propertyRowsFromTable = InputsPage.getInstancePropertiesList(element); + AssertJUnit.assertTrue("Some properties are missing in table. Instance name is : " + element, propertyRowsFromTable.size() == propertiesNameTypeJson.size()); + VfVerificator.verifyVfInputs(element, propertiesNameTypeJson, propertyRowsFromTable); + + GeneralUIUtils.clickOnElementByText(element); + } + + } + + + @Test + public void addAllInformationalArtifactPlaceholdersInVfTest() throws Exception{ + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + for(InformationalArtifactsPlaceholders informArtifact : InformationalArtifactsPlaceholders.values()){ + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, filePath,"asc_heat 0 2.yaml", informArtifact.getValue()); + } + + AssertJUnit.assertTrue(InformationalArtifactPage.checkElementsCountInTable(InformationalArtifactsPlaceholders.values().length)); + } + + @Test + public void verifyToscaArtifactsExist() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + final int numOfToscaArtifacts = 2; + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + AssertJUnit.assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); + + for(int i = 0; i < numOfToscaArtifacts; i++){ + String typeFromScreen = ToscaArtifactsPage.getArtifactType(i); + AssertJUnit.assertTrue(typeFromScreen.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) || typeFromScreen.equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())); + } + + ToscaArtifactsPage.clickSubmitForTestingButton(vfMetaData.getName()); + VfVerificator.verifyToscaArtifactsInfo(vfMetaData, getUser()); + } + + @Test(enabled=false) + public void testDownload() throws Exception{ +// ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); +// ResourceUIUtils.createResource(vfMetaData, getUser()); +// +// final int numOfToscaArtifacts = 2; +// ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); +// assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); +// GeneralUIUtils.clickOnElementByTestId("download-Tosca Model"); +// System.out.println("download me"); + + AttFtpClient attFtpClient = AttFtpClient.getInstance(); + + File retrieveLastModifiedFileFromFTP = attFtpClient.retrieveLastModifiedFileFromFTP(); + attFtpClient.deleteFilesFromFTPserver(); + } + + @Test + public void vfCertificationTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + String vfName = vfMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + ResourceGeneralPage.clickSubmitForTestingButton(vfName); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfName); + TesterOperationPage.certifyComponent(vfName); + + vfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void deleteVfCheckedoutTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + GeneralPageElements.clickTrashButtonAndConfirm(); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyVfDeleted(vfMetaData, getUser()); + } + + @Test + public void revertVfMetadataTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceReqDetails vfRevertDetails = new ResourceReqDetails(); + vfRevertDetails.setName("ciUpdatedName"); + vfRevertDetails.setDescription("kuku"); + vfRevertDetails.setCategories(vfMetaData.getCategories()); + vfRevertDetails.setVendorName("updatedVendor"); + vfRevertDetails.setVendorRelease("updatedRelease"); + ResourceUIUtils.fillResourceGeneralInformationPage(vfRevertDetails, getUser(), false); + + GeneralPageElements.clickRevertButton(); + + VfVerificator.verifyVFMetadataInUI(vfMetaData); + + } + + @Test + public void addDeploymentArtifactInCompositionScreenTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3","OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className("i-sdc-designer-sidebar-section-content-item-artifact")); + AssertJUnit.assertEquals(1, actualArtifactList.size()); + } + + // future removed from ui + @Test(enabled = false) + public void addPropertyInCompositionScreenTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showPropertiesAndAttributesTab(); + List propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = CompositionPage.getProperties().size(); + for (PropertyTypeEnum prop : propertyList){ + PropertiesUIUtils.addNewProperty(prop); + } + AssertJUnit.assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> CompositionPage.getProperties())); + } + + @Test + public void addDeploymentArtifactAndVerifyInCompositionScreen() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + AssertJUnit.assertTrue(DeploymentArtifactPage.checkElementsCountInTable(1)); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showDeploymentArtifactTab(); + List deploymentArtifactsFromScreen = CompositionPage.getDeploymentArtifacts(); + AssertJUnit.assertTrue(1 == deploymentArtifactsFromScreen.size()); + + String actualArtifactFileName = deploymentArtifactsFromScreen.get(0).getText(); + AssertJUnit.assertTrue("asc_heat-0-2.yaml".equals(actualArtifactFileName)); + } + + @Test + public void checkoutVfTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + + vfMetaData.setVersion("0.2"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + vfMetaData.setVersion("1.1"); + vfMetaData.setUniqueId(null); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + } + + @Test + public void deleteInstanceFromVfCanvas() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + CanvasElement portElement = vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.PORT); + + vfCanvasManager.clickOnCanvaElement(computeElement); + vfCanvasManager.deleteElementFromCanvas(computeElement); + + VfVerificator.verifyNumOfComponentInstances(vfMetaData, 1, getUser()); + } + + @Test + public void changeInstanceNameInVfTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); + + String updatedInstanceName = "updatedName"; + vfCanvasManager.updateElementNameInCanvas(computeElement, updatedInstanceName); + + String actualSelectedInstanceName = CompositionPage.getSelectedInstanceName(); + AssertJUnit.assertTrue(updatedInstanceName.equals(actualSelectedInstanceName)); + } + + + @Test + public void submitVfForTestingWithNonCertifiedAsset() throws Exception{ + String fileName = "vFW_VFC4.yml"; + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + try{ + CompositionPage.clickSubmitForTestingButton(vfMetaData.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void isDisabledAndReadOnlyInCheckin() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createResource(vfMetaData, getUser()); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceMetadataEnum[] fieldsForCheck = {ResourceMetadataEnum.RESOURCE_NAME, + ResourceMetadataEnum.DESCRIPTION, ResourceMetadataEnum.VENDOR_NAME, ResourceMetadataEnum.VENDOR_RELEASE, + ResourceMetadataEnum.CONTACT_ID}; + + for (ResourceMetadataEnum field: fieldsForCheck){ + AssertJUnit.assertTrue(GeneralUIUtils.isElementReadOnly(field.getValue())); + } + + AssertJUnit.assertTrue(GeneralUIUtils.isElementDisabled(ResourceMetadataEnum.CATEGORY.getValue())); + AssertJUnit.assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue())); + } + + @Test + public void exportToscaWithModulePropertiesVFTest() throws AWTException, Exception { + String vnfFile = "2016-042_vmsp_pxmc_30_1607_e2e.zip"; + Pair> vsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + String vspName = vsp.left; + ResourceGeneralPage.clickSubmitForTestingButton(vsp.left); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + VfModuleVerificator.validateSpecificModulePropertiesFromRequest(resource); + } + + @Test + public void exportToscaWithModulePropertiesTemplateCheckVFTest() throws AWTException, Exception { + String vnfFile = "2016-042_vmsp_pxmc_30_1607_e2e.zip"; + OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue()); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + ToscaDefinition toscaDefinition = VfModuleVerificator.getToscaTemplate(latestFilefromDir.getAbsolutePath()); + VfModuleVerificator.validateSpecificModulePropertiesFromFile(toscaDefinition); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java new file mode 100644 index 0000000000..2957379ff8 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java @@ -0,0 +1,380 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.ci.tests.businesslogic.ArtifactBusinessLogic; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.CompositionScreenEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.HeatWithParametersDefinition; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.HomeUtils; +import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +public class VfArtifacts extends SetupCDTest{ + + private String filePath; + private String vnfsRepositoryPath; + private String updatedVnfsRepositoryPath; + private String createdEnvFilePath; + private static final String PARAMETERS = "parameters"; + + @BeforeMethod + public void beforeTest() throws FileNotFoundException{ + filePath = getWindowTest().getDownloadDirectory(); + vnfsRepositoryPath = FileHandling.getVnfRepositoryPath(); +// vnfsRepositoryPath = FileHandling.getFilePath("Old_VNFs"); + updatedVnfsRepositoryPath = vnfsRepositoryPath + "UpdatedVNFs"; + Config config = Utils.getConfig(); + createdEnvFilePath = config.getWindowsDownloadDirectory(); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + + + @DataProvider(name = "heatEnvAndVersion", parallel = false) +// parameters: VSP, updatedVsp, expectedHeatVersion, expectedHeatEnvVersion + public Object[][] provideData() { + + return new Object[][] { + { "2016-043_vsaegw_fdnt_30_1607_e2e.zip", "FDNT_UpdateHeatParams.zip", "2", "1" }, // expected heat version 2 and heatEnv 1 + { "2016-043_vsaegw_fdnt_30_1607_e2e.zip", "FDNT_WithoutEnvFiles.zip", "1", "1" }, // expected heat version 1 and heatEnv 1 + { "2016-014_vlandslide_ldsa_30_1607_e2e.zip", "2016-209_vjsa_vjsa_30_1610_e2e.zip", "1", "0" }, // expected heat version 1 and heatEnv 0 + { "2016-045_vlb_lmsp_30_1607_e2e.zip", "2016-045_vlb_lmsp_30_1607_e2e.zip", "1", "1" }, // expected heat version 1 and heatEnv 1(DE270634) + { "2016-109_mobt_mobt_30_1607_e2e.zip", "2016-109_mobt_mobt_30_1607_e2e_DifferentParams.zip", "2", "1" } // expected heat version 2 and heatEnv 1 + }; + } + +// update first env file and verify parameters value + @Test + public void uploadUpdatedHeatEnv() throws Exception{ + + String vnfFile = "2016-042_vmsp_pxmc_30_1607_e2e.zip"; + File updateEnvFile = null; + Pair> vsp = OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.left; + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + List envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); +// create env file and update it + if(envFilesList.size()>0){ +// select index of env file to be updated + HeatWithParametersDefinition selectedEnvFileToUpdate = envFilesList.get(0); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue()+selectedEnvFileToUpdate.getHeatEnvLabel()); + updateEnvFile = ArtifactUIUtils.uploadCreatedUpdateParametersEnvFile(selectedEnvFileToUpdate, createdEnvFilePath); + ArtifactUIUtils.verifyUpdatedEnvParameters(selectedEnvFileToUpdate, updateEnvFile); + } + else{ + SetupCDTest.getExtendTest().log(Status.INFO, "Resource does not contain HEAT files"); + } + } + +// update all env files and verify parameters value in Deployment Artifact View + @Test + public void uploadUpdatedAllHeatEnv() throws Exception{ + + String vnfFile = "2016-044_vfw_fnat_30_1607_e2e.zip"; + File updateEnvFile = null; + Pair> vsp = OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.left; + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + List envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); + if(envFilesList.size()>0){ + for(HeatWithParametersDefinition selectedEnvFileToUpdate : envFilesList){ + // create env file and update it + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue()+selectedEnvFileToUpdate.getHeatEnvLabel()); + updateEnvFile = ArtifactUIUtils.uploadCreatedUpdateParametersEnvFile(selectedEnvFileToUpdate, createdEnvFilePath); + ArtifactUIUtils.verifyUpdatedEnvParameters(selectedEnvFileToUpdate, updateEnvFile); + } + }else{ + SetupCDTest.getExtendTest().log(Status.INFO, "Resource does not contain HEAT files"); + } + } + +// update all env files and verify parameters value in Composition + @Test + public void uploadUpdatedAllHeatEnvComposition() throws Exception{ + + String vnfFile = "2016-014_vlandslide_ldst_30_1607_e2e.zip"; + File updateEnvFile = null; + Pair> vsp = OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.left; + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + List envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.StepsEnum.COMPOSITION.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB.getValue()); + if(envFilesList.size()>0){ + for(HeatWithParametersDefinition selectedEnvFileToUpdate : envFilesList){ + // create env file and update it + String dataTestId = DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ITEM.getValue()+selectedEnvFileToUpdate.getHeatArtifactDisplayName(); + GeneralUIUtils.hoverOnAreaByTestId(dataTestId); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue()+selectedEnvFileToUpdate.getHeatArtifactDisplayName()); + updateEnvFile = ArtifactUIUtils.uploadCreatedUpdateParametersEnvFile(selectedEnvFileToUpdate, createdEnvFilePath); + ArtifactUIUtils.verifyUpdatedEnvParameters(selectedEnvFileToUpdate, updateEnvFile, dataTestId); + } + }else{ + SetupCDTest.getExtendTest().log(Status.INFO, "Resource does not contain HEAT files"); + } + } + +// expected heat version 1 and heatEnv 0 + @Test + // Download ENV file from VF level Update VSP. + public void downloadEnvFromVFLevelUpdateVSP() throws Throwable { + String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + String updatedVnfFile="2016-014_vlandslide_ldsa_30_1607_e2e.zip"; + String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory(); + Pair> CreatedVsp=OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = CreatedVsp.left; + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUtils.updateVnfAndValidate(vnfsRepositoryPath, CreatedVsp, updatedVnfFile, getUser()); + //get updated vsp env files + Map currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, downloadDirPath); + GeneralUIUtils.findComponentAndClick(vspName); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + List deploymentArtifcatsList = DeploymentArtifactPage.getDeploymentArtifactsNamesWorkSpace(); + + for (int i = 0; i < deploymentArtifcatsList.size(); i++) { + if (DeploymentArtifactPage.getArtifactType(deploymentArtifcatsList.get(i)).equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + DeploymentArtifactPage.clickDownloadEnvArtifact(deploymentArtifcatsList.get(i)); + GeneralUIUtils.ultimateWait(); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(downloadDirPath); + ArtifactUIUtils.compareYamlFilesByPattern(latestFilefromDir, currentZipEnvfiles.get(deploymentArtifcatsList.get(i)), PARAMETERS); + } + } + } + + @Test + // Download ENV file from VF level Work-Space. + public void downloadEnvFromVFLevelWorkSpace() throws AWTException, Exception { + String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory(); + + Pair> vsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + + Map currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.left,downloadDirPath); + GeneralUIUtils.findComponentAndClick(vsp.left); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + List deploymentArtifcatsList = DeploymentArtifactPage.getDeploymentArtifactsNamesWorkSpace(); + + for (int i = 0; i < deploymentArtifcatsList.size(); i++) { + + if (DeploymentArtifactPage.getArtifactType(deploymentArtifcatsList.get(i)).equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + DeploymentArtifactPage.clickDownloadEnvArtifact(deploymentArtifcatsList.get(i)); + GeneralUIUtils.ultimateWait(); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(downloadDirPath); + ArtifactUIUtils.compareYamlFilesByPattern(latestFilefromDir,currentZipEnvfiles.get(deploymentArtifcatsList.get(i)), PARAMETERS); + } + } + } + + @Test + // Download ENV file from VF level Composition. + public void downloadEnvVFLevelComposition() throws AWTException, Exception { + + String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory(); + String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + + Pair> vsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + Map currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.left,downloadDirPath); + GeneralUIUtils.findComponentAndClick(vsp.left); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.clickOnTabTestID(CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB); + List deploymentArtifcatsList = CompositionPage.getCompositionEnvArtifacts(); + + for (int i = 0; i < deploymentArtifcatsList.size(); i++) { + String fileName = GeneralUIUtils.getDataTestIdAttributeValue(deploymentArtifcatsList.get(i)).replace(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ENV.getValue(), ""); + if (GeneralUIUtils.isElementVisibleByTestId(GeneralUIUtils.getDataTestIdAttributeValue(deploymentArtifcatsList.get(i)))) { + CompositionPage.clickDownloadEnvArtifactComposition(fileName).click(); + GeneralUIUtils.ultimateWait(); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(downloadDirPath); + ArtifactUIUtils.compareYamlFilesByPattern(latestFilefromDir,currentZipEnvfiles.get(fileName), PARAMETERS); + } + } + } + + @Test + // Download ENV file from VF level Update parameters in UI. + public void downloadEnvVFLevelUpdateParameters() throws AWTException, Exception { + + String vnfFile = "2016-044_vfw_fcgi_30_1607_e2e.zip"; + String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory(); + Pair> CreatedVsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser()); + + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, CreatedVsp.left, "0.1"); + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + List envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); + + for (int i = 0; i < envFilesList.size(); i++) { + String artifactName = envFilesList.get(i).getHeatArtifactDisplayName(); + if (envFilesList.get(i).getHeatArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + ExtentTestActions.log(Status.INFO, String.format("Opening the edit/view artifact parameters form of %s resource...", vnfFile)); + DeploymentArtifactPage.clickEditEnvArtifact(envFilesList.get(i).getHeatArtifactDisplayName()); + + ExtentTestActions.log(Status.INFO, String.format("Going To locating all artifact parameters from UI of %s artifact...", artifactName)); + Map dataToWriteInUI = ArtifactUIUtils.getDataToWriteInUI(envFilesList.get(i).getHeatParameterDefinition()); + Map data = dataToWriteInUI; + ExtentTestActions.log(Status.INFO, String.format("Success to locate all artifact parameters from UI of %s artifact...", artifactName)); + + List listToSearchEnvParametersInUI = envFilesList.get(i).getHeatParameterDefinition(); + fillHeatEnvParametersInUi(data, listToSearchEnvParametersInUI); + + DeploymentArtifactPage.clickSaveEnvParameters(); + GeneralUIUtils.waitForLoader(); + ExtentTestActions.log(Status.INFO, String.format("Going to get the %s updated resource ...", CreatedVsp.left)); + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, CreatedVsp.left, "0.1"); + deploymentArtifacts = resource.getDeploymentArtifacts(); + Map> envFilesListupdated = new HashMap<>(); + ExtentTestActions.log(Status.INFO, String.format("Mapping the %s artifact parameters ...", artifactName)); + envFilesListupdated.put(artifactName,ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts)); + List heatEnvUpdatedParameters=envFilesListupdated.get(artifactName); + DeploymentArtifactPage. clickDownloadEnvArtifact(artifactName); + + Map mapExpectedProperties = new HashMap<>(); + for (HeatParameterDataDefinition param : heatEnvUpdatedParameters.get(i).getHeatParameterDefinition()) { + mapExpectedProperties.put(param.getName(), ArtifactUIUtils.getValue(param)); + } + ArtifactUIUtils.compareYamlParametersByPattern(mapExpectedProperties, FileHandling.getLastModifiedFileFromDir(downloadDirPath), PARAMETERS); + } + } + } + + + @Test + public void checkDefaultCreatedEnvArtifacts() throws Exception{ + String vnfFile = "2016-017_vixia_ixla_30_1607_e2e.zip"; + Pair> vsp = OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.left; + Map generatedEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath); + HomeUtils.findComponentAndClick(vspName); + GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_ARTIFACT); + for(Entry envFileEntry : generatedEnvFileList.entrySet()){ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue()+envFileEntry.getKey()); + ArtifactUIUtils.compareYamlFilesByPattern(envFileEntry.getValue(), FileHandling.getLastModifiedFileFromDir(), PARAMETERS); + ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "0", ArtifactTypeEnum.HEAT_ENV); + ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "1", ArtifactTypeEnum.HEAT); + } + } + +// ------------------------------------------------------------------------------- + @Test(dataProvider = "heatEnvAndVersion") + public void checkDefaultCreatedEnvArtifactsAfterVspUpdate(String vnfFile, String updatedVnfFile, String expectedHeatVersion, String expectedHeatEnvVersion) throws Throwable{ + String stringForLog = String.format("%s:%s:%s:%s", vnfFile, updatedVnfFile, expectedHeatVersion, expectedHeatEnvVersion); + setLog(stringForLog); + + Pair> vsp = OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.left; + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUtils.updateVnfAndValidate(updatedVnfsRepositoryPath, vsp, updatedVnfFile, getUser()); + Map generatedUpdatedEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath); + HomeUtils.findComponentAndClick(vspName); + GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_ARTIFACT); + for(Entry envFileEntry : generatedUpdatedEnvFileList.entrySet()){ +// TODO test will pass on case all objects on deployment view are visible + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue()+envFileEntry.getKey()); + ArtifactUIUtils.compareYamlFilesByPattern(envFileEntry.getValue(), FileHandling.getLastModifiedFileFromDir(), PARAMETERS); + ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), expectedHeatEnvVersion, ArtifactTypeEnum.HEAT_ENV); + ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), expectedHeatVersion, ArtifactTypeEnum.HEAT); + } + } + +// expected heat version 1 and heatEnv 2 + @Test + public void checkDefaultCreatedEnvArtifactsVspUpdatedWithSameVspTwice() throws Throwable{ + String vnfFile = "2016-044_vfw_fcgi_30_1607_e2e.zip"; + String updatedVnfFile = "2016-044_vfw_fcgi_30_1607_e2e.zip"; + Pair> vsp = OnboardingUtils.onboardAndValidate(vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.left; + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUtils.updateVnfAndValidate(vnfsRepositoryPath, vsp, updatedVnfFile, getUser()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUtils.updateVnfAndValidate(vnfsRepositoryPath, vsp, updatedVnfFile, getUser()); + Map generatedUpdatedSecondTimeEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath); + HomeUtils.findComponentAndClick(vspName); + GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_ARTIFACT); + for(Entry envFileEntry : generatedUpdatedSecondTimeEnvFileList.entrySet()){ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue()+envFileEntry.getKey()); + ArtifactUIUtils.compareYamlFilesByPattern(envFileEntry.getValue(), FileHandling.getLastModifiedFileFromDir(), PARAMETERS); + ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "2", ArtifactTypeEnum.HEAT_ENV); + ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "1", ArtifactTypeEnum.HEAT); + } + } + + + public void downloadFile(Entry envFileEntry) { + int fileCountBefore = FileHandling.getFileCountFromDefaulDownloadDirectory(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue()+envFileEntry.getKey()); + int fileCountAfter = FileHandling.getFileCountFromDefaulDownloadDirectory(); + assertTrue("Downloaded file is missing", (fileCountAfter - fileCountBefore) == 1 ); + } + + public static void fillHeatEnvParametersInUi(Map data,List listToSearchEnvParametersInUI) { + ExtentTestActions.log(Status.INFO, String.format("Going to search parameters in UI and insert new current value to each parameter in UI...")); + + for (HeatParameterDataDefinition paramDefinition : listToSearchEnvParametersInUI){ + DeploymentArtifactPage.searchBoxEnv(paramDefinition.getName()); + WebElement currenValueField=GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.EnvParameterView.ENV_CURRENT_VALUE.getValue()+paramDefinition.getName()); + currenValueField.clear(); + currenValueField.sendKeys(data.get(paramDefinition.getName()).toString()); + GeneralUIUtils.ultimateWait(); + DeploymentArtifactPage.clearSearchBoxEnv(); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java new file mode 100644 index 0000000000..42c43f3ac8 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java @@ -0,0 +1,862 @@ +/*- + * ============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.ci.tests.execute.sanity; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.Dashboard; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.ArtifactUIUtils; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.Test; + + +public class VfDeploymentInformationalArtifacts extends SetupCDTest { + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // START US824719 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // US824719 - Import VSP - VF informational artifacts + // TC1434241 - Import VF Artifacts - Deployment Artifacts - One Artifact, One Type + @Test + public void importVfArtifactsDeploymentArtifactsOneArtifactOneType() throws Exception { + String fileName = "TC1434241.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434245 - Import VF Artifacts - Deployment Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfArtifactsDeploymentArtifactsMultipleArtifactsMultipleTypes() throws Exception { + String fileName = "TC1434245.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1")); + + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName,folder, deploymentArtifacts, null); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434247 - Import VF Artifacts - Informational Artifacts - One Artifact, One Type + @Test + public void importVfArtifactsInformationalArtifactsOneArtifactOneType() throws Exception { + String fileName = "TC1434247.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434248 - Import VF Artifacts - Informational Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfArtifactsInformationalArtifactsMultipleArtifactsMultipleTypes() throws Exception { + String fileName = "TC1434248.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434249 - Import VF Artifacts - Deployment and Informational Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfArtifactsDeploymentAndInformationalArtifactsMultipleArtifactsMultipleTypes() throws Exception { + String fileName = "TC1434249.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // TODO: there is defect in flow: "Updated button enabled for artifact in invalid type folder" + // TODO: re-check it after defect fix + // US824719 - Import VSP - VF informational artifacts + // TC1438310 - Import VF Artifacts - Deployment Artifacts - Artifact Type Invalid + @Test + public void importVFArtifactsDeploymentArtifactsArtifactTypeInvalid() throws Exception { + String fileName = "DeploymentArtifactWithInvalidType.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1438311 - Import VF Artifacts - Informational Artifacts - Artifact Type Invalid + @Test + public void importVfArtifactsInformationalArtifactsArtifactTypeInvalid() throws Exception { + String fileName = "InformationArtifactWithInvalidType.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1438231 - Import VF Artifacts - Deployment Artifacts - Artifact Name To Long + @Test + public void importVfArtifactsDeploymentArtifactsArtifactNameToLong() throws Exception { + String folder = "US825779"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String fileName = "DeploymentArtifactWithLongName.csar"; + + importVfFromCsar(resourceMetaData, folder, fileName, getUser()); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1438232 - Import VF Artifacts - Informational Artifacts - Artifact Name To Long + // TODO: make informational artifact name longer then 255 + // TODO: windows/linux not allowed it + @Test(enabled=false) + public void importVfArtifactsInformationalArtifactsArtifactNameToLong() throws Exception { + String folder ="US825779"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String fileName = "InformationArtifactWithLongName.csar"; + + importVfFromCsar(resourceMetaData, folder, fileName, getUser()); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // END US824719 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // START US825779 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443736 - Update With One New Deployment Artifact + @Test + public void updateWithOneNewDeploymentArtifact() throws Exception { + String fileName = "ImportTC1443736.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443736.csar"; + deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, null, null, null); + } + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443737 - Update With One Removed Deployment Artifact + @Test + public void updateWithOneRemovedDeploymentArtifact() throws Exception { + String fileName = "ImportTC1443737.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"); + deploymentArtifacts.add(artifactInfo); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443737.csar"; + deploymentArtifacts.remove(artifactInfo); + + List deploymentArtifactsNotExist = new ArrayList(); + deploymentArtifactsNotExist.add(artifactInfo); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, null, deploymentArtifactsNotExist, null); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443738 - Update With One New Version Deployment Artifact + @Test + public void updateWithOneNewVersionDeploymentArtifact() throws Exception { + String fileName = "ImportTC1443738.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"); + deploymentArtifacts.add(artifactInfo); + + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443738.csar"; + artifactInfo.setArtifactVersion("2"); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, null, null, null); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443887 - Update With One New Informational Artifact + @Test + public void updateWithOneNewInformationalArtifact() throws Exception { + String fileName = "ImportTC1443887.csar"; + String folder ="US825779"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443887.csar"; + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, null, null); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443888 - Update With One Removed Informational Artifact + @Test + public void updateWithOneRemovedInformationalArtifact() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1443888.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"); + informationalArtifacts.add(artifactInfo); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443888.csar"; + + informationalArtifacts.remove(artifactInfo); + + List informationalArtifactNotExist = new ArrayList(); + informationalArtifactNotExist.add(artifactInfo); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, null, informationalArtifactNotExist); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443890 - Update With One New Artifact Version Informational Artifact + @Test + public void updateWithOneNewArtifactVersionInformationalArtifact() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1443890.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"); + informationalArtifacts.add(artifactInfo); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443890.csar"; + artifactInfo.setArtifactVersion("2"); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, null, null); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443893 - Update CSAR With Same Artifacts As Imported + @Test + public void updateCSARWithSameArtifactsAsImported() throws Exception { + String folder ="US825779"; + String fileName = "ImportUpdateTC1443893.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "ImportUpdateTC1443893.csar"; + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, null, null); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443954 - Update With Multiple Changes In Deployment And Informational Artifacts + @Test + public void updateWithMultipleChangesInDeploymentAndInformationalArtifacts() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1443954.csar"; + + ArtifactInfo deploymentHeat1 = new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"); + ArtifactInfo deploymentHeat2 = new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"); + ArtifactInfo deploymentHeat3 = new ArtifactInfo(null, "heatartifactname3.yaml", null, "heatartifactname3", ArtifactTypeEnum.HEAT.getType(), "1"); + + ArtifactInfo deploymentHeatVol1 = new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"); + ArtifactInfo deploymentHeatVol2 = new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"); + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(deploymentHeat1); + deploymentArtifacts.add(deploymentHeat2); + deploymentArtifacts.add(deploymentHeat3); + deploymentArtifacts.add(deploymentHeatVol1); + deploymentArtifacts.add(deploymentHeatVol2); + + ArtifactInfo infoGuide1 = new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"); + ArtifactInfo infoGuide2 = new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"); + + ArtifactInfo infoOther1 = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"); + ArtifactInfo infoOther2 = new ArtifactInfo(null, "artifactname2.txt", null, "artifactname2", ArtifactTypeEnum.OTHER.getType(), "1"); + ArtifactInfo infoOther3 = new ArtifactInfo(null, "artifactname3.txt", null, "artifactname3", ArtifactTypeEnum.OTHER.getType(), "1"); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(infoGuide1); + informationalArtifacts.add(infoGuide2); + informationalArtifacts.add(infoOther1); + informationalArtifacts.add(infoOther2); + informationalArtifacts.add(infoOther3); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443954.csar"; + + List informationalArtifactsNotExist = new ArrayList(); + List deploymentArtifactsNotExist = new ArrayList(); + + // Changes in deployment artifacts + deploymentArtifactsNotExist.add(deploymentHeat1); + deploymentArtifactsNotExist.add(deploymentHeat2); + deploymentArtifacts.remove(deploymentHeat1); + deploymentArtifacts.remove(deploymentHeat2); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname4.yaml", null, "heatartifactname4", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname5.yaml", null, "heatartifactname5", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentHeatVol1.setArtifactVersion("2"); + deploymentHeatVol2.setArtifactVersion("2"); + + // Changes in informational artifacts + infoGuide1.setArtifactVersion("2"); + infoOther1.setArtifactVersion("2"); + informationalArtifactsNotExist.add(infoGuide2); + informationalArtifactsNotExist.add(infoOther2); + informationalArtifacts.remove(infoGuide2); + informationalArtifacts.remove(infoOther2); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact3.yml", null, "GuideInfoArtifact3", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname4.txt", null, "artifactname4", ArtifactTypeEnum.OTHER.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, deploymentArtifactsNotExist, informationalArtifactsNotExist); + } + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444206 - Update With Existed Deployment Artifact By Artifact With Different Type + @Test + public void updateWithExistedDeploymentArtifactByArtifactWithDifferentType() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1444206.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444206.csar"; + String filePath = FileHandling.getFilePath(folder); ; + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444207 - Update With Existed Informational Artifact By Artifact With Different Type + @Test + public void updateWithExistedInformationalArtifactByArtifactWithDifferentType() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1444207.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444207.csar"; + String filePath = FileHandling.getFilePath(folder); ; + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444208 - Update With Existed Informational Artifact By Deployment Artifact With Different Type + @Test + public void updateWithExistedInformationalArtifactByDeploymentArtifactWithDifferentType() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1444208.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444208.csar"; + String filePath = FileHandling.getFilePath(folder); ; + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444520 - Update Deployment Artifact With Name To Long + @Test + public void updateDeploymentArtifactWithNameToLong() throws Exception { + String folder ="US825779"; + + String fileName = "ImportTC1444520.csar"; + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, null, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444520.csar"; + String filePath = FileHandling.getFilePath(folder); ; + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444521 - Update Informational Artifact With Name To Long + @Test + public void updateInformationalArtifactWithNameToLong() throws Exception { + + String folder = "US825779"; + String fileName = "ImportTC1444521.csar"; + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, null, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444521.csar"; + String filePath = FileHandling.getFilePath(folder); ; + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + + // TODO: only after below TODO's it complete test + // TODO: verify that if delete/edit button need to be disabled then check that there is no such buttons + // TODO: in composition & artifact pages + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444530 - Update Deployment Artifact With Invalid Type + @Test + public void updateDeploymentArtifactWithInvalidType() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1444530.csar"; + + List deploymentArtifacts = new ArrayList(); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444530.csar"; + deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, null, null, null); + } + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444531 - Update Informational Artifact With Invalid Type + @Test + public void updateInformationalArtifactWithInvalidType() throws Exception { + String folder ="US825779"; + String fileName = "ImportTC1444531.csar"; + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, null, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444531.csar"; + + List informationalArtifacts = new ArrayList(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, null, informationalArtifacts, null, null); + } + + + @Test + public void importValidInformationalArtifactInInvalidFolerTest_TC1438313() throws Exception{ + String fileName = "ValidArtifactNameInInvalidFolder.csar"; + String folder = "US824719"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + @Test + public void updateValidInformationalArtifactInInvalidFolerTest_TC1444533() throws Exception{ + String fileName = "ImportTC1444533.csar"; + String folder = "US824719"; + String filePath = FileHandling.getFilePath(folder); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + String updatedCsarFileName = "UpdateTC1444533.csar"; + + List deploymentArtifacts = new ArrayList(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, updatedCsarFileName, deploymentArtifacts, null, null, null); + } + + + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // END US825779 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + + public void updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(String folder, String fileName, + List deploymentArtifacts, List informationalArtifacts, + List deploymentArtifactsNotExist, List informationalArtifactsNotExist) throws Exception { + String filePath = FileHandling.getFilePath(folder); + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + validateDeploymentArtifactPage(deploymentArtifacts, null); + validateInformationalArtifactPage(informationalArtifacts, null); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + validateDeploymentArtifactInComposition(deploymentArtifacts, null); + validateInformationalArtifactInComposition(informationalArtifacts, null); + + } + + + public void importVfFromCsar(ResourceReqDetails resourceMetaData, String folder, String fileName, User user) { + String filePath = FileHandling.getFilePath(folder); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + // Insert file to the browse dialog + WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + browseWebElement.sendKeys(filePath + fileName); + + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + ResourceUIUtils.fillResourceGeneralInformationPage(resourceMetaData, getUser(), true); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + } + + + + + public void importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(String fileName, String folder, List deploymentArtifacts, List informationalArtifacts) throws Exception { + String filePath = FileHandling.getFilePath(folder); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + validateDeploymentArtifactPage(deploymentArtifacts, null); + validateInformationalArtifactPage(informationalArtifacts, null); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + validateDeploymentArtifactInComposition(deploymentArtifacts, null); + validateInformationalArtifactInComposition(informationalArtifacts, null); + } + + public void validateInformationalArtifactInComposition(List informationalArtifacts, List informationalArtifactsNotExist) throws Exception { + CompositionPage.showInformationArtifactTab(); + // Composition informational + if(informationalArtifacts != null && informationalArtifacts.size() > 0) { + validateEachArtifactOnCompositionRightMenuInformationPage(informationalArtifacts); + } + if(informationalArtifactsNotExist != null && informationalArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistOnCompositionRightMenuInformationPage(informationalArtifactsNotExist); + } + } + + public void validateDeploymentArtifactInComposition(List deploymentArtifacts, List deploymentArtifactsNotExist) throws Exception { + CompositionPage.showDeploymentArtifactTab(); + // Composition deployment + if(deploymentArtifacts != null && deploymentArtifacts.size() > 0) { + validateEachArtifactOnCompositionRightMenuDeploymentPage(deploymentArtifacts); + } + if(deploymentArtifactsNotExist != null && deploymentArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistOnCompositionRightMenuDeploymentPage(deploymentArtifactsNotExist); + } + } + + public void validateInformationalArtifactPage(List informationalArtifacts, List informationalArtifactsNotExist) { + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + // Informational page + if(informationalArtifacts != null && informationalArtifacts.size() > 0) { + validateEachArtifactInformationPage(informationalArtifacts); + } + if(informationalArtifactsNotExist != null && informationalArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistInformationPage(informationalArtifactsNotExist); + } + } + + public void validateDeploymentArtifactPage(List deploymentArtifacts, List deploymentArtifactsNotExist) { + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + // Deployment page + if(deploymentArtifacts != null && deploymentArtifacts.size() > 0) { + validateEachArtifactOnDeploymentPage(deploymentArtifacts); + } + if(deploymentArtifactsNotExist != null && deploymentArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistOnDeploymentPage(deploymentArtifactsNotExist); + } + } + + // TODO: add validation that if not editable / deleteable then button should not appear + public void validateEachArtifactOnDeploymentPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + String type = artifact.getArtifactType(); + String label = artifact.getArtifactLabel(); + String version = artifact.getArtifactVersion(); + + if (type.equals(ArtifactTypeEnum.HEAT.getType()) || type.equals(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equals(ArtifactTypeEnum.HEAT_NET.getType())){ + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(label, null, version, type, true, false, false, true); + } + else{ + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(label, null, version, type, true, true, true, false); + } + } + } + + public void validateEachArtifactNotExistOnDeploymentPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + public void validateEachArtifactInformationPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(artifact.getArtifactLabel(), null, artifact.getArtifactVersion(), artifact.getArtifactType(), true, true, true, false); + } + } + + public void validateEachArtifactNotExistInformationPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + public void validateEachArtifactOnCompositionRightMenuDeploymentPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + + String type = artifact.getArtifactType(); + String label = artifact.getArtifactLabel(); + String filename = artifact.getFilename(); + + if (type.equals(ArtifactTypeEnum.HEAT.getType()) || type.equals(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equals(ArtifactTypeEnum.HEAT_NET.getType())){ + ArtifactUIUtils.validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(filename, label, false, true, true, false); + } + else{ + ArtifactUIUtils.validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(filename, label, true, false, true, true); + } + } + } + + public void validateEachArtifactNotExistOnCompositionRightMenuDeploymentPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + // TODO: there is defect in this flow + // TODO: change isEditable to false when defect fix + public void validateEachArtifactOnCompositionRightMenuInformationPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + ArtifactUIUtils.validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(artifact.getFilename(), artifact.getArtifactLabel(), true, false, true, true); + } + } + + public void validateEachArtifactNotExistOnCompositionRightMenuInformationPage(List artifactInfoList) { + for(ArtifactInfo artifact: artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ArtifactsCorrelationManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ArtifactsCorrelationManager.java new file mode 100644 index 0000000000..7f67978aea --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ArtifactsCorrelationManager.java @@ -0,0 +1,72 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map.Entry; +import java.util.Set; + +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; + +public class ArtifactsCorrelationManager { + + private static HashMap> vNFArtifactsCorrelationMap = new HashMap>(); + private static HashMap>> serviceVNFCorrelationMap = new HashMap>>(); + + public static void addVNFartifactDetails(String vspName, + LinkedList deploymentArtifacts) { + + vNFArtifactsCorrelationMap.put(vspName, deploymentArtifacts); + + + } + + public static Entry> getVNFartifactDetails(String vnfName){ + + + Set>> entrySet = vNFArtifactsCorrelationMap.entrySet(); + for (Entry> entry : entrySet) { + String key = entry.getKey(); + if (key.equals(vnfName)) { + return entry; + } + + } + return null; + + } + + + public static void addVNFtoServiceArtifactCorrelation(String service, String vnfName){ + + serviceVNFCorrelationMap.put(service, getVNFartifactDetails(vnfName)); + + } + + public static Set>>> getServiceArtifactCorrelationMap(String service){ + + return serviceVNFCorrelationMap.entrySet(); + + } + +} + diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/AttFtpClient.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/AttFtpClient.java new file mode 100644 index 0000000000..1d7c4ae554 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/AttFtpClient.java @@ -0,0 +1,221 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.io.output.ByteArrayOutputStream; +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +public class AttFtpClient { + + private static final AttFtpClient instance = new AttFtpClient(); + + public static AttFtpClient getInstance() { + return instance; + } + + private FTPClient apacheFtpClient; + + private AttFtpClient() { + apacheFtpClient = new FTPClient(); + }; + + + public void init(String server, int port, String user, String pass) { + + try { + apacheFtpClient.connect(server, port); + showServerReply(apacheFtpClient); + + + int replyCode = apacheFtpClient.getReplyCode(); + if (!FTPReply.isPositiveCompletion(replyCode)) { + System.out.println("Connect failed"); + return; + } + + boolean success = apacheFtpClient.login(user, pass); + showServerReply(apacheFtpClient); + + if (!success) { + System.out.println("Could not login to the server"); + return; + } + +// else{ +// apacheFtpClient.enterLocalPassiveMode(); +// apacheFtpClient.setFileType(FTP.BINARY_FILE_TYPE); +// } + } catch (IOException ex) { + System.out.println("Oops! Something wrong happened"); + ex.printStackTrace(); + } + + } + + public File retrieveLastModifiedFileFromFTP() throws IOException { + FTPFile[] files1 = retrieveListOfFile(); + + // sort list by TimeStamp + List sorted = Arrays.asList(files1).stream() + .sorted((e1, e2) -> e1.getTimestamp().compareTo(e2.getTimestamp())).collect(Collectors.toList()); + printFileDetailsList(sorted); + + // retrieve file from FTP + FTPFile ftpFile = sorted.get(sorted.size() - 1); + + return retrieveFileFromFTP(ftpFile); + + } + + public FTPFile[] retrieveListOfFile() throws IOException { + // Lists files and directories + FTPFile[] files = apacheFtpClient.listFiles(""); + + printNames(files); + return files; + } + + public File retrieveFileFromFTP(FTPFile ftpFile) throws IOException { + + File downloadFile1 = new File("tmp"); + OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1)); + boolean success = apacheFtpClient.retrieveFile(ftpFile.getName(), outputStream1); + outputStream1.close(); + + if (success) { + System.out.println("File #1 has been downloaded successfully."); + } + + + return downloadFile1; + + } + + public void deleteFilesFromFTPserver() throws IOException { + FTPFile[] files = retrieveListOfFile(); + deleteFiles(files); + } + + public void terminateClient() throws IOException { + + String status = apacheFtpClient.getStatus(); + + // logs out and disconnects from server + try { + if (apacheFtpClient.isConnected()) { + apacheFtpClient.logout(); + apacheFtpClient.disconnect(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private void printFileDetailsList(List list) { + DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + for (FTPFile ftpFile : list) { + + String details = ftpFile.getName(); + if (ftpFile.isDirectory()) { + details = "[" + details + "]"; + } + details += "\t\t" + ftpFile.getSize(); + details += "\t\t" + dateFormater.format(ftpFile.getTimestamp().getTime()); + + System.out.println(details); + } + } + + private void printNames(FTPFile[] files) { + if (files != null && files.length > 0) { + for (FTPFile aFile : files) { + System.out.println(aFile); + } + } + } + + private void showServerReply(FTPClient ftpClient) { + String[] replies = ftpClient.getReplyStrings(); + if (replies != null && replies.length > 0) { + for (String aReply : replies) { + System.out.println("SERVER: " + aReply); + } + } + } + + public class LastModifiedComparator implements Comparator { + + public int compare(FTPFile f1, FTPFile f2) { + return f1.getTimestamp().compareTo(f2.getTimestamp()); + } + } + + public FTPFile getMaxLastModified(FTPFile[] ftpFiles) { + return Collections.max(Arrays.asList(ftpFiles), new LastModifiedComparator()); + } + + public static void displayFiles(File[] files) { + for (File file : files) { + System.out.printf("File: %-20s Last Modified:" + new Date(file.lastModified()) + "\n", file.getName()); + } + } + + public void deleteFiles(FTPFile[] files) { + + for (FTPFile file : files) { + + boolean deleted = false; + try { + deleted = apacheFtpClient.deleteFile(file.getName()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if (deleted) { + System.out.println("The file was deleted successfully."); + } else { + System.out.println("Could not delete the  file, it may not exist."); + } + } + + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java new file mode 100644 index 0000000000..7d0d77acfa --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java @@ -0,0 +1,125 @@ +/*- + * ============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.ci.tests.execute.setup; + + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; + + +public class DriverFactory { + + private static ThreadLocal driverThread; + private static List webDriverThreadPool = Collections.synchronizedList(new ArrayList()); + private static Config config; + + public DriverFactory() { + try { + config = Utils.getConfig(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + @BeforeSuite(alwaysRun = true) + public static void instantiateDriverObject() { + + + File basePath = new File(FileHandling.getBasePath()); + File[] listFiles = basePath.listFiles(new FilenameFilter() { + + @Override + public boolean accept(File basePath, String name) { + return name.startsWith(WebDriverThread.AUTOMATION_DOWNLOAD_DIR); + } + }); + Arrays.asList(listFiles).forEach(e -> FileHandling.deleteDirectory(e.getAbsolutePath())); + + + + driverThread = new ThreadLocal() { + @Override + protected WebDriverThread initialValue() { + WebDriverThread webDriverThread = new WebDriverThread(config); + webDriverThreadPool.add(webDriverThread); + return webDriverThread; + } + }; + } + + public static WebDriver getDriver() throws Exception { + return driverThread.get().getDriver(); + } + + public static FirefoxProfile getDriverFirefoxProfile() throws Exception { + return driverThread.get().getFirefoxProfile(); + } + + @AfterSuite(alwaysRun = true) + public static void quitDriverAfterSuite() throws Exception { + for (WebDriverThread webDriverThread : webDriverThreadPool) { + if (webDriverThread.getDriver() != null) + webDriverThread.quitDriver(); + } + deleteDownloadDirs(); + } + + private static void deleteDownloadDirs() throws IOException { +// System.gc(); + HashMap windowMap = WindowTestManager.getWholeMap(); + for (WindowTest win : windowMap.values()){ + String downloadDirectory = win.getDownloadDirectory(); + FileUtils.deleteDirectory(new File(downloadDirectory)); + } + } + + public static void quitDriver() throws Exception{ + driverThread.get().quitDriver(); + driverThread.remove(); + WindowTestManager.removeWindowTest(); + } + + public static Config getConfig() { + return config; + } + + public static void setConfig(Config config) { + DriverFactory.config = config; + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentManager.java new file mode 100644 index 0000000000..09dcad7c36 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentManager.java @@ -0,0 +1,169 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.io.File; + +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils; +import org.testng.ITestContext; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.reporter.ExtentHtmlReporter; +import com.aventstack.extentreports.reporter.ExtentXReporter; +import com.aventstack.extentreports.reporter.configuration.Protocol; +import com.aventstack.extentreports.reporter.configuration.Theme; + +public class ExtentManager { + + private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; + private static ExtentReports extent; + private static ExtentHtmlReporter htmlReporter; + private static ExtentXReporter extentxReporter; + private static final String icon = "$(document).ready(function() {" +"\n"+ + "$('.brand-logo').html('').prepend(\"\").width(\"120px\").css(\"float\",\"left\").css(\"padding-left\",\"0\");$('.report-name').css(\"font-weight\",\"bold\");"+"\n"+ +// "$('.logo-content' ).remove();"+"\n"+ +// "$('#slide-out li:first-child').on('click', function(){ $('#charts-row').hide() }) ; $('#slide-out li:last-child').on('click', function(){ $('#charts-row').show() });"+"\n"+ +// "$('.charts div:nth-child(2)').remove();"+"\n"+ + "})"; + + public enum suiteNameXml { + + TESTNG_FAILED_XML_NAME("testng-failed.xml"); + + suiteNameXml(String value) { + this.value = value; + } + + private String value; + + public String getValue() { + return value; + } + + } + + public synchronized static ExtentReports setReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception { + String dbIp = DriverFactory.getConfig().getReportDBhost(); + int dbPort = DriverFactory.getConfig().getReportDBport(); + + if (extent == null) { + extentxReporter = new ExtentXReporter(dbIp, dbPort); + extent = new ExtentReports(); + initAndSetExtentHtmlReporter(filePath, htmlFile, isAppend); + + if(extentxReporter.config().getReportObjectId() != null){ + setExtentXReporter(isAppend); + }else{ + extentxReporter.stop(); + } + } + return extent; + } + + public synchronized static void setExtentXReporter(Boolean isAppend){ + extentxReporter.setAppendExisting(isAppend); + extent.attachReporter(extentxReporter); + } + + public synchronized static void initAndSetExtentHtmlReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception{ + htmlReporter = new ExtentHtmlReporter(filePath + htmlFile); + setConfiguration(htmlReporter); + htmlReporter.setAppendExisting(isAppend); + extent.attachReporter(htmlReporter); + } + + public synchronized static ExtentReports getReporter() { + return extent; + } + + public static void initReporter(String filepath, String htmlFile, ITestContext context) throws Exception { + + String onboardVersion = AutomationUtils.getOnboardVersion(); + String osVersion = AutomationUtils.getOSVersion(); + Config config = Utils.getConfig(); + String envData = config.getUrl(); + String suiteName = getSuiteName(context); + + if(suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())){ + if (config.getUseBrowserMobProxy()) + setTrafficCaptue(config); + + setReporter(filepath, htmlFile, true); + String suiteNameFromVersionInfoFile = FileHandling.getKeyByValueFromPropertyFormatFile(filepath + VERSIONS_INFO_FILE_NAME, "suiteName"); + reporterDataDefinition(onboardVersion, osVersion, envData, suiteNameFromVersionInfoFile); + }else{ + FileHandling.deleteDirectory(SetupCDTest.getReportFolder()); + FileHandling.createDirectory(filepath); + setReporter(filepath, htmlFile, false); + reporterDataDefinition(onboardVersion, osVersion, envData, suiteName); + AutomationUtils.createVersionsInfoFile(filepath + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData, suiteName); + } + + } + + public static void reporterDataDefinition(String onboardVersion, String osVersion, String envData, String suiteNameFromVersionInfoFile) throws Exception { + extent.setSystemInfo("Onboard Version", onboardVersion); + extent.setSystemInfo("OS Version", osVersion); + extent.setSystemInfo("Host Name Address", RestCDUtils.getExecutionHostAddress()); + extent.setSystemInfo("ExecutedOn", envData); + extent.setSystemInfo("SuiteName", suiteNameFromVersionInfoFile); + } + + public static String getSuiteName(ITestContext context) { + String suitePath = context.getSuite().getXmlSuite().getFileName(); + if(suitePath != null){ + File file = new File(suitePath); + String suiteName = file.getName(); + return suiteName; + } + return null; + } + + public synchronized static ExtentHtmlReporter setConfiguration(ExtentHtmlReporter htmlReporter) throws Exception { + + htmlReporter.config().setTheme(Theme.STANDARD); + htmlReporter.config().setEncoding("UTF-8"); + htmlReporter.config().setProtocol(Protocol.HTTPS); + htmlReporter.config().setDocumentTitle("SDC Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(true); +// htmlReporter.config().setReportName(AutomationUtils.getATTVersion()); + htmlReporter.config().setReportName("SDC Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(false); + htmlReporter.config().setJS(icon); + return htmlReporter; + } + + public static void closeReporter(){ + extent.flush(); + } + + public static void setTrafficCaptue(Config config) { + boolean mobProxyStatus = config.getUseBrowserMobProxy(); + if (mobProxyStatus){ + config.setCaptureTraffic(true);; + } + } +} + diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java new file mode 100644 index 0000000000..0523647c16 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.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.ci.tests.execute.setup; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.MediaEntityBuilder; +import com.aventstack.extentreports.Status; +import com.aventstack.extentreports.markuputils.ExtentColor; +import com.aventstack.extentreports.markuputils.Markup; +import com.aventstack.extentreports.markuputils.MarkupHelper; + +public class ExtentTestActions { + + public static void log(Status logStatus, Markup mark){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, mark); + } + + public static void log(Status logStatus, String message){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, message); + } + + public static void log(Status logStatus, String message, String duration){ + log(logStatus, message + addDurationTag(duration)); + } + + public static void log(Status logStatus, Throwable throwabel){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, throwabel); + } + + public static void addTag(Status logStatus, String message){ + Markup m = null; + switch(logStatus){ + case PASS: + m = MarkupHelper.createLabel(message, ExtentColor.GREEN); + break; + case FAIL: + m = MarkupHelper.createLabel(message, ExtentColor.RED); + break; + case SKIP: + m = MarkupHelper.createLabel(message, ExtentColor.BLUE); + break; + case FATAL: + m = MarkupHelper.createLabel(message, ExtentColor.BROWN); + break; + default: + break; + } + + if (m != null){ + log(logStatus, m); + } + } + + public static String addScreenshot(Status logStatus, String screenshotName, String message) throws IOException{ + String imageFilePath = null; + String uuid = UUID.randomUUID().toString(); + String[] stringArray = uuid.split("-"); + screenshotName = screenshotName + "-" + stringArray[stringArray.length - 1]; + try { + File imageFile = GeneralUIUtils.takeScreenshot(screenshotName, SetupCDTest.getScreenshotFolder()); + imageFilePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFile.toURI()).getPath(); + } catch (IOException e) { + e.printStackTrace(); + } + + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, message, MediaEntityBuilder.createScreenCaptureFromPath(imageFilePath).build()); + return imageFilePath; + } + + private static String addDurationTag(String duration){ + return "" + duration + ""; + } + + public static String addLinkTag(String fileName, String pathToFile){ + return String.format("HAR file", fileName, pathToFile); + } + + public static void addFileToReportAsLink(File harFile, String pathToFileFromReportDirectory, String message) { + log(Status.INFO, message, addLinkTag(harFile.getName(), pathToFileFromReportDirectory)); + } + + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java new file mode 100644 index 0000000000..b5ed1ea498 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java @@ -0,0 +1,60 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.util.HashMap; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.ExtentTest; + +public class ExtentTestManager { + + private static HashMap extentTestMap = new HashMap(); + private static ExtentReports extent = ExtentManager.getReporter(); + + public static synchronized ExtentTest getTest() { + return extentTestMap.get(Thread.currentThread().getId()); + } + + public static synchronized void endTest() { +// extent.endTest(extentTestMap.get(Thread.currentThread().getId())); + extent.flush(); + } + + public static synchronized ExtentTest startTest(String testName) { + return startTest(testName, ""); + } + + public static synchronized ExtentTest startTest(String testName, String desc) { + ExtentTest test = extent.createTest(testName, desc); + extentTestMap.put(Thread.currentThread().getId(), test); + + return test; + } + + public static synchronized void assignCategory(Class clazz){ + String[] parts = clazz.getName().split("\\."); + String lastOne1 = parts[parts.length-1]; + String lastOne2 = parts[parts.length-2]; + getTest().assignCategory(lastOne2 + "-" + lastOne1); + } +} + diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/MobProxy.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/MobProxy.java new file mode 100644 index 0000000000..78cf2709af --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/MobProxy.java @@ -0,0 +1,103 @@ +package org.openecomp.sdc.ci.tests.execute.setup; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +import org.slf4j.LoggerFactory; + +import com.aventstack.extentreports.ExtentTest; +import com.github.markusbernhardt.proxy.ProxySearch; +import com.github.markusbernhardt.proxy.ProxySearch.Strategy; +import com.github.markusbernhardt.proxy.util.PlatformUtil; +import com.github.markusbernhardt.proxy.util.PlatformUtil.Platform; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import net.lightbody.bmp.BrowserMobProxyServer; + +public class MobProxy { + + private static HashMap mobProxyServerMap = new HashMap(); + public static InetSocketAddress localProxyAddress = getProxy(); + + public static InetSocketAddress getProxy(){ + setLogger(); + + ProxySearch proxySearch = new ProxySearch(); +// proxySearch.addStrategy(Strategy.JAVA); +// proxySearch.addStrategy(Strategy.BROWSER); +// proxySearch.addStrategy(Strategy.OS_DEFAULT); +// proxySearch.addStrategy(Strategy.ENV_VAR); + if (PlatformUtil.getCurrentPlattform() == Platform.WIN) { + proxySearch.addStrategy(Strategy.IE); + proxySearch.addStrategy(Strategy.FIREFOX); + proxySearch.addStrategy(Strategy.JAVA); + } else if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) { + proxySearch.addStrategy(Strategy.GNOME); + proxySearch.addStrategy(Strategy.KDE); + proxySearch.addStrategy(Strategy.FIREFOX); + proxySearch.addStrategy(Strategy.ENV_VAR); + return null; + } else { + proxySearch.addStrategy(Strategy.OS_DEFAULT); + } + ProxySelector proxySelector = proxySearch.getProxySelector(); + + ProxySelector.setDefault(proxySelector); + URI home = URI.create("http://www.google.com"); + System.out.println("ProxySelector: " + proxySelector); + System.out.println("URI: " + home); + List proxyList = proxySelector.select(home); + String host = null; + String port = null; + if (proxyList != null && !proxyList.isEmpty()) { + for (Proxy proxy : proxyList) { + System.out.println(proxy); + SocketAddress address = proxy.address(); + if (address instanceof InetSocketAddress) { + host = ((InetSocketAddress) address).getHostName(); + port = Integer.toString(((InetSocketAddress) address).getPort()); + System.setProperty("http.proxyHost", host); + System.setProperty("http.proxyPort", port); + } + } + } + InetSocketAddress address = new InetSocketAddress(host, Integer.parseInt(port)); + return address; + } + + // set logger for all classes connected to MobProxy + public static void setLogger() { + LoggerContext lc = (LoggerContext) LoggerFactory. getILoggerFactory(); +// lc.getLogger("ROOT").setLevel(Level.DEBUG); + for(Logger logger:lc.getLoggerList()){ + logger.setLevel(Level.INFO); + } + } + + public static synchronized void setProxyServer() { + BrowserMobProxyServer server = new BrowserMobProxyServer(); + server.setTrustAllServers(true); + if (localProxyAddress != null){ + server.setChainedProxy(localProxyAddress); + server.start(); + } else { + server.start(); + // filter firefox requests to mozilla when system proxy is absent + server.blacklistRequests(".*mozilla.*", 200); + } + mobProxyServerMap.put(Thread.currentThread().getId(), server); + } + + public static synchronized BrowserMobProxyServer getPoxyServer() { + return mobProxyServerMap.get(Thread.currentThread().getId()); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java new file mode 100644 index 0000000000..03c9b0281f --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/OnboardCSVReport.java @@ -0,0 +1,63 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; + +public class OnboardCSVReport { + + private StringBuilder sb; + private PrintWriter pw; + + public OnboardCSVReport(String filepath, String filename) { + sb = new StringBuilder(); + try { + File csvFile = new File(filepath + filename); + pw = new PrintWriter(csvFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public StringBuilder appendStringToFile(String content) { + return sb.append(content + ","); + } + + public void openNewRow() { + sb.append("\n"); + } + + public void writeRow(String... content) { + for (String str : content) { + appendStringToFile(str); + } + openNewRow(); + } + + public void closeFile() { + pw.write(sb.toString()); + pw.close(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java new file mode 100644 index 0000000000..ad923d5a1a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.execute.setup; + +import java.io.IOException; + +import org.openecomp.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml; +import org.testng.ITestContext; +import org.testng.ITestResult; + +import com.aventstack.extentreports.Status; + +public class ReportAfterTestManager extends ExtentTestActions { + + private static String testName; + private static Throwable throwable; + private static int status; + + private static void logSuccessAfterTest(){ + final Status logStatus = Status.PASS; + addTag(logStatus, "Success"); + try{ + String message = "Finished the test with the following screenshot : "; + addScreenshotToReport(logStatus, testName, message); + }catch(Exception e){ + log(logStatus, "SUCCESS - The following exepction occured : " + e.getMessage()); + } + } + + private static void logFailAfterTest(){ + addTag(Status.FAIL, "Failure"); + try{ + log(Status.ERROR, "ERROR - The following exepction occured : "); + log(Status.ERROR, throwable); + String message = "Failure is described in the following screenshot : "; + addScreenshotToReport(Status.FAIL, testName, message); + }catch(Exception e){ + log(Status.ERROR, "ERROR - The following exepction occured : " + e.getMessage()); + } + } + + private static void logSkipAfterTest(){ + final Status logStatus = Status.SKIP; + addTag(logStatus, "Skipped"); + try{ + log(logStatus, "SKIP - The following exepction occured : "); + log(logStatus, throwable); + String message = "Skip is described in the following screenshot : "; + addScreenshotToReport(logStatus, testName, message); + }catch(Exception e){ + log(logStatus, "SKIP - The following exepction occured : " + e.getMessage()); + } + } + private static void logFatalAfterTest(){ + final Status logStatus = Status.FATAL; + addTag(logStatus, "Fatal"); + try{ + log(logStatus, "FATAL - The following exepction occured : "); + log(logStatus, throwable); + String message = "Fatal is described in the following screenshot : "; + addScreenshotToReport(logStatus, testName, message); + }catch(Exception e){ + log(logStatus, "FATAL - The following exepction occured : " + e.getMessage()); + } + } + + private static String addScreenshotToReport(Status logStatus, String testName, String message) throws IOException{ + + String addedValueFromDataProvider = WindowTestManager.getWindowMap().getAddedValueFromDataProvider(); + if (addedValueFromDataProvider != null){ + addedValueFromDataProvider = addedValueFromDataProvider.replace(":", "-"); + testName = testName + "...." + addedValueFromDataProvider; + } + + return addScreenshot(logStatus, testName, message); + } + + public static void report(ITestResult result, ITestContext context){ + + testName = result.getName(); + throwable = result.getThrowable(); + status = result.getStatus(); + + String suiteName = ExtentManager.getSuiteName(context); + + switch(status){ + case ITestResult.SUCCESS: + logSuccessAfterTest(); + break; + + case ITestResult.FAILURE: + + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + logFatalAfterTest(); + }else{ + logFailAfterTest(); + } + break; + + case ITestResult.SKIP: + logSkipAfterTest(); + break; + + default: + break; + } + + } + +} + diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/Retry.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/Retry.java new file mode 100644 index 0000000000..0a01da06c3 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/Retry.java @@ -0,0 +1,44 @@ +/*- + * ============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.ci.tests.execute.setup; + +import org.testng.Assert; +import org.testng.IRetryAnalyzer; +import org.testng.ITestResult; +import org.testng.annotations.Test; + +public class Retry implements IRetryAnalyzer { + private int retryCount = 0; + private int maxRetryCount = 1; + + public boolean retry(ITestResult result) { + + if (retryCount < maxRetryCount) { + retryCount++; + return true; + } + return false; + } + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java new file mode 100644 index 0000000000..1838d3969d --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java @@ -0,0 +1,573 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; +import java.util.logging.FileHandler; +import java.util.logging.Handler; +import java.util.logging.LogManager; +import java.util.logging.Logger; + +import org.littleshoot.proxy.impl.ClientToProxyConnection; +import org.littleshoot.proxy.impl.ProxyToServerConnection; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.UserCredentials; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.sanity.Onboard; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.ITestContext; +import org.testng.ITestResult; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import groovyjarjarantlr.Utils; +import net.lightbody.bmp.BrowserMobProxyServer; +import net.lightbody.bmp.core.har.Har; + +public abstract class SetupCDTest extends DriverFactory { + +// private static final String RE_RUN = "ReRun - "; + private static final String RE_RUN = "ReRun - "; + private static final String WEB_SEAL_PASSWORD = "123123a"; + + public SetupCDTest() { + LoggerContext lc = (LoggerContext) LoggerFactory. getILoggerFactory(); + lc.getLogger("org.apache").setLevel(Level.INFO); + } + + /**************** CONSTANTS ****************/ + private static final String CREDENTIALS_FILE = "credentials.yaml"; + private static final String REPORT_FILE_NAME = "SDC_UI_Extent_Report.html"; + protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator; + protected static final String SCREENSHOT_FOLDER = REPORT_FOLDER + "screenshots" + File.separator; + protected static final String HAR_FILES_FOLDER_NAME = "har_files"; + protected static final String HAR_FILES_FOLDER = REPORT_FOLDER + HAR_FILES_FOLDER_NAME + File.separator; + + + private static final String SHORT_CSV_REPORT_FILE_NAME = "ShortReport.csv"; + private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2; + + + /**************** PRIVATES ****************/ + private static String url; + private static boolean localEnv = true; + private static OnboardCSVReport csvReport; + private static Map credentials; + + protected static ITestContext myContext; + + + /**************** METHODS ****************/ + public static ExtentTest getExtendTest() { + return ExtentTestManager.getTest(); + } + public static WindowTest getWindowTest(){ + return WindowTestManager.getWindowMap(); + } + + public OnboardCSVReport getCsvReport() { + return csvReport; + } + + public static String getReportFolder() { + return REPORT_FOLDER; + } + + public static String getScreenshotFolder() { + return SCREENSHOT_FOLDER; + } + + public static String getHarFilesFolder() { + return HAR_FILES_FOLDER; + } + + + protected abstract UserRoleEnum getRole(); + + /**************** BEFORE ****************/ + + @BeforeSuite(alwaysRun = true) + public void setupBeforeSuite(ITestContext context) throws Exception { + RestCDUtils.deleteOnDemand(); + myContext=context; + setErrorConfigurationFile(); + setUrl(); + ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context); + csvReport = new OnboardCSVReport(getReportFolder(), SHORT_CSV_REPORT_FILE_NAME); + } + + private static void setErrorConfigurationFile() { + if (!System.getProperty("os.name").contains("Windows")){ + String errorConfigurationFilename = getConfig().getErrorConfigurationFile(); + errorConfigurationFilename = errorConfigurationFilename.substring(errorConfigurationFilename.lastIndexOf("/") + 1, errorConfigurationFilename.length()); + getConfig().setErrorConfigurationFile(FileHandling.getBasePath() + File.separator + "conf" + File.separator + errorConfigurationFilename); + if (new File(getConfig().getErrorConfigurationFile()).exists()){ + System.out.println("Found error-configuration.yaml in : " + getConfig().getErrorConfigurationFile()); + } + } + } + + @BeforeMethod(alwaysRun = true ) + public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception { + + boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty(); + if (emptyDataProvider) { + System.out.println("ExtentReport instance started from BeforeMethod..."); + String suiteName = ExtentManager.getSuiteName(context); + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + ExtentTestManager.startTest(RE_RUN + method.getName()); + }else{ + ExtentTestManager.startTest(method.getName()); + } + + ExtentTestManager.assignCategory(this.getClass()); + setBrowserBeforeTest(getRole()); + } else { + System.out.println("ExtentReport instance started from Test..."); + } + + getConfig().setWindowsDownloadDirectory(getWindowTest().getDownloadDirectory()); + + if (getConfig().getCaptureTraffic()){ + try{ + MobProxy.getPoxyServer().newHar(method.getName() + ".har"); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + /**************** AFTER ****************/ + @AfterMethod(alwaysRun = true) + public void quitAfterTest(ITestResult result, ITestContext context) throws Exception { + + try{ + ReportAfterTestManager.report(result, context); + GeneralUIUtils.closeErrorMessage(); + } + finally{ + try { + if (getConfig().getCaptureTraffic()){ + addTrafficFileToReport(result); + } + + if (result.getInstanceName().equals(Onboard.class.getName()) && result.getStatus() == ITestResult.FAILURE){ + System.out.println("Onboarding test failed, closign browser...."); + getExtendTest().log(Status.INFO, "Onboarding test failed, closign browser...."); + quitDriver(); + } + else if (!getUser().getRole().toLowerCase().equals(UserRoleEnum.ADMIN.name().toLowerCase())){ + boolean navigateToHomePageSuccess = HomePage.navigateToHomePage(); + if (!navigateToHomePageSuccess){ + System.out.println("Navigating to homepage failed, reopening driver...."); + getExtendTest().log(Status.INFO, "Navigating to homepage failed, reopening driver...."); + quitDriver(); + } + } + + } catch (Exception e) { + e.printStackTrace(); + getExtendTest().log(Status.ERROR, "Exception:"+ e.toString()); + } + + + + ExtentTestManager.endTest(); + addResultToCSV(result, context); +// ExtentManager.closeReporter(); + FileHandling.cleanCurrentDownloadDir(); + } + + } + public void addResultToCSV(ITestResult result, ITestContext context) { + String suiteName = ExtentManager.getSuiteName(context); + ExtentTest test = ExtentTestManager.getTest(); + com.aventstack.extentreports.model.Test model = test.getModel(); + String name = model.getName(); + String status = model.getStatus().toString(); + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue()) && !(result.getStatus() == ITestResult.SUCCESS)) { + getCsvReport().writeRow(result.getInstanceName(), name.replace(RE_RUN,""), status); + } + } + + @AfterSuite(alwaysRun = true) + public void afterSuite() throws Exception { + + if (getConfig().getUseBrowserMobProxy()){ + MobProxy.getPoxyServer().stop(); + } + + csvReport.closeFile(); + RestCDUtils.deleteOnDemand(); + } + + protected static String setUrl() { + url = getConfig().getUrl(); + if (url == null) { + String message = "no URL found"; + System.out.println(message); + Assert.fail(message); + } else if (!url.contains("localhost") && !url.contains("127.0.0.1")) { + localEnv = false; + } + return url; + } + + public static void loadCredentialsFile() throws Exception { + if (credentials != null){ + return; + } + File credentialsFileRemote = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + CREDENTIALS_FILE); + File credentialsFileLocal = new File(FileHandling.getConfFilesPath() + CREDENTIALS_FILE); + File[] credentialFiles = {credentialsFileRemote, credentialsFileLocal}; + for (File credentialsFile : credentialFiles){ + if (credentialsFile.exists()){ + credentials = FileHandling.parseYamlFile(credentialsFile.getAbsolutePath()); + break; + } + } + } + + private UserCredentials getUserCredentialsFromFile(String userRole) throws Exception { + @SuppressWarnings("unchecked") + Map credentialsMap = (Map) credentials.get(userRole); + String user = (String) credentialsMap.get("username"); + String password = (String) credentialsMap.get("password"); + String firstname = (String) credentialsMap.get("firstname"); + String lastname = (String) credentialsMap.get("lastname"); + + return new UserCredentials(user, password, firstname, lastname, userRole); + } + + + public static void navigateToUrl(String url) throws Exception { + try { + System.out.println("Deleting cookies..."); + deleteCookies(); + + System.out.println("Navigating to URL : " + url); + getDriver().navigate().to(url); + GeneralUIUtils.waitForLoader(); + + System.out.println("Zooming out..."); + GeneralUIUtils.windowZoomOutUltimate(); + + } + catch (Exception e) { + String msg = "Browser is unreachable"; + System.out.println(msg); + getExtendTest().log(Status.ERROR, msg); + Assert.fail(msg); + } + } + private static void deleteCookies() throws Exception { + getDriver().manage().deleteAllCookies(); + Thread.sleep(1000); + + int attempts = 0; + final int max_attempts = 3; + + while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts){ + getExtendTest().log(Status.INFO, "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts"); + String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });"; + ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS); + attempts++; + + if (attempts == max_attempts){ + String msg = "Did not delete cookies, can't login as user " + WindowTestManager.getWindowMap().getUser().getRole(); + System.out.println(msg); + getExtendTest().log(Status.ERROR, msg); + Assert.fail(msg); + } + } + } + + protected void loginToSystem(UserRoleEnum role) throws Exception { + UserCredentials credentials; + if (localEnv){ + loginToSimulator(role); + credentials = new UserCredentials(role.getUserId(), WEB_SEAL_PASSWORD, role.getFirstName(), role.getLastName(), role.name()); + } + else{ + credentials = getUserFromFileByRole(role); + sendUserAndPasswordKeys(credentials); + WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), 30); + submitButton.click(); + WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), 30); + Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed."); + buttonOK.click(); + } + GeneralUIUtils.ultimateWait(); + getWindowTest().setUser(credentials); + } + protected UserCredentials getUserFromFileByRole(UserRoleEnum role) throws Exception { + loadCredentialsFile(); + return getUserCredentialsFromFile(role.name().toLowerCase()); + } + private void goToHomePage(UserRoleEnum role) throws Exception { + try { + getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() == 0 ? NUM_OF_ATTEMPTS_TO_REFTRESH : getWindowTest().getRefreshAttempts()); + if (!role.equals(UserRoleEnum.ADMIN)) { + + WebElement closeButton = GeneralUIUtils.getClickableButtonBy(By.className("sdc-welcome-close"), 10); + if (closeButton != null){ + closeButton.click(); + } + + if (!GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue())) + { + restartBrowser(role); + } + } + } + catch (Exception e) { + restartBrowser(role); + } + } + private void restartBrowser(UserRoleEnum role) throws Exception { + getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() - 1); + if (getWindowTest().getRefreshAttempts() <= 0) { + System.out.println("ERR : Something is wrong with browser!"); + Assert.fail("ERR : Something is wrong with browser!"); + } + System.out.println("Trying again..."); + getExtendTest().log(Status.INFO, "Trying again..."); + getExtendTest().log(Status.INFO, String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts() )); + System.out.println(String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts() )); + + reloginWithNewRole(role); + } + + public void loginToSimulator(UserRoleEnum role){ + WebDriver driver = GeneralUIUtils.getDriver(); + WebDriverWait wait = new WebDriverWait(driver, 30); + + wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']")))); + + WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId")); + userIdTextbox.sendKeys(role.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(WEB_SEAL_PASSWORD); + + wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click(); + } + + private void sendUserAndPasswordKeys(UserCredentials userId) { + System.out.println("Login as user : " + userId.getUserId()); + WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid")); + userNameTextbox.sendKeys(userId.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(userId.getPassword()); + } + + public void loginWithUser(UserRoleEnum role) { + try { + getExtendTest().log(Status.INFO, String.format("Login as user %s", role.name().toUpperCase())); + loginToSystem(role); + goToHomePage(role); + } catch (Exception e) { + throw new RuntimeException(e); + } + finally{ + getWindowTest().setPreviousRole(getWindowTest().getUser().getRole()); + } + } + + private void setUser(UserRoleEnum role) { + User user = new User(); + user.setUserId(role.getUserId()); + user.setFirstName(role.getFirstName()); + user.setRole(role.name()); + user.setLastName(role.getLastName()); + + getWindowTest().setUser(user); + } + + public User getUser() { + return getWindowTest().getUser(); + } + + private void setBrowserBeforeTest(UserRoleEnum role) { + System.out.println(String.format("Setup before test as %s.", role.toString().toUpperCase() )); + try { + System.out.println("Previous role is : " + getWindowTest().getPreviousRole() + " ; Current role is : " + role.name()); + if (!getWindowTest().getPreviousRole().toLowerCase().equals(role.name().toLowerCase())){ + System.out.println("Roles are different, navigate and login"); + navigateAndLogin(role); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void navigateAndLogin(UserRoleEnum role) throws Exception { + getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0); + setUser(role); + navigateToUrl(url); + loginWithUser(role); + GeneralUIUtils.ultimateWait(); + } + + public User getUser(UserRoleEnum role) { + User user = new User(); + user.setUserId(role.getUserId()); + user.setFirstName(role.getFirstName()); + user.setLastName(role.getLastName()); + user.setRole(role.name()); + return user; + } + + protected void reloginWithNewRole(UserRoleEnum role) throws Exception { + System.out.println(String.format("Setup before relogin as %s", role.toString().toUpperCase())); + navigateAndLogin(role); + } + + public static void setLocalUrl(UserRoleEnum role) { + switch (role) { + case ADMIN: { + url = "http://localhost:8181/sdc1/proxy-admin1#/dashboard"; + break; + } + case DESIGNER: { + url = "http://localhost:8181/sdc1/proxy-designer1#/dashboard"; + break; + } + case GOVERNOR: { + url = "http://localhost:8181/sdc1/proxy-governor1#/dashboard"; + break; + } + case OPS: { + url = "http://localhost:8181/sdc1/proxy-ops1#/dashboard"; + break; + } + case TESTER: { + url = "http://localhost:8181/sdc1/proxy-tester1#/dashboard"; + break; + } + case PRODUCT_MANAGER1: { + url = "http://localhost:8181/sdc1/proxy-pm1#/dashboard"; + break; + } + case PRODUCT_MANAGER2: { + url = "http://localhost:8181/sdc1/proxy-pm2#/dashboard"; + break; + } + case PRODUCT_STRATEGIST1: { + url = "http://localhost:8181/sdc1/proxy-ps1#/dashboard"; + break; + } + case PRODUCT_STRATEGIST2: { + url = "http://localhost:8181/sdc1/proxy-ps2#/dashboard"; + break; + } + default: { + break; + } + } + } + + public void addTrafficFileToReport(ITestResult result) { + try { + // Get the HAR data + Har har = MobProxy.getPoxyServer().getHar(); + String shortUUID = UUID.randomUUID().toString().split("-")[0]; + File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har"); + new File(getHarFilesFolder()).mkdirs(); + + har.writeTo(harFile); + + String pathToFileFromReportDirectory = HAR_FILES_FOLDER_NAME + File.separator + harFile.getName(); + ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory, "File with captured traffic"); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + /* + * * Start section of test in ExtentReport with DataProvider parameters, + * should be started from test method, see example in onboardVNFTest + */ + public void setLog(String fromDataProvider) { + + String suiteName = ExtentManager.getSuiteName(myContext); + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + ExtentTestManager.startTest(RE_RUN +Thread.currentThread().getStackTrace()[2].getMethodName() + "      " + fromDataProvider); + }else{ + ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "      " + fromDataProvider); + } + + + + getWindowTest().setAddedValueFromDataProvider(fromDataProvider); + ExtentTestManager.assignCategory(this.getClass()); + setBrowserBeforeTest(getRole()); + } + + + + /**************** MAIN ****************/ + public static void main(String[] args) { + System.out.println("---------------------"); + System.out.println("running test from CLI"); + System.out.println("---------------------"); + + String attsdcFilePath = FileHandling.getBasePath() + File.separator + "conf" + File.separator + "attsdc.yaml"; + System.setProperty("config.resource", attsdcFilePath); + System.out.println("attsdc.yaml file path is : " + attsdcFilePath); + + String filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator; + System.setProperty("filepath", filepath); + System.out.println("filepath is : " + System.getProperty("filepath")); + + Object[] testSuitsList = FileHandling.filterFileNamesFromFolder(FileHandling.getBasePath() + File.separator + "testSuites", ".xml"); + if (testSuitsList != null) { + System.out.println(String.format("Found %s testSuite(s)", testSuitsList.length)); + args = Arrays.copyOf(testSuitsList, testSuitsList.length, String[].class); + StartTest.main(args); + } + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/TestFtp.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/TestFtp.java new file mode 100644 index 0000000000..0268c69f59 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/TestFtp.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.execute.setup; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.openqa.selenium.remote.internal.ApacheHttpClient; + +public class TestFtp { + + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + AttFtpClient instance = AttFtpClient.getInstance(); + + String server = "135.177.130.113"; + int port = 2121; + String user = "admin"; + String pass = "admin"; + AttFtpClient.getInstance().init(server, port, user, pass); + + try { + AttFtpClient.getInstance().retrieveListOfFile(); + + File retrieveLastModifiedFileFromFTP = instance.retrieveLastModifiedFileFromFTP(); + String content = new String(Files.readAllBytes(Paths.get(retrieveLastModifiedFileFromFTP.getPath())), StandardCharsets.UTF_8); +// instance.deleteFilesFromFTPserver(); + System.out.println(content); + readFile(retrieveLastModifiedFileFromFTP); + + } finally { + instance.terminateClient(); + } + + + + + + + + } + public static void readFile(File retrieveLastModifiedFileFromFTP) { + + StringBuilder sb = new StringBuilder(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(retrieveLastModifiedFileFromFTP.getPath())); + String line; + while ((line = br.readLine()) != null) { + if (sb.length() > 0) { + sb.append("\n"); + } + sb.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) { + br.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + String contents = sb.toString(); + System.out.println(contents); + + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java new file mode 100644 index 0000000000..5a95df39f8 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java @@ -0,0 +1,164 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.io.File; +import java.io.FileNotFoundException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; + +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openqa.selenium.Platform; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.openqa.selenium.remote.CapabilityType; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.remote.LocalFileDetector; +import org.openqa.selenium.remote.RemoteWebDriver; + +import net.lightbody.bmp.BrowserMobProxyServer; +import net.lightbody.bmp.client.ClientUtil; +import net.lightbody.bmp.proxy.CaptureType; + +public class WebDriverThread { + + public static final String AUTOMATION_DOWNLOAD_DIR = "automationDownloadDir"; + private WebDriver webdriver; + private FirefoxProfile firefoxProfile; + public static final String SELENIUM_NODE_URL = "http://%s:%s/wd/hub"; + + public WebDriverThread(Config config) { + initDriver(config); + webdriver.manage().window().maximize(); + } + + public WebDriver getDriver() throws Exception { + return webdriver; + } + + public void quitDriver() { + if (webdriver != null) { + webdriver.quit(); + webdriver = null; + } + } + + + public void initDriver(Config config){ + try { + boolean remoteTesting = config.isRemoteTesting(); + if (!remoteTesting) { + boolean mobProxyStatus = config.getUseBrowserMobProxy(); + if (mobProxyStatus){ + setWebDriverWithMobProxy(); + } else { + System.out.println("Opening LOCAL browser"); + DesiredCapabilities cap = new DesiredCapabilities(); + + cap = DesiredCapabilities.firefox(); + cap.setBrowserName("firefox"); + cap.setCapability(FirefoxDriver.PROFILE, initFirefoxProfile()); + + firefoxProfile.setPreference("network.proxy.type", 2); + firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://emea-auto.proxy.att.com:8001/"); + firefoxProfile.setPreference("network.proxy.no_proxies_on", "localhost"); + + webdriver = new FirefoxDriver(cap); + } + } else { + System.out.println("Opening REMOTE browser"); + String remoteEnvIP = config.getRemoteTestingMachineIP(); + String remoteEnvPort = config.getRemoteTestingMachinePort(); + + DesiredCapabilities cap = new DesiredCapabilities(); + cap = DesiredCapabilities.firefox(); + cap.setPlatform(Platform.ANY); + cap.setBrowserName("firefox"); + + String remoteNodeUrl = String.format(SELENIUM_NODE_URL, remoteEnvIP, remoteEnvPort); + RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(remoteNodeUrl), cap); + remoteWebDriver.setFileDetector(new LocalFileDetector()); + webdriver = remoteWebDriver; + } + + + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + private FirefoxProfile initFirefoxProfile() { + firefoxProfile = new FirefoxProfile(); + firefoxProfile.setPreference("browser.download.folderList",2); + firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false); + firefoxProfile.setPreference("browser.download.dir", getDownloadDirectory()); + firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/octet-stream, application/xml, text/plain, text/xml, image/jpeg"); + return firefoxProfile; + } + + private String getDownloadDirectory() { + String downloadDirectory = FileHandling.getBasePath() + File.separator + AUTOMATION_DOWNLOAD_DIR + UUID.randomUUID().toString().split("-")[0] + File.separator; + File dir = new File(downloadDirectory); + if(!dir.exists()) { + dir.mkdirs(); + } + return dir.getAbsolutePath(); + } + + public FirefoxProfile getFirefoxProfile() { + return firefoxProfile; + } + + private void setWebDriverWithMobProxy(){ + WebDriver driver = null; + MobProxy.setProxyServer(); + BrowserMobProxyServer proxyServer = MobProxy.getPoxyServer(); + + firefoxProfile = new FirefoxProfile(); + firefoxProfile.setPreference("browser.download.folderList",2); + firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false); + firefoxProfile.setPreference("browser.download.dir", getDownloadDirectory()); + firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/octet-stream, application/xml, text/plain, text/xml, image/jpeg"); + firefoxProfile.setAcceptUntrustedCertificates(true); + firefoxProfile.setAssumeUntrustedCertificateIssuer(true); +// firefoxProfile.setPreference("network.proxy.http", "localhost"); +// firefoxProfile.setPreference("network.proxy.http_port", proxyServer.getPort()); +// firefoxProfile.setPreference("network.proxy.ssl", "localhost"); +// firefoxProfile.setPreference("network.proxy.ssl_port", proxyServer.getPort()); +// firefoxProfile.setPreference("network.proxy.type", 1); +// firefoxProfile.setPreference("network.proxy.no_proxies_on", ""); + + DesiredCapabilities capabilities = new DesiredCapabilities(); + + capabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile); + capabilities.setCapability(CapabilityType.PROXY, ClientUtil.createSeleniumProxy(proxyServer)); + capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + + webdriver = new FirefoxDriver(capabilities); + proxyServer.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT, CaptureType.REQUEST_COOKIES, CaptureType.REQUEST_BINARY_CONTENT, + CaptureType.REQUEST_HEADERS, CaptureType.RESPONSE_COOKIES, CaptureType.RESPONSE_HEADERS, CaptureType.RESPONSE_BINARY_CONTENT); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTest.java new file mode 100644 index 0000000000..8df3c596fe --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTest.java @@ -0,0 +1,77 @@ +/*- + * ============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.ci.tests.execute.setup; + +import java.io.File; + +import org.openecomp.sdc.be.model.User; + +public class WindowTest { + + public WindowTest(){ + refreshAttempts = 0; + previousRole = ""; + addedValueFromDataProvider = null; + try { + downloadDirectory = DriverFactory.getDriverFirefoxProfile().getStringPreference("browser.download.dir", null) + File.separator; + } catch (Exception e) { + e.printStackTrace(); + } + } + + private int refreshAttempts; + private String previousRole; + private User user; + private String addedValueFromDataProvider; + private String downloadDirectory; + + public int getRefreshAttempts() { + return refreshAttempts; + } + public void setRefreshAttempts(int refreshAttempts) { + this.refreshAttempts = refreshAttempts; + } + public String getPreviousRole() { + return previousRole; + } + public void setPreviousRole(String previousRole) { + this.previousRole = previousRole; + } + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } + public synchronized String getAddedValueFromDataProvider() { + return addedValueFromDataProvider; + } + public synchronized void setAddedValueFromDataProvider(String addedValueFromDataProvider) { + this.addedValueFromDataProvider = addedValueFromDataProvider; + } + public String getDownloadDirectory() { + return downloadDirectory; + } + public void setDownloadDirectory(String downloadDirectory) { + this.downloadDirectory = downloadDirectory; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTestManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTestManager.java new file mode 100644 index 0000000000..5e5ddc4fbd --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WindowTestManager.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.execute.setup; + +import java.util.HashMap; + +import com.aventstack.extentreports.ExtentTest; + +public class WindowTestManager { + + private static HashMap windowMap = new HashMap(); + + public static synchronized WindowTest getWindowMap() { + Long currentThreadId = Thread.currentThread().getId(); + boolean containsKey = windowMap.containsKey(currentThreadId); + if (!containsKey){ + setWindowMap(currentThreadId); + } + return windowMap.get(currentThreadId); + } + + private static synchronized void setWindowMap(Long currentThreadId) { + WindowTestManager.windowMap.put(currentThreadId, new WindowTest()); + } + + public static synchronized void removeWindowTest(){ + windowMap.remove(Thread.currentThread().getId()); + } + + public static synchronized HashMap getWholeMap(){ + return windowMap; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AdminGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AdminGeneralPage.java new file mode 100644 index 0000000000..98ef4318c8 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AdminGeneralPage.java @@ -0,0 +1,132 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.UserManagementTab; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class AdminGeneralPage extends GeneralPageElements { + + public AdminGeneralPage() { + super(); + } + + private static UserManagementTab userManagementTab = new UserManagementTab(); + + public static UserManagementTab getUserManagementTab() { + return userManagementTab; + } + + public static void selectCategoryManagmetTab() throws Exception { + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.AdminPageTabs.CATEGORY_MANAGEMENT.getValue()); + } + + public static void selectUserManagmetTab() throws Exception { + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.AdminPageTabs.USER_MANAGEMENT.getValue()); + } + + public static List getServiceCategoriesList() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.SERVICE_CATEGORY_HEADER.getValue()); + GeneralUIUtils.waitForLoader(); + return GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.CategoryManagement.SERVICE_CATEGORY_LIST.getValue()); + } + + public static List getResourceCategoriesList() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_HEADER.getValue()); + GeneralUIUtils.waitForLoader(); + return GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_LIST.getValue()); + } + + public static void createNewServiceCategory(String name) throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.SERVICE_CATEGORY_HEADER.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Creating service..."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.NEW_CATEGORY_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + defineNewResourceCategoryName(name); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.waitForLoader(); + } + + public static void selectElementFromList(List list, String elementToSelect) throws Exception { + + for (WebElement webElement : list) { + if (webElement.getText().toLowerCase().equals(elementToSelect.toLowerCase())){ + webElement.click(); + } + } + + } + + + + public static void addSubCategoryToResource(List resourceList, String parentResource, String subCategoryName) throws Exception{ + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_HEADER.getValue()); + selectElementFromList(resourceList, parentResource); + SetupCDTest.getExtendTest().log(Status.INFO, "Creating..."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.NEW_SUB_CATEGORY_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + defineNewResourceCategoryName(subCategoryName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.waitForLoader(); + + + } + + public static void createNewResourceCategory(String name) throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_HEADER.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Creating..."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.NEW_CATEGORY_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + defineNewResourceCategoryName(name); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.waitForLoader(); + + } + + public void insertPropertyDefaultValue(String value) { + WebElement propertyValue = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_VALUE.getValue()); + propertyValue.clear(); + propertyValue.sendKeys(value); + } + + private static void defineNewResourceCategoryName(String name) { + WebElement categoryNameTextbox = getCategoryName(); + categoryNameTextbox.clear(); + categoryNameTextbox.sendKeys(name); + } + + private static WebElement getCategoryName() { + return GeneralUIUtils.getWebElementByClassName(DataTestIdEnum.CategoryManagement.NEW_CATEGORY_NAME.getValue()); + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java new file mode 100644 index 0000000000..d795599f24 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ComponentLeftMenu.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.pages; + +public interface ComponentLeftMenu { + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java new file mode 100644 index 0000000000..496c537d49 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java @@ -0,0 +1,197 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; +import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.Select; + +import com.aventstack.extentreports.Status; + +public class CompositionPage extends GeneralPageElements { + + public CompositionPage() { + super(); + } + + public static UploadArtifactPopup artifactPopup() { + return new UploadArtifactPopup(true); + } + + public static void searchForElement(String elementName) { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + elementName + " in the left panel"); + WebElement searchField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.SEARCH_ASSET.getValue()); + searchField.clear(); + searchField.sendKeys(elementName); + GeneralUIUtils.ultimateWait(); + } + + public static void showDeploymentArtifactTab() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB); + } + + public static void showInformationsTab() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.INFORMATION_TAB); + } + + public static void showPropertiesAndAttributesTab() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.PROPERTIES_AND_ATTRIBUTES_TAB); + } + + public static List getProperties() { + return PropertiesPage.getElemenetsFromTable(); + } + + public static List getDeploymentArtifacts() { + return getAllAddedArtifacts(); + } + + public static List getAllAddedArtifacts() { + String dataTestsId = DataTestIdEnum.CompositionScreenEnum.ARTIFACTS_LIST.getValue(); + return GeneralUIUtils.getWebElementsListBy(By.xpath("//*[contains(@data-tests-id,'" + dataTestsId + "')]")); + } + + public static void moveToInputsScreen() throws Exception { + OpenPagesMenu(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.MENU_INPUTS.getValue()); + GeneralUIUtils.ultimateWait(); + } + + private static void OpenPagesMenu() { + Actions actions = new Actions(GeneralUIUtils.getDriver()); + List triangleList = GeneralUIUtils.getWebElementsListByClassName(DataTestIdEnum.CompositionScreenEnum.MENU_TRIANGLE_DROPDOWN.getValue()); + WebElement pagesMenu = triangleList.get(2); + actions.moveToElement(pagesMenu).perform(); + } + + public static void changeComponentVersion(CanvasManager canvasManager, CanvasElement element, String version) { + try{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Changing component version to %s", version)); + canvasManager.clickOnCanvaElement(element); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue()); + GeneralUIUtils.ultimateWait(); + Select selectlist = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue())); + while (selectlist.getOptions().size() == 0) { + selectlist = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue())); + } + GeneralUIUtils.ultimateWait();; + selectlist.selectByValue(version); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickSomewhereOnPage(); + } + catch(Exception e){ + throw e; + } + } + + public static void clickAddArtifactButton() throws Exception{ + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.ADD_ARTIFACT); + GeneralUIUtils.getWebElementByClassName("sdc-add-artifact"); + } + + public static String getSelectedInstanceName(){ + return GeneralUIUtils.getWebElementByTestID("selectedCompTitle").getText(); + } + + public static void showInformationArtifactTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.INFORMATION_ARTIFACTS); + } + + public static void showAPIArtifactTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.API); + } + + public static void showInformationTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.INFORMATION); + } + + public static void showCompositionTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.COMPOSITION); + } + + public static void showInputsTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.INPUTS); + } + + public static void showRequirementsAndCapabilitiesTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.REQUIREMENTS_AND_CAPABILITIES); + } + + public static List getOpenTabTitle() throws Exception{ +// return GeneralUIUtils.getElementsByCSS("expand-collapse span"); + return GeneralUIUtils.getElementsByCSS("expand-collapse"); + } + + public static void clickOnTab(DataTestIdEnum.CompositionScreenEnum tabSelector) throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", tabSelector.name())); + GeneralUIUtils.getElementsByCSS(tabSelector.getValue()).get(0).click(); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum tabSelector) throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", tabSelector.name())); + GeneralUIUtils.getWebElementByTestID(tabSelector.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + + public static CanvasElement addElementToCanvasScreen(LeftPanelCanvasItems elementName, CanvasManager vfCanvasManager) throws Exception{ + CompositionPage.searchForElement(elementName.name()); + return vfCanvasManager.createElementOnCanvas(elementName); + } + + public static CanvasElement addElementToCanvasScreen(String elementName, CanvasManager vfCanvasManager) throws Exception{ + CompositionPage.searchForElement(elementName); + return vfCanvasManager.createElementOnCanvas(elementName); + } + + public static List getCompositionDeplymentArtifacts() { + return GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue()); + } + public static WebElement getCustomizationUUID() throws Exception { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.CUSTOMIZATION_UUID.getValue()); + } + + + public static List getCompositionEnvArtifacts(){ + return GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ENV.getValue()); + } + + public static WebElement clickDownloadEnvArtifactComposition(String fileName) { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ENV.getValue() + fileName); + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() +fileName); + } + + + + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java new file mode 100644 index 0000000000..810a1f991c --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java @@ -0,0 +1,277 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang.WordUtils; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.collections.Lists; + +import com.aventstack.extentreports.Status; + +public class DeploymentArtifactPage extends GeneralPageElements { + + public DeploymentArtifactPage() { + super(); + } + + public static ResourceLeftMenu getLeftPanel() { + return new ResourceLeftMenu(); + } + + public static UploadArtifactPopup artifactPopup() { + return new UploadArtifactPopup(); + } + + protected static void addNewArtifact(ArtifactGroupTypeEnum artifactGroupType) { + switch (artifactGroupType) { + case DEPLOYMENT: + GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.ADD_DEPLOYMENT_ARTIFACT.getValue()).click(); + break; + case INFORMATIONAL: + GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.ADD_INFORMATIONAL_ARTIFACT.getValue()).click(); + break; + default: + break; + } + } + + public static void clickAddNewArtifact() { + addNewArtifact(ArtifactGroupTypeEnum.DEPLOYMENT); + } + + public static void clickAddAnotherArtifact() { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.ADD_ANOTHER_ARTIFACT.getValue()).click(); + } + + public static void clickEditArtifact(String artifactLabel) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + artifactLabel).click(); + } + + public static void clickEditEnvArtifact(String artifactLabel) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactLabel).click(); + } + + public static void clickDeleteArtifact(String artifactLabel) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Deleting %s Artefact ",artifactLabel)); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + artifactLabel).click(); + } + + public static WebElement clickDownloadArtifact(String artifactLabel) { + WebElement downloadButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + artifactLabel); + + return downloadButton; + } + + public static void clickDownloadEnvArtifact(String envFileNameToDownload) { + ExtentTestActions.log(Status.INFO, String.format("Downloading the updated %s artifact for validate parameters with the response after the update...", envFileNameToDownload)); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + envFileNameToDownload); + ExtentTestActions.log(Status.INFO, String.format("%s Envartifact was downloaded successfully!", envFileNameToDownload)); + } + + public static void clickSaveEnvParameters() { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.SAVE.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + + public static WebElement getAddOtherArtifactButton(){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.ADD_ANOTHER_ARTIFACT.getValue()); + } + + public static void clickOK(){ + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.OK.getValue()).click(); + GeneralUIUtils.getWebElementBy(By.className("flex-container")); + GeneralUIUtils.waitForAngular(); + } + + public static String getArtifactDescription(String artifactLabel) throws Exception { + clickOnArtifactDescription(artifactLabel); // open artifact + WebElement artifactDescriptionElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.GET_DEPLOYMENT_ARTIFACT_DESCRIPTION.getValue()); + String artifactDesc = artifactDescriptionElement.getAttribute("value"); + closeArtifactDescription(artifactLabel); // close artifact + return artifactDesc; + } + + public static void closeArtifactDescription(String artifactLabel) { + GeneralUIUtils.clickOnElementByTestId("popover-x-button"); + } + + public static WebElement clickOnArtifactDescription(String artifactLabel) throws Exception { + try{ + WebElement artifact = GeneralUIUtils.getWebElementByTestID("descriptionIcon_" + artifactLabel); + artifact.click(); + GeneralUIUtils.waitForLoader(); + return artifact; + } + catch(Exception e){ + throw new Exception("Artifact " + artifactLabel + "is not found"); + } + } + + public static boolean checkElementsCountInTable(int expectedElementsCount) { + return GeneralPageElements.checkElementsCountInTable(expectedElementsCount + 1); + } + + public static String[] verifyArtifactsExistInTable(String filepath, String vnfFile) throws Exception{ + String[] artifactNamesFromZipFile = FileHandling.getArtifactsFromZip(filepath, vnfFile); + return verifyArtifactsExistInTable(artifactNamesFromZipFile); + } + + public static String[] verifyArtifactsExistInTable(String[] artifactNamesFromZipFile) throws Exception{ + if (artifactNamesFromZipFile != null){ + checkArtifactsDisplayed(artifactNamesFromZipFile); + checkEnvArtifactsDisplayed(); + } + + return artifactNamesFromZipFile; + } + + public static void checkArtifactsDisplayed(String[] artifactsFromZipFile) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the artifacts in the table"); + List artifactList = Lists.newArrayList(artifactsFromZipFile).stream().filter(p -> !p.contains(".env")).map(p -> getVisualArtifactName(p)).collect(Collectors.toList()); + try{ +// List rows = GeneralUIUtils.getElementsByCSS("div div[data-tests-id^='artifact-item'] span.ng-binding:nth-of-type(2)"); + List rows = GeneralUIUtils.getElementsByCSS("div div[data-tests-id^='artifact-item'] span[data-tests-id^='artifactDisplayName']"); + for (WebElement r : rows){ + String artifactDisplayed = r.getAttribute("textContent").trim(); + if (artifactList.contains(artifactDisplayed)){ + artifactList.remove(artifactDisplayed); + } + else if (artifactDisplayed.toLowerCase().contains("license")){ + artifactList.add(artifactDisplayed); + } + } + checkLicenseArtifactsDisplayed(artifactList); + } + catch(Exception e){ + throw new Exception("Table problem"); + } + + + if (!artifactList.isEmpty()){ + throw new Exception(String.format("missing the following artifact(s) : %s", artifactList.toString())); + } + } + + public static void checkEnvArtifactsDisplayed() throws Exception { + List envRows; + List heatRows; + List heatNetRows; + List heatVolRows; + int envArtifactsSize = 0; + + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the HEAT_ENV artifacts in the table"); + + try{ + envRows = GeneralUIUtils.getElementsByCSS("div div[data-tests-id='HEAT_ENV']"); + + heatRows = GeneralUIUtils.getElementsByCSS("div div[tooltip-content='HEAT']"); + heatNetRows = GeneralUIUtils.getElementsByCSS("div div[tooltip-content='HEAT_NET']"); + heatVolRows = GeneralUIUtils.getElementsByCSS("div div[tooltip-content='HEAT_VOL']"); + + envArtifactsSize = heatRows.size() + heatNetRows.size() + heatVolRows.size(); + } + catch(Exception e){ + throw new Exception("Table problem"); + } + + if (envArtifactsSize !=envRows.size()){ + throw new Exception(String.format("some env artifacts are missing... there is %s instead of %s", envRows.size(), envArtifactsSize)); + } + + } + + public static void checkLicenseArtifactsDisplayed(List rowsFromTable) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the license artifacts in the table"); + String vfLicense = getPreparedLicense(ArtifactTypeEnum.VF_LICENSE.getType()); + String[] split = vfLicense.split(" "); + vfLicense = vfLicense.replaceAll(split[0], split[0].toUpperCase()); + if (rowsFromTable.contains(vfLicense)){ + rowsFromTable.remove(vfLicense); + } + + String vendorLicense = getPreparedLicense(ArtifactTypeEnum.VENDOR_LICENSE.getType()); + if (rowsFromTable.contains(vendorLicense)){ + rowsFromTable.remove(vendorLicense); + } + + } + + public static String getPreparedLicense(String license) { + return WordUtils.capitalizeFully(license.replaceAll("_", " ")); + } + + + private static String getVisualArtifactName(String artifactName) { + if (artifactName.contains(".")){ + return artifactName.substring(0, artifactName.lastIndexOf(".")); + } + return artifactName; + } + + public static void updateDescription(String newDescription, ArtifactInfo artefact) throws Exception{ + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + DeploymentArtifactPage.clickEditArtifact(artefact.getArtifactLabel()); + artifactPopup.insertDescription(newDescription); + artifactPopup.clickDoneButton(); + } + + public static List getDeploymentArtifactsNamesWorkSpace() { + return GeneralUIUtils.getWebElementListText(GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue())); + } + + //Get Artifact Type by Artifact Name. + public static String getArtifactType(String artifactName){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.TYPE.getValue()+artifactName).getText(); + } + + public static List getHeatParametersInUI(String dataTestId){ + Listelements; + ListNames=new ArrayList<>(); + elements=GeneralUIUtils.getWebElementsListByContainTestID(dataTestId); + for (WebElement webElement : elements) { + String attributevalue=webElement.getAttribute("data-tests-id"); + Names.add(attributevalue.replace("heatParameterName_", "")); + } + return Names; + } + + public static void searchBoxEnv(String parameterName) { + GeneralUIUtils.getWebElementByContainsClassName("w-sdc-env-search-input").sendKeys(parameterName); + } + + public static void clearSearchBoxEnv() { + GeneralUIUtils.getWebElementByContainsClassName("w-sdc-env-search-input").clear(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentPage.java new file mode 100644 index 0000000000..5ee85e099e --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentPage.java @@ -0,0 +1,239 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collector; +import java.util.stream.Collectors; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.DeploymentScreen; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import static org.testng.Assert.assertTrue; + + +import com.aventstack.extentreports.Status; + +public class DeploymentPage { + + public DeploymentPage() { + super(); + } + + public static List getGroupMembersList(String instanceName) { + List propertyRows = null; + clickOnModuleName(instanceName); + propertyRows = getVisibleMembers(); + return propertyRows; + } + + public static void clickOnModuleName(String instanceName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", instanceName)); + GeneralUIUtils.clickOnElementByText(instanceName); + GeneralUIUtils.ultimateWait(); + } + + public static List getVisibleMembers() { + List instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='hierarchy-module-member-list']")); + for (WebElement instance : instancesFromTable){ + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")){ + return instance.findElements(By.cssSelector("div[class^='expand-collapse-sub-title']")); + } + } + return null; + } + + public static void clickOnProperties() throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Properties button")); + GeneralUIUtils.clickOnElementByCSS(DataTestIdEnum.DeploymentScreen.BUTTON_PROPERTIES.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnArtifacts() throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Artifacts button")); + GeneralUIUtils.clickOnElementByCSS(DataTestIdEnum.DeploymentScreen.BUTTON_ARTIFACTS.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnSaveButton(){ + clickInDeployment(DataTestIdEnum.DeploymentScreen.SAVE); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("popover-inner")); + } + + public static void clickOnCancelButton(){ + clickInDeployment(DataTestIdEnum.DeploymentScreen.CANCEL); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("popover-inner")); + } + + public static void clickOnXIcon(){ + clickInDeployment(DataTestIdEnum.DeploymentScreen.X_BUTTON); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("popover-inner")); + } + + public static void clickOnEditIcon(){ + clickInDeployment(DataTestIdEnum.DeploymentScreen.PENCIL_ICON); + } + + public static void clickOnProperty(WebElement property) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s propertie ...", property.getText())); + property.click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.POPUP_FORM.getValue()); + } + + private static void clickInDeployment(DataTestIdEnum.DeploymentScreen element){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s ...", element.getValue())); + GeneralUIUtils.clickOnElementByTestId(element.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static List getPropertyNames() throws Exception{ + clickOnProperties(); + return GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.PROPERTY_NAMES.getValue()); + } + + public static List getArtifactNames() throws Exception{ + clickOnArtifacts(); + return GeneralUIUtils.getInputElements(DataTestIdEnum.DeploymentScreen.ARTIFACT_NAME.getValue()); + } + + public static String updateModuleName(String currentModuleName, String newModuleName) throws Exception { + GeneralUIUtils.ultimateWait(); + ResourceUIUtils.clickOnElementByText(currentModuleName, null); + GeneralUIUtils.ultimateWait(); + clickOnEditIcon(); + WebElement moduleNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.NAME_INPUT.getValue()); + String oldModuleName = moduleNameField.getAttribute("value"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating %s module name ...", currentModuleName)); + moduleNameField.clear(); + GeneralUIUtils.ultimateWait(); + moduleNameField.sendKeys(newModuleName); + GeneralUIUtils.ultimateWait(); + clickOnSaveButton(); + String newReconstructedModuleName = reconstructModuleName(currentModuleName.split("\\.\\."), newModuleName); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Name of element instance changed from %s to %s", currentModuleName, newReconstructedModuleName)); + return oldModuleName; + } + + public static String reconstructModuleName(String[] splittedName, String middleName){ + int i = 0; + StringBuilder builder = new StringBuilder(); + for(String s : splittedName) { + if (i == 1){ + builder.append(middleName); + } else { + builder.append(s); + } + if (i < 2 ){ + builder.append(".."); + } + i++; + } + return builder.toString(); + } + + public static List getVisibleModulesService() { + List instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='hierarchy-modules-list']")); + for (WebElement instance : instancesFromTable){ + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")){ + return instance.findElements(By.cssSelector("span[class^='expand-collapse-title-text']")); + } + } + return null; + } + + public static List getInstanceModulesList(String instanceName) { + List propertyRows = null; + ResourceUIUtils.clickOnElementByText(instanceName, null); + GeneralUIUtils.ultimateWait(); + propertyRows = getVisibleModulesService(); + return propertyRows; + } + + public static String getGroupVersion() throws Exception{ + return GeneralUIUtils.getElementsByCSS("div[data-tests-id='selected-module-version']").get(0).getText(); + } + + public static String getModuleID() throws Exception{ + return GeneralUIUtils.getElementsByCSS("div[data-tests-id='selected-module-group-uuid'] span[class^='small-font']").get(0).getText(); + } + + public static Map> collectMetaDataFromUI() throws Exception{ + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + Map> deploymentViewMetaData = new HashMap>(); + List moduleRowsFromTable = GeneralUIUtils.getElementsByCSS("span[class^='expand-collapse-title-text']"); + for(WebElement moduleRow :moduleRowsFromTable){ + HashMap tempGroupMap = new HashMap(); + String moduleRowText = moduleRow.getText(); + GeneralUIUtils.clickOnElementByText(moduleRowText); + tempGroupMap.put("moduleID", getModuleID()); + tempGroupMap.put("version", DeploymentPage.getGroupVersion().split(":")[1].trim()); + deploymentViewMetaData.put(moduleRowText.split("\\.\\.")[1], tempGroupMap); + GeneralUIUtils.clickOnElementByText(moduleRowText); + } + return deploymentViewMetaData; + } + + public static void updateAndCancel(String newModuleName, DataTestIdEnum.DeploymentScreen buttonToClick){ + WebElement moduleNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.NAME_INPUT.getValue()); + String oldModuleName = moduleNameField.getAttribute("value"); + moduleNameField.clear(); + GeneralUIUtils.ultimateWait(); + moduleNameField.sendKeys(newModuleName); + GeneralUIUtils.ultimateWait(); + if (buttonToClick.equals(DataTestIdEnum.DeploymentScreen.X_BUTTON)) + clickOnXIcon(); + else + clickOnCancelButton(); + } + + public static String getPropertyValueFromPropertiesList(String property) throws InterruptedException{ + List propertyDataElements = GeneralUIUtils.getElementsByCSS("div[class^='list-item property-data']"); + for(WebElement propertyDataElement: propertyDataElements){ + WebElement propertyNameElement = GeneralUIUtils.getElementfromElementByCSS(propertyDataElement, DeploymentScreen.PROPERTY_NAMES.getValue()); + if (propertyNameElement.getText().equals(property)){ + WebElement propertyValueElement = GeneralUIUtils.getElementfromElementByCSS(propertyDataElement, String.format("div[data-tests-id='%s']", DeploymentScreen.PROPERTY_SCHEMA_TYPE.getValue())); + return propertyValueElement.getText().trim().split(":")[1].trim(); + } + } + return null; + } + + public static List getPropertyErrorValidationMessdge() throws Exception{ + List propertyErrorElements = GeneralUIUtils.getElementsByCSS("div[class='input-error'] span[class='ng-scope']"); + return propertyErrorElements; + } + + public static boolean isPropertySaveButtonDisabled(){ + WebElement saveButtonElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.SAVE.getValue()); + return GeneralUIUtils.isElementDisabled(saveButtonElement); + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java new file mode 100644 index 0000000000..04e3a8bb28 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java @@ -0,0 +1,160 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; +import java.util.function.Supplier; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class GeneralPageElements { + + public GeneralPageElements() { + super(); + } + + public static ResourceLeftMenu getLeftMenu() { + return new ResourceLeftMenu(); + } + + public static void clickOKButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the OK button"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.waitForLoader(); + } + + public static void clickCreateButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CREATE/UPDATE button."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + ExtentTestActions.log(Status.INFO, "Succeeded."); + } + + public static void clickCreateButton(int timeout) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CREATE/UPDATE button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), timeout); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void clickUpdateButton(){ + clickCreateButton(); + } + + public static void clickCheckinButton(String componentName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CHECKIN button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue()).sendKeys("Checkin " + componentName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue(), 60); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSubmitForTestingButton(String componentName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the submiting for testing button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.SUBMIT_FOR_TESTING_BUTTON.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.SUMBIT_FOR_TESTING_MESSAGE.getValue()).sendKeys("Submit for testing " + componentName); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue(), 60); + GeneralUIUtils.ultimateWait();; + } + + public static void clickCheckoutButton() throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on CHECKOUT button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CHECKOUT_BUTTON.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickDeleteVersionButton() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on DELETE VERSION button ..."); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.DELETE_VERSION_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.OK.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickRevertButton() throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on REVERT button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.REVERT_BUTTON.getValue()); + } + + public static String getLifeCycleState() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()).getText(); + } + + public static void selectVersion(String version) { + GeneralUIUtils.getSelectList(version, DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static List getElemenetsFromTable() { + GeneralUIUtils.ultimateWait();; + return GeneralUIUtils.getElemenetsFromTable(By.className("flex-container")); + } + + public static boolean checkElementsCountInTable(int expectedElementsCount) { + return checkElementsCountInTable(expectedElementsCount, () -> getElemenetsFromTable()); + } + + + public static void clickTrashButtonAndConfirm() throws InterruptedException{ + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on TRASH button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.DELETE_VERSION_BUTTON.getValue()); + clickOKButton(); + } + + public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier> func) { + SetupCDTest.getExtendTest().log(Status.INFO, "Checking the number of elements in the table; should be " + (expectedElementsCount - 1)); +// int maxWaitingPeriodMS = 10*1000; +// int napPeriodMS = 200; +// int sumOfWaiting = 0; +// List elements = null; +// boolean isKeepWaiting = false; +// while (!isKeepWaiting) { +// GeneralUIUtils.sleep(napPeriodMS); +// sumOfWaiting += napPeriodMS; +// elements = func.get(); +// isKeepWaiting = (expectedElementsCount == elements.size()); +// if (sumOfWaiting > maxWaitingPeriodMS) +// return false; +// } + GeneralUIUtils.ultimateWait(); + return true; + } + + public static void clickDeleteFile() throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on delete file X-button ..."); + GeneralUIUtils.clickOnAreaJS(GeneralUIUtils.getWebElementBy + (By.cssSelector("div[class='i-sdc-form-file-upload-x-btn']"))); + GeneralUIUtils.ultimateWait();; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java new file mode 100644 index 0000000000..ff964e3a01 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java @@ -0,0 +1,46 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +import com.aventstack.extentreports.Status; + +public class GovernorOperationPage { + + public GovernorOperationPage() { + super(); + } + + public static void approveSerivce(String serviceName) { + SetupCDTest.getExtendTest().log(Status.INFO, "Approving the distrbution of the service " + serviceName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("service " + serviceName + " tested successfuly"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java new file mode 100644 index 0000000000..84451dc905 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java @@ -0,0 +1,109 @@ +/*- + * ============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.ci.tests.pages; + +import java.io.File; +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.MainMenuButtonsFromInsideFrame; +import org.openecomp.sdc.ci.tests.utilities.DownloadManager; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +public class HomePage extends GeneralPageElements { + + public HomePage() { + super(); + } + + public static void showVspRepository(){ + GeneralUIUtils.waitForElementInVisibilityBy(By.className("ui-notification"), 30); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.MainMenuButtons.REPOSITORY_ICON.getValue()); + } + + public static boolean searchForVSP(String vspName){ + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ImportVfRepository.SEARCH.getValue()).sendKeys(vspName); + return checkElementsCountInTable(2); + } + + public static void importVSP(String vspName){ + HomePage.showVspRepository(); + boolean vspFound = HomePage.searchForVSP(vspName); + if (vspFound){ + List elemenetsFromTable = getElemenetsFromTable(); +// GeneralUIUtils.waitForLoader(); + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30); + WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); + findElement.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(60*10); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + } + + + public static boolean navigateToHomePage() { + try{ + System.out.println("Searching for reporsitory icon."); + WebElement repositoryIcon = GeneralUIUtils.getInputElement("repository-icon"); + if (repositoryIcon != null){ + return true; + } + else{ + GeneralUIUtils.ultimateWait(); + List homeButtons = GeneralUIUtils.getElemenetsFromTable(By.xpath("//a[contains(.,'HOME')]")); + if (homeButtons.size() != 0){ + for (WebElement home : homeButtons){ + if (home.isDisplayed()){ + home.click(); + System.out.println("Clicked on home button"); + break; + } + } + GeneralUIUtils.closeErrorMessage(); + WebElement homeButton = GeneralUIUtils.getInputElement(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue()); + return homeButton.isDisplayed(); + } + + } + } + catch(Exception innerException){ + System.out.println("Can't click on home button."); + return false; + } + return false; + } + + public static File downloadVspCsarToDefaultDirectory(String vspName) throws Exception { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, ""); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + return latestFilefromDir; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java new file mode 100644 index 0000000000..fd9befa148 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/IconPage.java @@ -0,0 +1,51 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +public class IconPage extends GeneralPageElements { + + public IconPage() { + super(); + } + + public static void clickOnIcon(ResourceCategoryEnum iconName) { + GeneralUIUtils.getWebElementByTestID(iconStringBuilder(iconName) + DataTestIdEnum.ServiceMetadataEnum.ICON.getValue()) + .click(); + } + + private static String iconStringBuilder(ResourceCategoryEnum icon) { + String iconName = icon.getSubCategory(); + String[] splitedIconName = iconName.split(" "); + splitedIconName[0] = splitedIconName[0].toLowerCase(); + + StringBuilder sb = new StringBuilder(); + for (String word : splitedIconName) { + sb.append(word); + } + + return sb.toString(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java new file mode 100644 index 0000000000..9916292e5b --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InformationalArtifactPage.java @@ -0,0 +1,74 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class InformationalArtifactPage extends DeploymentArtifactPage { + + public InformationalArtifactPage() { + super(); + } + + public static void clickAddNewArtifact() { + addNewArtifact(ArtifactGroupTypeEnum.INFORMATIONAL); + } + + public static String getArtifactDescription(String artifactLabel) throws Exception { + InformationalArtifactPage.clickOnArtifact(artifactLabel); + String artifactDesc = GeneralUIUtils.getWebElementByTestID( + artifactLabel + DataTestIdEnum.ArtifactPageEnum.GET_INFORMATIONAL_ARTIFACT_DESCRIPTION.getValue()) + .getText(); + InformationalArtifactPage.clickOnArtifact(artifactLabel); // close artifact + return artifactDesc; + } + + public static List getElemenetsFromTable() { + return GeneralUIUtils.getWebElementsListByTestID("InformationalArtifactRow"); + } + + public static WebElement clickOnArtifact(String artifactLabel) throws Exception { + try{ + WebElement artifact = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel); + artifact.click(); + GeneralUIUtils.waitForLoader(); + return artifact; + } + catch(Exception e){ + throw new Exception("Artifact " + artifactLabel + "is not found"); + } + } + + + public static void clickDeleteArtifact(String artifactLabel) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Deleting %s Artefact ",artifactLabel)); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + artifactLabel).click(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InputsPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InputsPage.java new file mode 100644 index 0000000000..b977b263a0 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/InputsPage.java @@ -0,0 +1,158 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; +import java.util.stream.Collectors; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InputsScreenService; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.TestException; + +import com.aventstack.extentreports.Status; + +public class InputsPage extends GeneralPageElements { + + public InputsPage() { + super(); + + } + + public static List getInstancePropertiesList(String instanceName) { + List propertyRows = null; + GeneralUIUtils.clickOnElementByText(instanceName); + GeneralUIUtils.ultimateWait(); + propertyRows = getVisibleProperites(); + return propertyRows; + } + + public static List getVisibleProperites() { + List instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='vf-instance-list']")); + for (WebElement instance : instancesFromTable){ + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")){ + return instance.findElements(By.className("property-row")); + } + } + return null; + } + + public static void addInputToService(String VFInstanceName, String propertyName) throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding property %s from VF instance %s to Service", propertyName, VFInstanceName)); + List instaceInputs = getInstanceInputsList(VFInstanceName); + for(WebElement instancInput: instaceInputs){ + String actualPropertyName = instancInput.findElement(By.className("title-text")).getText(); + if (actualPropertyName.equals(propertyName) && clickOnVFInputCheckbox(instancInput)){ + clickOnAddInputButton(); + } + } + } + + public static List getInstanceInputsList(String instanceName) { + List inputRows = null; + GeneralUIUtils.clickOnElementByText(instanceName); + GeneralUIUtils.ultimateWait(); + inputRows = getVisibleInputs(inputRows); + return inputRows; + } + + public static List getVisibleInputs(List inputRows) { + List instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='vf-instance-list']")); + for (WebElement instance : instancesFromTable){ + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")){ + inputRows = instance.findElements(By.className("input-row")); + break; + } + } + return inputRows; + } + + public static void clickOnAddInputButton(){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Add Input aka Greater than symbol button")); + GeneralUIUtils.clickOnElementByTestId(InputsScreenService.ADD_SELECTED_INPUTS_BTN.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static boolean clickOnVFInputCheckbox(WebElement instancInput){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on VF instance input checkbox")); + instancInput.findElement(By.className("tlv-checkbox-label")).click(); + GeneralUIUtils.ultimateWait(); + return instancInput.findElement(By.className("tlv-checkbox-i")).getAttribute("class").contains("ng-not-empty"); + } + + public static WebElement getServiceInput(String VFInstanceName, String propertyName) throws Exception{ + String expectedInputName = String.format("%s_%s", VFInstanceName.replace(" ", "").toLowerCase(), propertyName); + List inputsFromTable = GeneralUIUtils.getElementsByCSS(InputsScreenService.SERVICE_INPUT_ROW.getValue()); + for(WebElement inputFromTable: inputsFromTable){ + String actualInputName = inputFromTable.findElement(By.className("title-text")).getText(); + if(actualInputName.equals(expectedInputName)){ + return inputFromTable; + } + } + throw new TestException(String.format("%s input don't exist", expectedInputName)); + } + + public static void deleteServiceInput(String VFInstanceName, String propertyName) throws Exception{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Deleting property %s in VF instance %s ", propertyName, VFInstanceName)); + WebElement serviceInput = getServiceInput(VFInstanceName, propertyName); + serviceInput.findElement(By.cssSelector(InputsScreenService.DELETE_INPUT_BTN.getValue())).click(); + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on OK button ")); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.OK.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static List getVFCInstancesNamesFromTable() throws Exception{ + WebElement inputsTable = getInputsTable("VFC "); + return inputsTable.findElements(By.cssSelector("span[class^='title-text']")).stream(). + map(e -> e.getText()). + collect(Collectors.toList()); + } + + public static WebElement getInputsTable(String tableName) throws Exception{ + List tableElements = GeneralUIUtils.getElementsByCSS("div.table"); + for(WebElement tableElement: tableElements){ + String tableTitle = GeneralUIUtils.getElementfromElementByCSS(tableElement, "div.table-header").getText(); + if (tableTitle.contains(tableName)){ + return tableElement; + } + } + throw new TestException(String.format("Can't find %s table", tableName)); + } + + public static void clickOnProperty(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on property %s ", propertyName)); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_NAME.getValue() + propertyName); + GeneralUIUtils.ultimateWait(); + } + + + + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java new file mode 100644 index 0000000000..82171b8de9 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OpsOperationPage.java @@ -0,0 +1,156 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.aventstack.extentreports.Status; + +public class OpsOperationPage { + + public OpsOperationPage() { + super(); + } + + public static void distributeService() { + SetupCDTest.getExtendTest().log(Status.INFO, "Distributing"); + clickOnButton(DataTestIdEnum.DistributionChangeButtons.DISTRIBUTE); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.MONITOR.getValue()); + } + + public static void displayMonitor() { + GeneralUIUtils.moveToStep(StepsEnum.MONITOR); + } + + public static void re_distributeService() { + SetupCDTest.getExtendTest().log(Status.INFO, "Redistributing..."); + clickOnButton(DataTestIdEnum.DistributionChangeButtons.RE_DISTRIBUTE); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.MONITOR.getValue()); + } + + private static void clickOnButton(DataTestIdEnum.DistributionChangeButtons button) { + GeneralUIUtils.getWebElementByTestID(button.getValue()).click(); + GeneralUIUtils.waitForLoader(); + } + + public static List getRowsFromMonitorTable() { + SetupCDTest.getExtendTest().log(Status.INFO, "Counting the rows from the distribution table"); + GeneralPageElements.checkElementsCountInTable(1, () -> GeneralUIUtils.getWebElementsListByTestID("ditributionTable")); + List distributionRecords = GeneralUIUtils.getWebElementsListByTestID("ditributionTable"); + List findElements = distributionRecords.get(0).findElements(By.className("w-sdc-distribute-parent-block")); + return findElements; + } + + public static void showDistributionStatus(int rowIndex) { + GeneralUIUtils.getWebElementByTestID("ShowRecordButton_" + String.valueOf(rowIndex)).click(); + GeneralUIUtils.waitForLoader(); + } + + public static String getTotalArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("totalArtifacts_" + String.valueOf(rowIndex)).getText(); + } + + public static String getNotifiedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("notified_" + String.valueOf(rowIndex)).getText(); + } + + public static String getDownloadedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("downloaded_" + String.valueOf(rowIndex)).getText(); + } + + public static String getDeployedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("deployed_" + String.valueOf(rowIndex)).getText(); + } + + public static String getNotNotifiedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("NotNotified_" + String.valueOf(rowIndex)).getText(); + } + + public static String getErrorsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("errors_" + String.valueOf(rowIndex)).getText(); + } + + public static void clickRefreshTableButton(int rowIndex) { + GeneralUIUtils.getWebElementByTestID("refreshButton").click(); + // wait until total artifacts field disappear + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 90); + wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + "totalArtifacts_" + String.valueOf(rowIndex) + "']"))); + } + + public static void waitUntilArtifactsDistributed(int rowIndex) throws Exception { + waitUntilArtifactsDistributed("0", 0); + } + + public static void waitUntilArtifactsDistributed(String expectedArtifactsSum, int rowIndex) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Waiting until all artifacts are distributed"); + boolean isKeepWaiting = true; + int maxWaitingPeriodMS = 5 * 60 * 1000; + int sumWaitingTime = 0; + int napPeriod = 10000; + while (isKeepWaiting) { + showDistributionStatus(rowIndex); + String actualTotalArtifactsSize = getTotalArtifactsSum(rowIndex); + String actualNotifiedArtifactsSize = getNotifiedArtifactsSum(rowIndex); + String actualDownloadedArtifactsSize = getDownloadedArtifactsSum(rowIndex); + String actualDeployedArtifactsSize = getDeployedArtifactsSum(rowIndex); + String actualNotNotifedArtifactsSize = getNotNotifiedArtifactsSum(rowIndex); + isKeepWaiting = !actualTotalArtifactsSize.equals(actualDownloadedArtifactsSize) + || !actualTotalArtifactsSize.equals(actualNotifiedArtifactsSize) + || !actualTotalArtifactsSize.equals(actualDeployedArtifactsSize) + || actualTotalArtifactsSize.equals("0") || actualDownloadedArtifactsSize.equals("0") + || actualNotifiedArtifactsSize.equals("0") || actualDeployedArtifactsSize.equals("0"); + + if (isKeepWaiting) { + + if (Integer.parseInt(actualNotNotifedArtifactsSize) > 1) { + SetupCDTest.getExtendTest().log(Status.INFO, "Some artifacts are not notified"); + isKeepWaiting = false; + throw new Exception("Some artifacts are not notified..."); + } + + GeneralUIUtils.sleep(napPeriod); + sumWaitingTime += napPeriod; + + if (sumWaitingTime > maxWaitingPeriodMS) { + SetupCDTest.getExtendTest().log(Status.INFO, "Not all artifacts are displayed"); + isKeepWaiting = false; + throw new Exception(String.format("Not all artifacts are displayed withing %s seconds", + String.valueOf(maxWaitingPeriodMS / 1000))); + } + + clickRefreshTableButton(rowIndex); + } + } + + SetupCDTest.getExtendTest().log(Status.INFO, "All artifacts were successfully distributed"); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductGeneralPage.java new file mode 100644 index 0000000000..3bec4f636c --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductGeneralPage.java @@ -0,0 +1,119 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.ArrayList; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +/** + * @author al714h + * + */ + +public class ProductGeneralPage extends ResourceGeneralPage { + + public ProductGeneralPage() { + super(); + } + + public static ProductLeftMenu getProductLeftMenu() { + return new ProductLeftMenu(); + } + + public static void defineName(String productName) { + WebElement productNameTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.PRODUCT_NAME.getValue()); + productNameTextbox.clear(); + productNameTextbox.sendKeys(productName); + } + + public static void defineFullName(String productFullName) { + WebElement productFullNameTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.FULL_NAME.getValue()); + productFullNameTextbox.clear(); + productFullNameTextbox.sendKeys(productFullName); + } + + public static void defineProjectCode(String pmat) { + WebElement pmattTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.PROJECT_CODE.getValue()); + pmattTextbox.clear(); + pmattTextbox.sendKeys(pmat); + } + + public static String getPmattText(){ + return getPmattField().getAttribute("value"); + } + + public static String[] getTags(){ + return ResourceGeneralPage.getElementsFromTagsTable().stream().map(WebElement::getText).toArray(String[]::new); + } + + private static WebElement getPmattField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.PROJECT_CODE.getValue()); + } + + public static void deleteOldTags(ProductReqDetails product){ + // Delete tag elements + int i = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-delete").size(); + while (i > 0){ + GeneralUIUtils.getWebElementByTestID("i-sdc-tag-delete").click(); + i--; + } + + product.setTags(new ArrayList()); + } + + public static void clickAddWorkflow (){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding workflow...")); + GeneralUIUtils.clickOnElementByText("Add Workflow"); + } + + public static void fillAndAddNewWorkflow(String name, String description ) throws InterruptedException{ + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling name field with %s", name)); + insertText(name, "label + input"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling description filed with %s", name)); + insertText(description,"label + textarea"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking save button ")); + clickSave(); + } + + public static void insertText(String artifactDescriptoin, String element) throws InterruptedException { + GeneralUIUtils.getElementsByCSS("div[class='modal-content']"); + WebElement artifactDescriptionTextbox = GeneralUIUtils.getWebElementBy(By.cssSelector(element)); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSave() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Save button")); + GeneralUIUtils.clickOnElementByText("Save"); + GeneralUIUtils.ultimateWait(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductLeftMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductLeftMenu.java new file mode 100644 index 0000000000..2972e59618 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ProductLeftMenu.java @@ -0,0 +1,48 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +/** + * @author al714h + * + */ + +public class ProductLeftMenu implements ComponentLeftMenu { + + public void moveToGeneralScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.GENERAL); + } + + public void moveToIconScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ICON); + } + + public void moveToCompositionScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION); + } + + public void moveToHierarchyScreen() { + GeneralUIUtils.moveToStep(StepsEnum.HIERARCHY); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java new file mode 100644 index 0000000000..4899ab15af --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesPage.java @@ -0,0 +1,74 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class PropertiesPage extends GeneralPageElements { + + public PropertiesPage() { + super(); + } + + public static List getElemenetsFromTable() { + return GeneralUIUtils.getInputElements(DataTestIdEnum.PropertiesPageEnum.PROPERTY_ROW.getValue()); + } + + public static void clickAddPropertyArtifact() { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.ADD_NEW_PROPERTY.getValue()).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.POPUP_FORM.getValue()); + } + + public static void clickEditPropertyArtifact(String propertyName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.EDIT_PROPERTY.getValue() + propertyName).click(); + } + + public static void clickDeletePropertyArtifact(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Delete property %s", propertyName)); + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propertyName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPageEnum.DELETE_PROPERTY.getValue() + propertyName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.waitForElementInVisibilityBy(By.className("w-sdc-modal-confirmation"), 10); + } + + public static void clickOnProperty(String propertyName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propertyName).click(); + } + + public static PropertyPopup getPropertyPopup() { + return new PropertyPopup(); + } + + public static boolean verifyTotalProperitesField(int count){ + String totalPropertiesCount = GeneralUIUtils.getWebElementBy(By.id("properties-count")).getText(); + return ("Total Properties: " + count).equals(totalPropertiesCount); + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java new file mode 100644 index 0000000000..5052406d4e --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertyPopup.java @@ -0,0 +1,111 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.NoSuchElementException; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +import com.aventstack.extentreports.Status; + +public class PropertyPopup { + + + public PropertyPopup() { + } + + public boolean getPopupForm(){ + return GeneralUIUtils.waitForElementInVisibilityByTestId(DataTestIdEnum.PropertiesPageEnum.POPUP_FORM.getValue(), 60); + } + + public void insertPropertyName(String name) { + WebElement propertyNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_NAME.getValue()); + propertyNameField.clear(); + propertyNameField.sendKeys(name); + } + + public void insertPropertyDefaultValue(String value) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Inserting to property default value: %s ", value)); + WebElement selectedType = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_TYPE.getValue())).getFirstSelectedOption(); + if(selectedType.getText().equals("boolean")) { + GeneralUIUtils.getSelectList(value, DataTestIdEnum.PropertiesPopupEnum.PROPERTY_BOOLEAN_VALUE.getValue()); + } else { + WebElement propertyValue = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_VALUE.getValue()); + propertyValue.clear(); + propertyValue.sendKeys(value); + } + + GeneralUIUtils.ultimateWait(); + } + + public void insertPropertyDescription(String description) { + WebElement propertyDescription = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_DESCRIPTION.getValue()); + propertyDescription.clear(); + propertyDescription.sendKeys(description); + } + + public void selectPropertyType(String propertyType) { + boolean isEntrySchemaDisplayed; + try{ + GeneralUIUtils.getSelectList(propertyType, DataTestIdEnum.PropertiesPopupEnum.PROPERTY_TYPE.getValue()); + isEntrySchemaDisplayed = GeneralUIUtils.getDriver().findElement(By.xpath(DataTestIdEnum.PropertiesPopupEnum.ENTRY_SCHEMA.getValue())).isDisplayed(); + if (isEntrySchemaDisplayed){ + PropertiesPage.getPropertyPopup().selectEntrySchema(propertyType); + } + } + catch(NoSuchElementException e){ + + } + } + + public void selectEntrySchema(String propertyType){ + GeneralUIUtils.getSelectList(propertyType, DataTestIdEnum.PropertiesPopupEnum.ENTRY_SCHEMA.getValue()); + } + + public void clickAdd() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.ADD.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public void clickSave() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.SAVE.getValue()); + getPopupForm(); + } + + public void clickCancel() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.CANCEL.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public void clickDone() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.DONE.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public void selectPropertyRadioButton(String propertyName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_RADIO_BUTTON_CONTAINER.getValue() + propertyName).findElement(By.className(DataTestIdEnum.PropertiesPopupEnum.RADIO_BUTTON_CLASS.getValue())).click(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java new file mode 100644 index 0000000000..1412a4b969 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceGeneralPage.java @@ -0,0 +1,177 @@ +/*- + * ============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.ci.tests.pages; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; + + +public class ResourceGeneralPage extends GeneralPageElements { + + public ResourceGeneralPage() { + super(); + } + + public static WebElement getNameField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.RESOURCE_NAME.getValue()); + } + + public static WebElement getDescriptionField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.DESCRIPTION.getValue()); + } + + public static String getCategoryDataTestsIdAttribute() { + return DataTestIdEnum.ResourceMetadataEnum.CATEGORY.getValue(); + } + + public static WebElement getVendorNameField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.VENDOR_NAME.getValue()); + } + + public static WebElement getVendorReleaseField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.VENDOR_RELEASE.getValue()); + } + + public static WebElement getTagsField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.TAGS.getValue()); + } + + public static WebElement getContactIdField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.CONTACT_ID.getValue()); + } + + /***************************************************************/ + + public static String getNameText() { + return getNameField().getAttribute("value"); + } + + public static void defineName(String resourceName) { + WebElement resourceNameTextbox = getNameField(); + resourceNameTextbox.clear(); + resourceNameTextbox.sendKeys(resourceName); + } + + public static void defineNameWithPaste() { + defineTextBoxWithPaste(getNameField()); + } + + public static String getDescriptionText() { + return getDescriptionField().getAttribute("value"); + } + + public static void defineDescription(String description) { + WebElement descriptionTextbox = getDescriptionField(); + descriptionTextbox.clear(); + descriptionTextbox.sendKeys(description); + } + + public static void defineDescriptionWithPaste() { + defineTextBoxWithPaste(getDescriptionField()); + } + + public static String getVendorNameText() { + return getVendorNameField().getAttribute("value"); + } + + public static void defineVendorName(String vendorName) { + WebElement vendorNameTextbox = getVendorNameField(); + vendorNameTextbox.clear(); + vendorNameTextbox.sendKeys(vendorName); + } + + public static void defineVendorNameWithPaste() { + defineTextBoxWithPaste(getVendorNameField()); + } + + public static String getVendorReleaseText() { + return getVendorReleaseField().getAttribute("value"); + } + + public static void defineVendorRelease(String vendorRelease) { + WebElement vendorReleaseTextbox = getVendorReleaseField(); + vendorReleaseTextbox.clear(); + vendorReleaseTextbox.sendKeys(vendorRelease); + } + + public static void defineVendorReleaseWithPaste() { + defineTextBoxWithPaste(getVendorReleaseField()); + } + + public static void defineTag(String resourceTags) { + WebElement tagTextbox = getTagsField(); + tagTextbox.clear(); + tagTextbox.sendKeys(resourceTags); + tagTextbox.sendKeys(Keys.ENTER); + } + + public static void defineTagsList(ComponentReqDetails component, String[] tags) { + List taglist = new ArrayList(); + WebElement resourceTagsTextbox = getTagsField(); + for (String tag : tags) { + resourceTagsTextbox.clear(); + resourceTagsTextbox.sendKeys(tag); + GeneralUIUtils.sleep(500); + resourceTagsTextbox.sendKeys(Keys.ENTER); + taglist.add(tag); + } + component.getTags().addAll(taglist); + } + + public static void defineTagsListWithPaste() { + List taglist = new ArrayList(); + WebElement resourceTagsTextbox = getTagsField(); + defineTextBoxWithPaste(resourceTagsTextbox); + resourceTagsTextbox.sendKeys(Keys.ENTER); + } + + public static void defineCategory(String category) { + GeneralUIUtils.getSelectList(category, getCategoryDataTestsIdAttribute()); + } + + public static String getContactIdText() { + return getContactIdField().getAttribute("value"); + } + + public static void defineContactId(String userId) { + WebElement contactIdTextbox = getContactIdField(); + contactIdTextbox.clear(); + contactIdTextbox.sendKeys(userId); + GeneralUIUtils.waitForLoader(); + } + + public static List getElementsFromTagsTable(){ + return GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.ResourceMetadataEnum.TAGS_TABLE.getValue()); + } + + public static void defineTextBoxWithPaste(WebElement textBox) { + textBox.clear(); + textBox.sendKeys(Keys.CONTROL + "v"); + GeneralUIUtils.ultimateWait(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java new file mode 100644 index 0000000000..a128aefdc8 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftMenu.java @@ -0,0 +1,67 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +public class ResourceLeftMenu implements ComponentLeftMenu { + + public void moveToGeneralScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.GENERAL); + } + + public void moveToIconScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ICON); + } + + public void moveToDeploymentArtifactScreen() { + GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_ARTIFACT); + } + + public void moveToInformationalArtifactScreen() { + GeneralUIUtils.moveToStep(StepsEnum.INFORMATION_ARTIFACT); + } + + public void moveToPropertiesScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.PROPERTIES); + } + + public void moveToCompositionScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION); + } + + public void moveToActivityLogScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ACTIVITY_LOG); + } + + public void moveToDeploymentViewScreen() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.DEPLOYMENT_VIEW); + } + + public void moveToToscaArtifactsScreen() { + GeneralUIUtils.moveToStep(StepsEnum.TOSCA_ARTIFACTS); + } + + public void moveToInputsScreen() { + GeneralUIUtils.moveToStep(StepsEnum.INPUTS); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java new file mode 100644 index 0000000000..0394978261 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.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.ci.tests.pages; + +import java.util.ArrayList; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class ServiceGeneralPage extends ResourceGeneralPage { + + public ServiceGeneralPage() { + super(); + } + + public static ServiceLeftMenu getServiceLeftMenu() { + return new ServiceLeftMenu(); + } + + public static void defineName(String serviceName) { + WebElement serviceNameTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.SERVICE_NAME.getValue()); + serviceNameTextbox.clear(); + serviceNameTextbox.sendKeys(serviceName); + } + + public static void defineProjectCode(String pmat) { + WebElement projectCodeTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue()); + projectCodeTextbox.clear(); + projectCodeTextbox.sendKeys(pmat); + } + + public static String getProjectCodeText(){ + return getProjectCodeField().getAttribute("value"); + } + + public static String[] getTags(){ + return ResourceGeneralPage.getElementsFromTagsTable().stream().map(WebElement::getText).toArray(String[]::new); + } + + private static WebElement getProjectCodeField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue()); + } + + public static void deleteOldTags(ServiceReqDetails service){ + // Delete tag elements + int i = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-delete").size(); + while (i > 0){ + GeneralUIUtils.getWebElementByTestID("i-sdc-tag-delete").click(); + i--; + } + + service.setTags(new ArrayList()); + } + + public static String getCategoryText() { + return GeneralUIUtils.getSelectedElementFromDropDown(getCategoryDataTestsIdAttribute()).getText(); + } + + public static void clickAddWorkflow (){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding workflow...")); + GeneralUIUtils.clickOnElementByText("Add Workflow"); + } + + public static void fillAndAddNewWorkflow(String name, String description ) throws InterruptedException{ + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling name field with %s", name)); + insertText(name, "label + input"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling description filed with %s", name)); + insertText(description,"label + textarea"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking save button ")); + clickSave(); + } + + public static void insertText(String artifactDescriptoin, String element) throws InterruptedException { + GeneralUIUtils.getElementsByCSS("div[class='modal-content']"); + WebElement artifactDescriptionTextbox = GeneralUIUtils.getWebElementBy(By.cssSelector(element)); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSave() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Save button")); + GeneralUIUtils.clickOnElementByText("Save"); + GeneralUIUtils.ultimateWait(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceLeftMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceLeftMenu.java new file mode 100644 index 0000000000..127ada2309 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceLeftMenu.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +public class ServiceLeftMenu implements ComponentLeftMenu { + + public void moveToManagmentWorkflow() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.MANAGEMENT_WORKFLOW); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java new file mode 100644 index 0000000000..d9ef375d17 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TesterOperationPage.java @@ -0,0 +1,101 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; + +import com.aventstack.extentreports.Status; + +public class TesterOperationPage { + + public TesterOperationPage() { + super(); + } + + public static void certifyComponent(String componentName) throws Exception{ + clickStartTestingButton(); + clickAccpetCertificationButton(componentName); + } + + public static void clickAccpetCertificationButton(String componentName) throws Exception { + ExtentTestActions.log(Status.INFO, "Accepting certifiction of " + componentName); + String actionDuration = GeneralUIUtils.getActionDuration(() -> + { + try { + clickAccpetCertificationButtonWithoutDuration(componentName); + } catch (Exception e) { + e.printStackTrace(); + } + }); + ExtentTestActions.log(Status.INFO, componentName + " is certifed", actionDuration); + + } + + public static void clickStartTestingButton() throws Exception{ + ExtentTestActions.log(Status.INFO, "Starting to test"); + String actionDuration = GeneralUIUtils.getActionDuration(() -> { + try { + clickStartTestingButtonWithoutDuration(); + } catch (Exception e) { + e.printStackTrace(); + } + }); + ExtentTestActions.log(Status.INFO, "Ready for certification", actionDuration); + } + + + private static void certifyComponentWithoutDuration(String componentName) throws Exception { + clickStartTestingButtonWithoutDuration(); + clickAccpetCertificationButtonWithoutDuration(componentName); + } + + + private static void clickAccpetCertificationButtonWithoutDuration(String componentName) throws Exception { + try{ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue()); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.ACCEP_TESTING_MESSAGE.getValue()).sendKeys(componentName + " tested successfuly"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.sleep(2000); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + } + catch (Exception e){ + throw new Exception("Accepting certification of " + componentName + " falied"); + } + } + + private static void clickStartTestingButtonWithoutDuration() throws Exception { + try{ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.START_TESTING.getValue()); +// GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue()); +// GeneralUIUtils.ultimateWait(); +// GeneralUIUtils.sleep(1000); + } + catch (Exception e){ + throw new Exception("Start testing falied"); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java new file mode 100644 index 0000000000..077ccacde1 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ToscaArtifactsPage.java @@ -0,0 +1,54 @@ +/*- + * ============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.ci.tests.pages; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; + +public class ToscaArtifactsPage extends DeploymentArtifactPage { + + public ToscaArtifactsPage() { + + } + + public static String getArtifactName(int row){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_NAME.getValue() + row).getText(); + } + + public static String getArtifactType(int row){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_TYPE.getValue() + row).getText(); + } + + public static String getArtifactVersion(int row){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_VERSION.getValue() + row).getText(); + } + + public static WebElement getArtifactDetails(int row){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_DETAILS.getValue() + row); + } + + public static void downloadCsar() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.DOWNLOAD_CSAR.getValue()); + GeneralUIUtils.ultimateWait(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java new file mode 100644 index 0000000000..e97f3feb62 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/UploadArtifactPopup.java @@ -0,0 +1,126 @@ +/*- + * ============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.ci.tests.pages; + +import java.io.File; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; +import org.testng.TestException; + +import com.aventstack.extentreports.Status; + +public class UploadArtifactPopup { + + boolean isCompositionPage; + + public UploadArtifactPopup(boolean isCompositionPage) { + super(); + this.isCompositionPage = isCompositionPage; + } + + public UploadArtifactPopup() { + super(); + } + + public WebElement getArtifactDescriptionWebElement(){ + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.ARTIFACT_DESCRIPTION.getValue()); + } + + public void loadFile(String path, String filename) { + final WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPopup.BROWSE.getValue()); +// browseWebElement.sendKeys(path + filename); + browseWebElement.sendKeys(path + File.separator + filename); + GeneralUIUtils.ultimateWait(); + +// if (!browseWebElement.getAttribute("value").equals(filename)) +// { +// throw new TestException("File named " + filename + " does not presented"); +// } + } + + + + public void insertDescription(String artifactDescriptoin) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Changing artifact description to: %s", artifactDescriptoin)); + WebElement artifactDescriptionTextbox = getArtifactDescriptionWebElement(); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + + GeneralUIUtils.ultimateWait();; + } + + public Select defineArtifactLabel(String requiredArtifactLabel) { + Select selectList = null; + WebElement artifactLabelWebElement = null; + +// if (isCompositionPage){ + artifactLabelWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.ARTIFACT_LABEL.getValue()); +// } +// else{ +// selectList = GeneralUIUtils.getSelectList("Create New Artifact", DataTestIdEnum.ArtifactPopup.ARTIFACT_LABEL.getValue()); +// artifactLabelWebElement = GeneralUIUtils.getDriver().findElement(By.name(DataTestIdEnum.ArtifactPopup.ARTIFACT_LABEL.getValue())); +// } + + artifactLabelWebElement.clear(); + artifactLabelWebElement.sendKeys(requiredArtifactLabel); + return selectList; + } + + public Select selectArtifactType(String artifactType) { + return GeneralUIUtils.getSelectList(artifactType, DataTestIdEnum.ArtifactPopup.ARTIFACT_TYPE.getValue()); + } + + public void clickDoneButton() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementInVisibilityBy(By.className("sdc-add-artifact"), 10); + } + + public void clickCancelButton() throws Exception { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.CANCEL_BUTTON.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementInVisibilityByTestId("sdc-add-artifact"); + } + +// public void clickUpdateButton() throws Exception { +// clickAddButton(); +// GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.UPDATE_BUTTON.getValue()).click(); +// GeneralUIUtils.waitForLoader(); +// GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("sdc-add-artifact"), 50); +// } + + public void insertURL(String artifactDescriptoin) throws Exception { + WebElement artifactDescriptionTextbox = getArtifactURLWebElement(); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox. sendKeys(artifactDescriptoin); + } + + public WebElement getArtifactURLWebElement(){ + return GeneralUIUtils.getWebElementBy(By.cssSelector((DataTestIdEnum.ArtifactPopup.URL.getValue()))); + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java new file mode 100644 index 0000000000..aa260ecc80 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java @@ -0,0 +1,110 @@ +/*- + * ============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.ci.tests.utilities; + +import java.util.concurrent.TimeUnit; + +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.support.ui.ExpectedCondition; + +import com.paulhammant.ngwebdriver.NgWebDriver; + +public class AdditionalConditions { + + public static ExpectedCondition jQueryAJAXCallsHaveCompleted() { + return new ExpectedCondition() { + @Override + public Boolean apply(WebDriver driver) { + return (Boolean) ((JavascriptExecutor)driver). + executeScript("return (window.jQuery!= null) && (jQuery.active === 0);"); + } + }; + } + + public static ExpectedCondition angularHasFinishedProcessing() { + return new ExpectedCondition() { + @Override + public Boolean apply(WebDriver driver) { +// String scriptJS = "return (window.angular !==undefined) &&" +// + " (angular.element(document).injector() !==undefined) &&" +// + " (angular.element(document).injector().get('$http').pendingRequests.length === 0)"; +// return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString()); + new NgWebDriver((JavascriptExecutor) driver).waitForAngularRequestsToFinish(); + return true; + } + }; + } + + public static ExpectedCondition pageLoadWait() { + return new ExpectedCondition() { + @Override + public Boolean apply(WebDriver driver) { + String scriptJS = + "try {\r\n" + + " if (document.readyState !== 'complete') {\r\n" + + " return false; // Page not loaded yet\r\n" + + " }\r\n" + + " if (window.jQuery) {\r\n" + + " if (window.jQuery.active) {\r\n" + + " return false;\r\n" + + " } else if (window.jQuery.ajax && window.jQuery.ajax.active) {\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " if (window.angular) {\r\n" + + " if (!window.qa) {\r\n" + + " // Used to track the render cycle finish after loading is complete\r\n" + + " window.qa = {\r\n" + + " doneRendering: false\r\n" + + " };\r\n" + + " }\r\n" + + " // Get the angular injector for this app (change element if necessary)\r\n" + + " var injector = window.angular.element('body').injector();\r\n" + + " // Store providers to use for these checks\r\n" + + " var $rootScope = injector.get('$rootScope');\r\n" + + " var $http = injector.get('$http');\r\n" + + " var $timeout = injector.get('$timeout');\r\n" + + " // Check if digest\r\n" + + " if ($rootScope.$$phase === '$apply' || $rootScope.$$phase === '$digest' || $http.pendingRequests.length !== 0) {\r\n" + + " window.qa.doneRendering = false;\r\n" + + " return false; // Angular digesting or loading data\r\n" + + " }\r\n" + + " if (!window.qa.doneRendering) {\r\n" + + " // Set timeout to mark angular rendering as finished\r\n" + + " $timeout(function() {\r\n" + + " window.qa.doneRendering = true;\r\n" + + " }, 0);\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " return true;\r\n" + + "} catch (ex) {\r\n" + + " return false;\r\n" + + "}"; + return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString()); + } + }; + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java new file mode 100644 index 0000000000..db621f3355 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java @@ -0,0 +1,57 @@ +/*- + * ============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.ci.tests.utilities; + +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.pages.AdminGeneralPage; + +public class AdminWorkspaceUIUtilies { + + + public static void createNewUser(String userId, UserRoleEnum userRole){ + AdminGeneralPage.getUserManagementTab().setNewUserBox(userId); + AdminGeneralPage.getUserManagementTab().selectUserRole(userRole); + AdminGeneralPage.getUserManagementTab().clickCreateButton(); +// AdminWorkspaceUIUtilies.highlightNewRow(); + } + + private static void highlightNewRow(){ + GeneralUIUtils.HighlightMyElement(AdminGeneralPage.getUserManagementTab().getRow(0)); + } + + public static void updateUserRole(int rowIndx, UserRoleEnum userRole) { + AdminGeneralPage.getUserManagementTab().updateUser(rowIndx); + AdminGeneralPage.getUserManagementTab().updateUserRole(userRole, rowIndx); + AdminGeneralPage.getUserManagementTab().saveAfterUpdateUser(rowIndx); + } + + public static void deleteFirstRow(){ + AdminGeneralPage.getUserManagementTab().deleteUser(0); + } + + public static void searchForUser(String searchString){ + AdminGeneralPage.getUserManagementTab().searchUser(searchString); + } + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java new file mode 100644 index 0000000000..d55ace4374 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java @@ -0,0 +1,638 @@ +/*- + * ============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.ci.tests.utilities; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.awt.AWTException; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.datatransfer.StringSelection; +import java.awt.event.KeyEvent; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifactsPlaceholders; +import org.openecomp.sdc.ci.tests.datatypes.HeatWithParametersDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.UploadArtifactPopup; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class ArtifactUIUtils { + + private static final String PARAMETERS = "parameters"; + + private ArtifactUIUtils() { + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo) throws Exception { + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + fillAndAddNewArtifactParameters(artifactInfo, artifactPopup); +// artifactPopup.defineArtifactLabel(artifactInfo.getArtifactLabel()); +// artifactPopup.selectArtifactType(artifactInfo.getArtifactType()); +// artifactPopup.insertDescription(artifactInfo.getDescription()); +// artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); +// artifactPopup.clickAddButton(); + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo, UploadArtifactPopup artifactPopup) throws Exception { + artifactPopup.defineArtifactLabel(artifactInfo.getArtifactLabel()); + artifactPopup.selectArtifactType(artifactInfo.getArtifactType()); + artifactPopup.insertDescription(artifactInfo.getDescription()); + artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); + artifactPopup.clickDoneButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("A new artifact of type %s was added", artifactInfo.getArtifactType())); + } + + public static void fillAndAddNewEnvArtifactParameters(ArtifactInfo artifactInfo, UploadArtifactPopup artifactPopup) throws Exception { + artifactPopup.insertDescription(artifactInfo.getDescription()); + artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); + artifactPopup.clickDoneButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("ENV parameters %s artifact updated ", artifactInfo.getArtifactType())); + } + + public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifactsPlaceholders artifactLabel,String filepath, String filename, String description) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + InformationalArtifactPage.artifactPopup().loadFile(filepath, filename); + InformationalArtifactPage.artifactPopup().insertDescription(description); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + } + + public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifactsService artifactLabel, + String filepath, String filename, String description) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filepath, filename); + artifactPopup.insertDescription(description); + artifactPopup.clickDoneButton(); + } + + public static void fillPlaceHolderAPIArtifact(DataTestIdEnum.APIArtifactsService artifactLabel, + String filepath, String filename, String description, String url) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filepath, filename); + artifactPopup.insertURL(url); + artifactPopup.insertDescription(description); + artifactPopup.clickDoneButton(); + } + + public static RestResponse deploymentArtifactResourceInUI(ResourceReqDetails resource, User user, + ArtifactReqDetails artifact, String file) throws Exception { + Thread.sleep(1000); + + List listFormInput = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-designer-sidebar-tab")); + WebElement addArtifactElement = listFormInput.get(2); + addArtifactElement.click(); + + WebElement addArtifact = GeneralUIUtils.getDriver() + .findElement(By.className("i-sdc-designer-sidebar-section-content-item-artifact-details-name")); + addArtifact.click(); + + Thread.sleep(1000); + WebElement descriptionProperty = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-textarea")); + descriptionProperty.clear(); + descriptionProperty.sendKeys(artifact.getDescription()); + + WebElement uploadFile = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-label-upload")); + uploadFile.click(); + + StringSelection sel = new StringSelection(file); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null); + // System.out.println("selection" + sel); + Thread.sleep(1000); + + Robot robot = new Robot(); + Thread.sleep(1000); + + Thread.sleep(2000); + + robot.keyPress(KeyEvent.VK_ENTER); + + // Release Enter + robot.keyRelease(KeyEvent.VK_ENTER); + + // Press CTRL+V + robot.keyPress(KeyEvent.VK_CONTROL); + robot.keyPress(KeyEvent.VK_V); + + // Release CTRL+V + robot.keyRelease(KeyEvent.VK_CONTROL); + robot.keyRelease(KeyEvent.VK_V); + Thread.sleep(1000); + + // Press Enter + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + Thread.sleep(3000); + + WebElement clickDone = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-form-action")); + clickDone.click(); + + Thread.sleep(3500); + + GeneralUIUtils.getDriver().findElement(By.cssSelector("button[data-ng-click^=save]")).click(); + + RestResponse getResource = RestCDUtils.getResource(resource, user); + assertEquals("Did not succeed to get resource after create", 200, getResource.getErrorCode().intValue()); + return getResource; + } + + public static void addInformationArtifact(ArtifactReqDetails artifact, String filePath, + final InformationalArtifactsPlaceholders dataTestEnum) throws Exception { + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.sleep(2000); + GeneralUIUtils.getWebElementByTestID(dataTestEnum.getValue()).click(); + +// final WebElement browseWebElement = GeneralUIUtils.retryMethodOnException( +// () -> GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue())); + + WebElement browseWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue()); + browseWebElement.sendKeys(filePath); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.DESCRIPTION.getValue()) + .sendKeys(artifact.getDescription()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.ADD.getValue()).click(); + + } + + private static void addFileToWindowBrowse(String file) throws InterruptedException, AWTException { + StringSelection sel = new StringSelection(file); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null); + // System.out.println("selection" + sel); + Thread.sleep(1000); + + Robot robot = new Robot(); + + robot.keyPress(KeyEvent.VK_ENTER); + + // Release Enter + robot.keyRelease(KeyEvent.VK_ENTER); + + // Press CTRL+V + robot.keyPress(KeyEvent.VK_CONTROL); + robot.keyPress(KeyEvent.VK_V); + + // Release CTRL+V + robot.keyRelease(KeyEvent.VK_CONTROL); + robot.keyRelease(KeyEvent.VK_V); + Thread.sleep(1000); + + // Press Enter + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + Thread.sleep(3000); + } + + static WebElement ArtifactLabel; + + public static Map addInformationalArtifact(String artifactLabel) throws Exception { + String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText(); + Map artifactValues = new HashMap(); + String labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getFirstSelectedOption() + .getText(); + ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel")); + if (ArtifactLabel.getAttribute("value").equals("")) { + labelName = "New-Test-Artifact"; + ArtifactLabel.sendKeys(labelName); + type = GeneralUIUtils.getSelectList("HEAT", "artifacttype").getFirstSelectedOption().getText(); + } + String description = "This is Description"; + String fileName = "Heat-File.yaml"; + GeneralUIUtils.setWebElementByTestId("description", "description"); + ResourceUIUtils.importFileWithSendKeyBrowse(ImportAssetUIUtils.FILE_PATH, fileName); + GeneralUIUtils.getWebElementByTestID("Add").click(); + GeneralUIUtils.getWebElementByTestID(labelName); + + artifactValues.put("type", type); + artifactValues.put("description", description); + artifactValues.put("name", labelName); + artifactValues.put("fileName", fileName); + return artifactValues; + } + + public static Map addDeploymentArtifact(String artifactLabel, String artifactType, String fileName) + throws Exception { + String type = null; + String labelName; + Map artifactValues = new HashMap(); + try { + labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getOptions().get(1).getText(); + GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").selectByVisibleText(labelName); + } catch (Exception e) { + labelName = GeneralUIUtils.getWebElementByClassName(artifactLabel).getText(); + } + ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel")); + if (ArtifactLabel.getText().equals("")) { + labelName = "New-Test-Artifact"; + ArtifactLabel.sendKeys(labelName); + type = GeneralUIUtils.getSelectList(artifactType, "artifacttype").getFirstSelectedOption().getText(); + } + String description = "This is Description"; + GeneralUIUtils.setWebElementByTestId("description", "description" ); + ResourceUIUtils.importFileWithSendKeyBrowse(ImportAssetUIUtils.FILE_PATH, fileName); + try { + GeneralUIUtils.getWebElementByTestID("Add").click(); + } catch (Exception e) { + GeneralUIUtils.getWebElementByClassName("w-sdc-form-action add-property").click(); + } + + artifactValues.put("type", artifactType); + artifactValues.put("description", description); + artifactValues.put("name", labelName); + artifactValues.put("fileName", fileName); + return artifactValues; + } + + + public static Map addDeploymentArtifactFromCanvas(String artifactLabel) throws Exception { + String type = null; + Map artifactValues = new HashMap(); + String labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getFirstSelectedOption() + .getText(); + ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel")); + if (ArtifactLabel.getText().equals("")) { + labelName = "New-Test-Artifact"; + ArtifactLabel.sendKeys(labelName); + type = GeneralUIUtils.getSelectList("OTHER", "artifacttype").getFirstSelectedOption().getText(); + } + String description = "This is Description"; + String filePath = "C:\\Git_work\\ASDC\\d2-sdnc\\ui-ci\\src\\main\\resources\\Files\\"; + String fileName = "Heat-File.yaml"; + GeneralUIUtils.setWebElementByTestId("description", "description"); + ResourceUIUtils.importFileWithSendKeyBrowse(filePath, fileName); + GeneralUIUtils.getWebElementByTestID("Add").click(); + artifactValues.put("type", type); + artifactValues.put("description", description); + artifactValues.put("name", labelName); + artifactValues.put("fileName", fileName); + return artifactValues; + } + + public static Map valideArtifact(Map artifactValues, Boolean condition) + throws Exception { + if (condition) { + GeneralUIUtils.getWebElementByClassName("table-edit-btn").click(); + } else { + System.out.println(artifactValues.get("name")); + GeneralUIUtils.getWebElementByTestID("edit_" + artifactValues.get("name")).click(); + } + Thread.sleep(1000); + String labelname = GeneralUIUtils.getWebElementByClassName("artifactLabel").getAttribute("value"); + String filename = GeneralUIUtils.getWebElementByTestID("filename").getText(); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText(); + labelname.compareToIgnoreCase(artifactValues.get("name").replaceAll("-", "")); + assertEquals(filename, artifactValues.get("fileName").replaceAll(" ", "-")); + assertEquals(type, artifactValues.get("type")); + assertEquals(description, artifactValues.get("description")); + GeneralUIUtils.getWebElementByTestID("Update").click(); + return artifactValues; + } + + public static void valideArtifactFromCanvas(Map artifactValues) throws Exception { + GeneralUIUtils.getWebElementByTestID("artifactDisplayName-" + artifactValues.get("name")).click(); + Thread.sleep(1000); + String labelname = GeneralUIUtils.getWebElementByClassName("artifactLabel").getAttribute("value"); + String filename = GeneralUIUtils.getWebElementByTestID("filename").getText(); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText(); + labelname.compareToIgnoreCase(artifactValues.get("name").replaceAll("-", "")); + assertEquals(filename, artifactValues.get("fileName")); + assertEquals(type, artifactValues.get("type")); + assertEquals(description, artifactValues.get("description")); + } + + public static Map> getArtifactsListFromResponse(String jsonResponse, + String fieldOfArtifactList) { + JSONObject object = (JSONObject) JSONValue.parse(jsonResponse); + Map> map = (Map>) object.get(fieldOfArtifactList); + return map; + } + + public static void validateArtifactNameVersionType(String artifactLabel, String artifactVersion, String artifactType) { +// Assert.assertEquals(GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel + "']")).getAttribute("textContent").trim(), artifactLabel); + if(!GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactLabel)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact label not equal - this warnning represent defect."); + } + if(artifactVersion != null) { +// Assert.assertEquals(GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']")).getAttribute("textContent").trim(), artifactVersion, "Artifact version not equal."); + if(!GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactVersion)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact version not equal - this warnning represent defect."); + } + } + if(artifactType != null) { +// Assert.assertEquals(GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + artifactLabel + "']")).getAttribute("textContent").trim(), artifactType, "Artifact type not equal."); + if(!GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactType)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact type not equal - this warnning represent defect."); + } + } + } + + public static void validateArtifactVersionByTypeAndLabel(String artifactLabel, String expectedArtifactVersion, ArtifactTypeEnum artifactType) { + if(expectedArtifactVersion != null) { + String xPath; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to validate artifact version ...")); + if(artifactType.getType().equals(ArtifactTypeEnum.HEAT_ENV.getType())){ + xPath = "//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION_ENV.getValue() + artifactLabel + "']"; + }else{ + xPath = "//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']"; + } + String actualartifactVersion = GeneralUIUtils.getDriver().findElement(By.xpath(xPath)).getAttribute("textContent").trim(); + Assert.assertEquals(actualartifactVersion, expectedArtifactVersion, "Artifact type " + artifactType.getType() + " expected version is " + expectedArtifactVersion + " not equal to " + actualartifactVersion); + } + } + + public static void validateExistArtifactOnDeploymentInformationPage(String expectedArtifactLabel, String artifactUUID, String artifactVersion, String artifactType, boolean isDownloadable, boolean isEditable, boolean isDeletable, boolean isArtifactParametersEditable) { + + String dataTestId = DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + expectedArtifactLabel; + + List artifactElements = GeneralUIUtils.getWebElementsListByContainTestID(dataTestId); + Assert.assertEquals(artifactElements.size(), 1, "There are more then one artifact named " + expectedArtifactLabel); + + WebElement artifact = artifactElements.get(0); + String actualArtifactLabel = GeneralUIUtils.getTextContentAttributeValue(artifact).trim(); + Assert.assertEquals(actualArtifactLabel, expectedArtifactLabel); + + if(artifactUUID != null) { + WebElement uuid = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(uuid).trim(), artifactUUID, "Artifact uuid not equal."); + } + if(artifactVersion != null) { + WebElement version = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(version).trim(), artifactVersion, "Artifact version not equal."); + } + if(artifactType != null) { + WebElement type = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(type).trim(), artifactType, "Artifact type not equal."); + } + if(isArtifactParametersEditable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that parameters edit button enabled."); + } else if(isArtifactParametersEditable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that parameters edit button disabled."); + } + if(isDownloadable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that download button enabled."); + } else if(isDownloadable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that download button disabled."); + } + if(isEditable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that edit button enabled."); + } else if(isEditable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that edit button disabled."); + } + if(isDeletable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that delete button enabled."); + } else if(isDeletable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that delete button disabled."); + } + } + + public static void validateNotExistArtifactOnDeploymentInformationPage(String artifactLabel) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel), false); + } + + public static void validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(String fileName, String artifactDisplayedName, + boolean isUpdateable, boolean isParametersEditable, boolean isDownloadable, boolean isDeleteable) { + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactDisplayedName).getText(), fileName); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName).getText(), artifactDisplayedName); + + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + + if(isParametersEditable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactDisplayedName), true, "Expect that parameters edit button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactDisplayedName), false, "Expect that parameters edit button disabled."); + } + if(isDownloadable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + artifactDisplayedName), true, "Expect that download button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + artifactDisplayedName), false, "Expect that download button disabled."); + } + if(isDeleteable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + artifactDisplayedName), true, "Expect that delete button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + artifactDisplayedName), false, "Expect that delete button disabled."); + } + if(isUpdateable) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), true, "Expect that edit button enabled."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + GeneralUIUtils.waitForElementInVisibilityByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + } else { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false, "Expect that edit button disabled."); + } + + } + + public static void validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(String artifactDisplayedName) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactDisplayedName), false); + } + + public static File verifyUpdatedEnvParameters(HeatWithParametersDefinition pairToUpdate, File updateEnvFile, String dataTestId) throws Exception { + GeneralUIUtils.hoverOnAreaByTestId(dataTestId); + return verifyUpdatedEnvParameters(pairToUpdate, updateEnvFile); + } + + public static File verifyUpdatedEnvParameters(HeatWithParametersDefinition pairToUpdate, File updateEnvFile) throws Exception { + + String heatDisplayName = pairToUpdate.getHeatArtifactDisplayName(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue()+heatDisplayName); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + + String pattern = PARAMETERS; + Map mapUpdetedEnvFile = FileHandling.parseYamlFileToMapByPattern(updateEnvFile, pattern); + Map mapDownloadedEnvFile = FileHandling.parseYamlFileToMapByPattern(latestFilefromDir, pattern); + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to check, that ENV file was updated ..."); + assertTrue("File" + latestFilefromDir.getName() + " contains different parameters number from expected file", mapDownloadedEnvFile.size() == mapUpdetedEnvFile.size()); + assertTrue("Updated file contains not updated parameters value", mapDownloadedEnvFile.entrySet().containsAll(mapUpdetedEnvFile.entrySet())); + return latestFilefromDir; + } + + /** + * compare heat env files by pattern ("parameters") + * @param expectedFile + * @param actualFile + * @param pattern + * @throws Exception + */ + public static void compareYamlFilesByPattern(File expectedFile, File actualFile, String pattern) throws Exception { + + Map mapExpectedFile = FileHandling.parseYamlFileToMapByPattern(expectedFile, pattern); + Map mapActualFile = FileHandling.parseYamlFileToMapByPattern(actualFile, pattern); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare files ..."); + assertTrue("File" + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size()); + assertTrue("File " + actualFile.getName() + " does not contains all expected parametrs", mapActualFile.entrySet().containsAll(mapExpectedFile.entrySet())); + } + + public static void compareYamlParametersByPattern(Map mapExpectedproperties, File actualFileproperties, String pattern) throws Exception { + + Map mapActualFileProerties = FileHandling.parseYamlFileToMapByPattern(actualFileproperties, pattern); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare files ..."); + assertTrue("Actual file contains different parameters number from expected file", mapActualFileProerties.size() == mapExpectedproperties.size()); + Map newMap = new HashMap<>(mapActualFileProerties); + assertTrue("Actual file does not contains all expected parametrs", newMap.entrySet().containsAll(mapExpectedproperties.entrySet())); + } + + + public static File uploadCreatedUpdateParametersEnvFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws Exception { +// created env file to upload + File pathToEnvParametersFile = prepareEnvParametersFile(heatEnvDetails, directoryPath); + ArtifactInfo heatEnvArtifactInfo = new ArtifactInfo(directoryPath, heatEnvDetails.getHeatEnvLabel()+".env", "heatEnvDesc", heatEnvDetails.getHeatEnvLabel(),heatEnvDetails.getHeatEnvArtifactType()); + ArtifactUIUtils.fillAndAddNewEnvArtifactParameters(heatEnvArtifactInfo, CompositionPage.artifactPopup()); + return pathToEnvParametersFile; + } + + public static File prepareEnvParametersFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws IOException { + File pathToEnvParametersFile = FileHandling.createEmptyFile(directoryPath+heatEnvDetails.getHeatEnvLabel()+".env"); +// fill file + FileHandling.writeToFile(pathToEnvParametersFile, "parameters:", 0); + for(HeatParameterDataDefinition paramDefinition : heatEnvDetails.getHeatParameterDefinition()){ + Object data = getDataToWrite(paramDefinition); + FileHandling.writeToFile(pathToEnvParametersFile, data, 2); + } + + return pathToEnvParametersFile; + } + + public static Object getDataToWrite(HeatParameterDataDefinition paramDefinition) { + Object data = ""; + switch (paramDefinition.getType()) { + case "string": + String text = "\"string\""; + data = getFormatedData(paramDefinition.getName(), text); + break; + case "number": + data = getFormatedData(paramDefinition.getName(), 666); + break; + case "json": + String jsonText = "{\"param1\":\"param1\", \"param2\":2}"; + data = getFormatedData(paramDefinition.getName(), jsonText); + break; + case "boolean": + if(paramDefinition.getCurrentValue().equals("true")){ + data = getFormatedData(paramDefinition.getName(), false); + }else{ + data = getFormatedData(paramDefinition.getName(), true); + } + break; + case "comma_delimited_list": + String commaDelimitedListText = "127.0.0.10, 127.0.0.15, 127.0.0.20"; + data = getFormatedData(paramDefinition.getName(), commaDelimitedListText); + break; + default: + break; + } + return data; + } + + + public static Map getDataToWriteInUI(List paramDefinitionFromGetResourceResponse) { + MapnewValuesToUpdateInUI=new HashMap<>(); + for (HeatParameterDataDefinition param : paramDefinitionFromGetResourceResponse) { + System.out.println(param.getCurrentValue()); + switch (param.getType()) { + + case "string": + String text = "string"; + newValuesToUpdateInUI.put(param.getName(),text); + break; + case "number": + newValuesToUpdateInUI.put(param.getName(),666); + break; + case "json": + String jsonText = "{\"param1\":\"param1\", \"param2\":2}"; + newValuesToUpdateInUI.put(param.getName(),jsonText); + break; + case "boolean": + if (param.getCurrentValue().equals(true)) { + newValuesToUpdateInUI.put(param.getName(),false); + } else { + newValuesToUpdateInUI.put(param.getName(),true); + } + break; + case "comma_delimited_list": + String commaDelimitedListText = "127.0.0.10, 127.0.0.15, 127.0.0.20"; + newValuesToUpdateInUI.put(param.getName(),commaDelimitedListText); + break; + default: + break; + + } + + } + return newValuesToUpdateInUI; + } + + public static Object getValue(HeatParameterDataDefinition param) { + String type = param.getType(); + Object result = null; + switch(type){ + case "string": + result = param.getCurrentValue(); + break; + case "number": + result = new Integer(param.getCurrentValue()); + break; + case "json": + result = param.getCurrentValue(); + break; + case "boolean": + result = new Boolean(param.getCurrentValue()); + break; + case "comma_delimited_list": + result = param.getCurrentValue(); + break; + default: + break; + } + return result; + } + + public static Object getFormatedData(String name, Object text) { + return name + ": " + text; +} + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java new file mode 100644 index 0000000000..c53fef596a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java @@ -0,0 +1,67 @@ +/*- + * ============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.ci.tests.utilities; + +import org.codehaus.jettison.json.JSONObject; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; + +public class AuditCDUtils { + + public static void validateResourceSuccessAudit(ResourceReqDetails resource, User user, String action) + throws Exception { + JSONObject auditBody = AuditValidationUtils.filterAuditByUuid(action, resource.getUUID()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resource, resource.getVersion(), user); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, auditBody.toString(), false); + } + + public static void validateServiceSuccessAudit(ServiceReqDetails service, User user, String action) + throws Exception { + validateServiceSuccessAudit(service, user, action, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + public static void validateServiceSuccessAudit(ServiceReqDetails service, User user, String action, + LifecycleStateEnum lifecycleStatus) throws Exception { + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = AuditValidationUtils + .constructFieldsForAuditValidation(service, service.getVersion(), user); + String body = AuditValidationUtils.filterAuditByUuid(action, service.getUUID()).toString(); + expectedResourceAuditJavaObject.setAction(action); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(lifecycleStatus.toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, action, body, false); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java new file mode 100644 index 0000000000..fbe8c04036 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java @@ -0,0 +1,54 @@ +/*- + * ============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.ci.tests.utilities; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openqa.selenium.WebElement; + +public final class CanvasElement { + private final String uniqueId; + private ImmutablePair location; + private WebElement elementType; + + CanvasElement(String name, ImmutablePair location, WebElement canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + elementType = canvasItem; + } + + public String getUniqueId() { + return uniqueId; + } + + public ImmutablePair getLocation() { + return location; + } + + public void setLocation(ImmutablePair location) { + this.location = location; + } + + public WebElement getElementType() { + return elementType; + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java new file mode 100644 index 0000000000..18cb338891 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java @@ -0,0 +1,179 @@ +/*- + * ============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.ci.tests.utilities; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; + +public final class CanvasManager { + private Map canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_ELEMENT_Y_OFFSET = 40; + private static final int CANVAS_ELEMENT_X_OFFSET = 21; // 14 - 27 + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair newLocation) + throws Exception { + GeneralUIUtils.waitForLoader(); + Thread.sleep(500); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.waitForLoader(); + } + + private String getItemName(WebElement canvasItem) { + String canvasItemName = canvasItem.getAttribute("data-tests-id"); + + return canvasItemName.substring(canvasItemName.lastIndexOf("-")); + } + + public CanvasElement createElementOnCanvas(WebElement canvasItem) throws Exception { + GeneralUIUtils.waitForLoader(); + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(canvasItem, 0, 0); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + + String uniqueId = getItemName(canvasItem) + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, canvasItem); + addCanvasElement(canvasElement); + GeneralUIUtils.waitForLoader(); + return canvasElement; + } + + private ImmutablePair getFreePosition() { + // TODO mshitrit use better method + ImmutablePair randomPosition = null; + boolean freePosition = false; + int minSpace = 150; + while (!freePosition) { + ImmutablePair tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair getRandomPosition() { + int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair(xElement, yElement); + } + + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + GeneralUIUtils.waitForLoader(); + drawSimpleLink(firstElement, secondElement); + + selectReqAndCapAndConnect(); + + GeneralUIUtils.waitForLoader(); + + } + + private void selectReqAndCapAndConnect() { + // Select First Cap + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0).click(); + // Select First Req + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0).click(); + // Connect + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click(); + } + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) { + + int yOffset = CANVAS_ELEMENT_Y_OFFSET; + int xOffset = CANVAS_ELEMENT_X_OFFSET; + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, + secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java new file mode 100644 index 0000000000..e9ba11f0f4 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java @@ -0,0 +1,232 @@ +/*- + * ============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.ci.tests.utilities; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.CatalogPageLeftPanelFilterTitle; +import org.openecomp.sdc.ci.tests.datatypes.TypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class CatalogUIUtilitis { + + + + + + // Get all Categories , Subcategories and Icons. + public void getAllCategoriesAndSubcategories() throws IOException, JSONException { + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + for (int j = 0; j < subcategories.length(); j++) { + String subcategoryname = (String) subcategories.getJSONObject(j).get("name"); + System.out.println(subcategoryname); + } + for (int j = 0; j < subcategories.length(); j++) { + JSONArray icons = (JSONArray) subcategories.getJSONObject(j).get("icons"); + for (int k = 0; k < icons.length(); k++) { + System.out.println(icons.get(k)); + } + } + System.out.println("-------------------------------"); + } + } + + @Test + // FOr testing---delete. + public static List abcd() throws IOException, JSONException { + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + List allcat = new ArrayList<>(); + String uniqueId = null; + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + uniqueId = (String) categories.getJSONObject(i).get("uniqueId"); + allcat.add(uniqueId); + JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + for (int j = 0; j < subcategories.length(); j++) { + String subcategoryname = (String) subcategories.getJSONObject(j).get("name"); + uniqueId = (String) subcategories.getJSONObject(j).get("uniqueId"); + allcat.add(uniqueId); + } + } + return allcat; + + } + + public static void clickTopMenuButton(TopMenuButtonsEnum button) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s button ...", button.name())); + switch (button) { + case CATALOG: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + case HOME: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + case ON_BOARDING: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + default: + break; + } + GeneralUIUtils.ultimateWait(); + } + + public static String catalogFilterTypeChecBox(TypesEnum enumtype) throws Exception { + String Type = enumtype.toString().toLowerCase(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s ...", Type)); + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + return Type; + } + + public static List catalogFilterStatusChecBox(CheckBoxStatusEnum statusEnum) throws Exception { + List status = null; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s status", statusEnum.name())); + switch (statusEnum) { + case IN_DESIGN: + status = Arrays.asList("NOT_CERTIFIED_CHECKIN", "NOT_CERTIFIED_CHECKOUT"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case READY_FOR_TESTING: + status = Arrays.asList("READY_FOR_CERTIFICATION"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case IN_TESTING: + status = Arrays.asList("CERTIFICATION_IN_PROGRESS"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case CERTIFIED: + status = Arrays.asList("CERTIFIED"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case DISTRIBUTED: + status = Arrays.asList("CERTIFIED"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + } + return status; + } + + // Get all Categories uniqueID .//The parent categories. + public static List getCategories() throws IOException, JSONException { + List allCategoriesList = new ArrayList<>(); + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + System.out.println(categoryname); + allCategoriesList.add(categoryname); + } + return allCategoriesList; + } + + @Test + // Get Subcategories by Category name + public static List getAllSubcategoriesByUniqueId(String uniqueId) throws IOException, JSONException { + + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + List subCategories = new ArrayList<>();// subCategories to + // return. + JSONArray subcategories = null; + + for (int i = 0; i < categories.length(); i++) { + + String categoryuniqueId = (String) categories.getJSONObject(i).get("uniqueId"); + + if (categoryuniqueId.contentEquals(uniqueId)) { + subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + + for (int j = 0; j < subcategories.length(); j++) { + + subCategories.add((String) subcategories.getJSONObject(j).get("uniqueId")); + } + + break; + } + } + if (subcategories == null) { + subCategories.add(uniqueId); + } + return subCategories; + } + + @Test + // Get icons by category name + public void getSubCategoryIcons() throws IOException, JSONException { + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String subcategoryname = (String) categories.getJSONObject(i).get("name"); + if (subcategoryname.contentEquals("Generic")) { + JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + for (int j = 0; j < subcategories.length(); j++) { + JSONArray icons = (JSONArray) subcategories.getJSONObject(j).get("icons"); + for (int k = 0; k < icons.length(); k++) { + System.out.println(icons.get(k)); + } + } + break; + } + } + } + + + public static WebElement clickOnUpperCategoryCheckbox() throws InterruptedException { + List categorieCheckboxes = GeneralUIUtils.getElementsByCSS("span[data-tests-id*='category']"); // get all categories and subcategories + WebElement categorieCheckbox = categorieCheckboxes.get(0); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s category ...", categorieCheckbox.getText())); + categorieCheckbox.click(); + GeneralUIUtils.ultimateWait(); + return categorieCheckbox; + } + + public static void clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle leftPanelElement) throws InterruptedException { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", leftPanelElement.name())); + GeneralUIUtils.getElementsByCSS(leftPanelElement.getValue()).forEach(WebElement::click); + } + + public static WebElement catalogSearchBox(String searchText) { + WebElement searchBox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + searchBox.clear(); + searchBox.sendKeys(searchText); + return searchBox; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java new file mode 100644 index 0000000000..08b392fcd6 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java @@ -0,0 +1,115 @@ +/*- + * ============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.ci.tests.utilities; + +import java.io.File; +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.AttFtpClient; +import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.aventstack.extentreports.Status; + +public class DownloadManager { + + + public File fetchDownloadedFile(){ + + File retrieveLastModifiedFileFromFTP = null; + + if (DriverFactory.getConfig().isRemoteTesting()){ + + + try { + + AttFtpClient instance = AttFtpClient.getInstance(); + AttFtpClient.getInstance().retrieveListOfFile(); + retrieveLastModifiedFileFromFTP = instance.retrieveLastModifiedFileFromFTP(); + + } catch (Exception e) { + System.out.println("could not retriev file"); + } + + return retrieveLastModifiedFileFromFTP; + + } + + + return retrieveLastModifiedFileFromFTP; + + } + + + /** + * this method download csar file from VSP repository to default browser download directory + * @param vspName + * @throws Exception + */ + public static void downloadCsarByNameFromVSPRepository(String vspName, String vspId) throws Exception{ + FileHandling.cleanCurrentDownloadDir(); + HomePage.showVspRepository(); + boolean vspFound = HomePage.searchForVSP(vspName); + if (vspFound){ + ExtentTestActions.log(Status.INFO, String.format("Going to downloading VSP %s", vspName)); + List elemenetsFromTable = HomePage.getElemenetsFromTable(); +// GeneralUIUtils.ultimateWait(); +// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 5); +// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); + elemenetsFromTable.get(1).click(); +// findElement.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.DOWNLOAD_CSAR.getValue()); + ExtentTestActions.log(Status.INFO, "Succeeded to downloaded CSAR file named " + vspId + " into folder " + SetupCDTest.getWindowTest().getDownloadDirectory()); + GeneralUIUtils.getElementsByCSS("div[class^='w-sdc-modal-close']").forEach(e -> e.click()); + GeneralUIUtils.ultimateWait(); + } + } + +// AttFtpClient instance = AttFtpClient.getInstance(); +// +// String server = "135.177.130.113"; +// int port = 2121; +// String user = "admin"; +// String pass = "admin"; +// AttFtpClient.getInstance().init(server, port, user, pass); +// +// try { +// AttFtpClient.getInstance().retrieveListOfFile(); +// +// File retrieveLastModifiedFileFromFTP = instance.retrieveLastModifiedFileFromFTP(); +// String content = new String(Files.readAllBytes(Paths.get(retrieveLastModifiedFileFromFTP.getPath())), StandardCharsets.UTF_8); +//// instance.deleteFilesFromFTPserver(); +// System.out.println(content); +// readFile(retrieveLastModifiedFileFromFTP); +// +// } finally { +// instance.terminateClient(); +// } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java new file mode 100644 index 0000000000..6008f200d2 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java @@ -0,0 +1,505 @@ +/*- + * ============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.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.BufferedOutputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.yaml.snakeyaml.Yaml; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +public class FileHandling { + +// ------------------yaml parser methods---------------------------- + public static Map parseYamlFile(String filePath) throws Exception { + Yaml yaml = new Yaml(); + File file = new File(filePath); + InputStream inputStream = new FileInputStream(file); + Map map = (Map) yaml.load(inputStream); + return map; + } + + /** + * The method return map fetched objects by pattern from yaml file + * @param yamlFile + * @param pattern + * @return + * @throws Exception + */ + public static Map parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception { + Map yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString()); + Map objectMap = getObjectMapByPattern(yamlFileToMap, pattern); + return objectMap; + } + + @SuppressWarnings("unchecked") + public static Map getObjectMapByPattern(Map parseUpdetedEnvFile, String pattern) { + Map objectMap = null; + + Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern); + if(objectUpdetedEnvFile instanceof HashMap){ + objectMap = (Map) objectUpdetedEnvFile; + } + return objectMap; + } + +// ------------------------------------------------------------------------------------------------- + + public static String getFilePath(String folder) { + String filepath = System.getProperty("filepath"); + if (filepath == null && System.getProperty("os.name").contains("Windows")) { + filepath = FileHandling.getResourcesFilesPath() + folder + File.separator; + } + + else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filepath = FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator; + } + + System.out.println(filepath); + + return filepath; + } + + public static String getBasePath() { + return System.getProperty("user.dir") + File.separator; + } + + public static String getDriversPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci" + File.separator + "drivers" + File.separator; + } + + public static String getResourcesFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator; + } + + public static String getResourcesEnvFilesPath() { + return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator; + } + + public static String getCiFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci"; + } + + public static String getConfFilesPath() { + return getCiFilesPath() + File.separator + "conf" + File.separator; + } + + public static String getTestSuitesFilesPath() { + return getCiFilesPath() + File.separator + "testSuites" + File.separator; + } + + public static String getVnfRepositoryPath() { + return getFilePath("VNFs"); + } + + public static File getConfigFile(String configFileName) throws Exception { + File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName); + if (!configFile.exists()) { + configFile = new File(FileHandling.getConfFilesPath() + configFileName); + } + return configFile; + } + + public static Object[] filterFileNamesFromFolder(String filepath, String extension) { + try { + File dir = new File(filepath); + List filenames = new ArrayList(); + + FilenameFilter extensionFilter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(extension); + } + }; + + if (dir.isDirectory()) { + for (File file : dir.listFiles(extensionFilter)) { + filenames.add(file.getName()); + } + return filenames.toArray(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String[] getArtifactsFromZip(String filepath, String zipFilename){ + try{ + ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename); + Enumeration entries = zipFile.entries(); + + String[] artifactNames = new String[zipFile.size() - 1]; + + int i = 0; + while(entries.hasMoreElements()){ + ZipEntry nextElement = entries.nextElement(); + if (!nextElement.isDirectory()){ + if (!nextElement.getName().equals("MANIFEST.json")){ + String name = nextElement.getName(); + artifactNames[i++] = name; + } + } + } + zipFile.close(); + return artifactNames; + } + catch(ZipException zipEx){ + System.err.println("Error in zip file named : " + zipFilename); + zipEx.printStackTrace(); + } catch (IOException e) { + System.err.println("Unhandled exception : "); + e.printStackTrace(); + } + + return null; + + } + + public static Object[] getZipFileNamesFromFolder(String filepath) { + return filterFileNamesFromFolder(filepath, ".zip"); + } + + public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){ + int fileCounter = 0; + for (String artifact : artifactsArr){ + String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length()); + if (extensionFile.equals(reqExtension)){ + fileCounter++; + } + } + return fileCounter; + } + + + public static synchronized File getLastModifiedFileFromDir() throws Exception{ + return getLastModifiedFileFromDir(SetupCDTest.getWindowTest().getDownloadDirectory()); + } + + public static synchronized File getLastModifiedFileFromDir(String dirPath){ + File dir = new File(dirPath); + File[] files = dir.listFiles(); + if (files == null) { + assertTrue("File not found under directory " + dirPath, false); + return null; + } + + File lastModifiedFile = files[0]; + for (int i = 1; i < files.length; i++) { + if(files[i].isDirectory()) { + continue; + } + if (lastModifiedFile.lastModified() < files[i].lastModified()) { + lastModifiedFile = files[i]; + } + } + return lastModifiedFile; + } + + public static void deleteDirectory(String directoryPath) { + File dir = new File(directoryPath); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + System.out.println("Failed to delete " + dir); + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir); + } + } + + public static void createDirectory(String directoryPath) { + File directory = new File(String.valueOf(directoryPath)); + if (! directory.exists()){ + directory.mkdir(); + } + } + + + /** + * The method append data to existing file, if file not exists - create it + * @param pathToFile + * @param text + * @param leftSpaceCount + * @throws IOException + */ + public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{ + + BufferedWriter bw = null; + FileWriter fw = null; + if(!pathToFile.exists()){ + createEmptyFile(pathToFile); + } + try { + fw = new FileWriter(pathToFile, true); + bw = new BufferedWriter(fw); + StringBuilder sb = new StringBuilder(); + if(leftSpaceCount > 0 ){ + for(int i = 0; i < leftSpaceCount; i++){ + sb.append(" "); + } + } + bw.write(sb.toString() + text); + bw.newLine(); + bw.close(); + fw.close(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + public static synchronized void writeToFile(File pathToFile, Map> dataMap, Integer leftSpaceCount) throws IOException{ + + BufferedWriter bw = null; + FileWriter fw = null; + try { + if(!pathToFile.exists()){ + createEmptyFile(pathToFile); + } + fw = new FileWriter(pathToFile, true); + bw = new BufferedWriter(fw); + StringBuilder sb = new StringBuilder(); + if(leftSpaceCount > 0 ){ + for(int i = 0; i < leftSpaceCount; i++){ + sb.append(" "); + } + } + for(Map.Entry> entry : dataMap.entrySet()){ + Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right); + bw.write(sb.toString() + record); + bw.newLine(); + } + bw.close(); + fw.close(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + public static void deleteLastDowloadedFiles(List files) throws IOException { + for (File file : files) { + File fileToDelete =new File(Config.instance().getWindowsDownloadDirectory()+file.getName()); + fileToDelete.delete(); + } + } + + public static void cleanCurrentDownloadDir() throws IOException { + try{ + ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory()); + System.gc(); + FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory())); + } + catch(Exception e){ + + } + } + + public static boolean isFileDownloaded(String downloadPath, String fileName) { + boolean flag = false; + File dir = new File(downloadPath); + File[] dir_contents = dir.listFiles(); + for (int i = 0; i < dir_contents.length; i++) { + if (dir_contents[i].getName().equals(fileName)) + return flag = true; + } + return flag; + } + + public static String getMD5OfFile(File file) throws IOException { + String content = FileUtils.readFileToString(file); + String md5 = GeneralUtility.calculateMD5ByString(content); + return md5; + } + + public static File createEmptyFile(String fileToCreate) { + File file= new File(fileToCreate); + try { + if(file.exists()){ + deleteFile(file); + } + file.createNewFile(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return file; + } + + public static File createEmptyFile(File fileToCreate) { + try { + if(fileToCreate.exists()){ + deleteFile(fileToCreate); + } + fileToCreate.createNewFile(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return fileToCreate; + } + + public static void deleteFile(File file){ + + try{ + if(file.exists()){ + file.deleteOnExit(); + SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted"); + }else{ + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName()); + } + }catch(Exception e){ + e.printStackTrace(); + } + + } + + + /** + * get file list from directory by extension array + * @param directory + * @param okFileExtensions + * @return + */ + public static List getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){ + + List fileList = new ArrayList<>(); + File[] files = directory.listFiles(); + + for (String extension : okFileExtensions){ + for(File file : files){ + if (file.getName().toLowerCase().endsWith(extension)){ + fileList.add(file); + } + } + } + return fileList; + } + + private static final int BUFFER_SIZE = 4096; + public static void unzip(String zipFilePath, String destDirectory) throws IOException { + File destDir = new File(destDirectory); + if (!destDir.exists()) { + destDir.mkdir(); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry entry = zipIn.getNextEntry(); +// iterates over entries in the zip file + while (entry != null) { + String entryName; + if(System.getProperty("os.name").contains("Windows")){ + entryName = entry.getName().replaceAll("/", "\\"+File.separator); + }else{ + entryName = entry.getName(); + } + String filePath = destDirectory + entryName; + String currPath = destDirectory; + String[] dirs = entryName.split("\\"+File.separator); + String currToken; + for(int i = 0; i0) { +// timeOut=time; +// } +// else { +// timeOut=timeOut; +// } +// } + + /**************** DRIVER ****************/ + + public static WebDriver getDriver() { + try{ + return DriverFactory.getDriver(); + } + catch(Exception e){ + e.printStackTrace(); + } + return null; + } + /****************************************/ + + public static List getElemenetsFromTable(By by) { + return getDriver().findElements(by); + } + + public static File takeScreenshot(String screenshotFilename, String dir, String testName) throws IOException { + if (screenshotFilename == null) { + if (testName != null){ + screenshotFilename = testName; + } + else + { + screenshotFilename = UUID.randomUUID().toString(); + } + } + try { + File scrFile = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.FILE); + File filePath = new File(String.format("%s/%s.png", dir, screenshotFilename)); + new File(dir).mkdirs(); + FileUtils.copyFile(scrFile, filePath); + return filePath; + } catch (IOException e1) { + e1.printStackTrace(); + } + return null; + } + + public static File takeScreenshot(String screenshotFilename, String dir) throws IOException{ + return takeScreenshot(screenshotFilename, dir, null); + } + + + public static void scrollDown() { + try{ + Robot robot = new Robot(); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + GeneralUIUtils.waitForLoader(); + } + catch(Exception e){ + e.printStackTrace(); + } + } + + public static void minimizeCatalogFilterByTitle(CatalogFilterTitlesEnum titlesEnum) { + + switch (titlesEnum) { + case CATEGORIES: + GeneralUIUtils.getWebElementByTestID(titlesEnum.getValue()).click(); + break; + case STATUS: + GeneralUIUtils.getWebElementByTestID(titlesEnum.getValue()).click(); + break; + case TYPE: + GeneralUIUtils.getWebElementByTestID(titlesEnum.getValue()).click(); + break; + default: + break; + } + + } + + public static WebElement getWebElementByTestID(String dataTestId) { + return getWebElementByTestID(dataTestId, timeOut); + } + + public static WebElement getWebElementByTestID(String dataTestId, int timeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeout); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static boolean isWebElementExistByTestId(String dataTestId) { + if(getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")).size() == 0) { + return false; + } + return true; + } + + public static WebElement getInputElement(String dataTestId) { + try{ + ultimateWait(); + return getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + } + catch(Exception e){ + return null; + } + } + + public static List getInputElements(String dataTestId) { + ultimateWait(); + return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + + } + + public static WebElement getWebElementBy(By by) { + return getWebElementBy(by, timeOut); + } + + public static WebElement getWebElementBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(by)); + } + + public static List getWebElementListText(Listelements) { + ListText=new ArrayList<>(); + for (WebElement webElement : elements) { + Text.add(webElement.getText()); + } + return Text; + } + + + public static List getWebElementsListBy(By by) { + return getWebElementsListBy(by, timeOut); + } + + public static List getWebElementsListBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); + } + + public static List getWebElementsListByContainTestID(String dataTestId) { + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), 10); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@data-tests-id, '"+dataTestId+"')]"))); + } + catch(Exception e){ + return new ArrayList(); + } + } + + public static List getWebElementsListByContainsClassName(String containedText) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@class, '"+containedText+"')]"))); + } + + public static WebElement getWebElementByContainsClassName(String containedText) { + return getWebElementBy(By.xpath("//*[contains(@class, '"+containedText+"')]")); + } + + public static WebElement getWebElementByClassName(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(className))); + } + + public static WebElement getWebElementByLinkText(String linkText) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@text='" + linkText + "']"))); + } + + + public static List getWebElementsListByTestID(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static List getWebElementsListByClassName(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className(className))); + } + + + + + public static Boolean isElementInvisibleByTestId(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until( + ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static Boolean isElementVisibleByTestId(String dataTestId) { + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + if(wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//*[@data-tests-id='" + dataTestId + "']")))).isDisplayed()){ + return true; + }else { + return false; + } + } + catch(Exception e){ + return false; + } + } + + public static void clickOnElementByTestId(String dataTestId) { + clickOnElementByTestIdWithoutWait(dataTestId); + ultimateWait(); + } + + public static void clickOnElementByTestIdWithoutWait(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).click(); + } + + public static void clickOnElementByTestId(String dataTestId, int customTimeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).click(); + } + + public static WebElement waitForElementVisibilityByTestId(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId) { + return waitForElementInVisibilityByTestId(dataTestId, timeOut); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + boolean displayed = getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")).isEmpty(); + if (!displayed){ + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "'])"))); + ultimateWait(); + return until; + } + return false; + } + + public static Boolean waitForElementInVisibilityByTestId(By by) { + return waitForElementInVisibilityBy(by, timeOut); + } + + + public static Boolean waitForElementInVisibilityBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + boolean displayed = getDriver().findElements(by).isEmpty(); + if (!displayed){ + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(by)); + sleep(1000); + return until; + } + return false; + } + + + public static void setWebElementByTestId(String elemetID, String value) { + WebElement resourceDescriptionTextbox = GeneralUIUtils.getWebElementByTestID(elemetID); + resourceDescriptionTextbox.clear(); + resourceDescriptionTextbox.sendKeys(value); + + } + + public static WebElement hoverOnAreaByTestId(String areaId) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByTestID(areaId); + actions.moveToElement(area).perform(); + ultimateWait(); + return area; + } + + public static WebElement hoverOnAreaByClassName(String className) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByClassName(className); + actions.moveToElement(area).perform(); + GeneralUIUtils.ultimateWait(); + return area; + } + + public static void clickElementUsingActions(WebElement element){ + Actions actions = new Actions(getDriver()); + + actions.moveToElement(element); + actions.perform(); + + actions.click(); + actions.perform(); + + ultimateWait(); + } + + public static void waitForLoader() { + waitForLoader(timeOut); + } + + public static void waitForLoader(int timeOut) { + sleep(500); + waitForElementInVisibilityBy(By.className("tlv-loader"), timeOut); + } + + public static void findComponentAndClick(String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in homepage"); + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + try{ + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + ultimateWait(); + } + catch(Exception e){ + SetupCDTest.getExtendTest().log(Status.INFO, "Can't interact with search bar"); + e.printStackTrace(); + } + + + try{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component from home screen", resourceName)); + clickOnElementByTestId(resourceName); + GeneralUIUtils.ultimateWait(); + getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } + catch(Exception e){ + SetupCDTest.getExtendTest().log(Status.INFO, "Can't click on component named " + resourceName); + e.printStackTrace(); + } + } + + + public static String getComponentVersion(String componentName) { + return GeneralUIUtils.getWebElementByTestID(componentName + "Version").getText(); + } + + public static void windowZoomOut() { + final int zoomOutFactor = 3; + for (int i = 0; i < zoomOutFactor; i++) { + if(getDriver() instanceof FirefoxDriver) { + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT)); + } + } + } + + public static void resetZoom(){ + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0")); + } + + public static void windowZoomOutUltimate(){ + resetZoom(); + windowZoomOut(); +// JavascriptExecutor js = (JavascriptExecutor) driver; +// js.executeScript("document.body.style.zoom='90%'"); + } + + public static void clickASDCLogo() { + WebDriverWait wait = new WebDriverWait(getDriver(), 15); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("ASDC"))); + WebElement ClickASDCLogo = getDriver().findElement(By.linkText("ASDC")); + ClickASDCLogo.click(); + GeneralUIUtils.waitForLoader(); + } + + public static void sleep(int duration) { + try { + Thread.sleep(duration); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + public static void moveToStep(DataTestIdEnum.StepsEnum Stepname) { + moveToStep(Stepname.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to %s page ", Stepname.toString())); + } + + public static void moveToStep(String dataTestId) { + clickOnElementByTestId(dataTestId); + ultimateWait(); + } + + + public static Select getSelectList(String item, String datatestsid) { + Select selectlist = new Select(getWebElementByTestID(datatestsid)); + if (item != null) { + selectlist.selectByVisibleText(item); + } + return selectlist; + } + + public static List waitForElementsListVisibilityTestMethod(DashboardCardEnum dataTestId) { + GeneralUIUtils.waitForLoader(); + return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId.getValue() + "']")); + } + + public static List getElementsByCSS(String cssString) throws InterruptedException { + GeneralUIUtils.waitForLoader(); + List assets = getDriver().findElements(By.cssSelector(cssString)); + return assets; + } + + public static WebElement getElementfromElementByCSS(WebElement parentElement, String cssString){ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + GeneralUIUtils.waitForLoader(); + return parentElement.findElement(By.cssSelector(cssString)); + } + + public static WebElement getElementfromElementByXPATH(WebElement parentElement, DashboardCardEnum dataTestId){ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + GeneralUIUtils.waitForLoader(); + return HighlightMyElement( parentElement.findElement(By.xpath("//*[@data-tests-id='" + dataTestId.getValue() + "']"))); + } + + public static WebElement HighlightMyElement(WebElement element) { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + javascript.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 4px solid yellow;"); + return element; + } + + public static WebElement getSelectedElementFromDropDown(String dataTestId){ + GeneralUIUtils.ultimateWait();; + WebElement selectedElement = new Select (getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).getFirstSelectedOption(); + return selectedElement; + } + + + public static void waitForPageLoadByReadyState() { + new WebDriverWait(getDriver(), 30).until((ExpectedCondition) wd -> + ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); + } + + + public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier> func) { + int maxWaitingPeriodMS = 10 * 1000; + int napPeriodMS = 100; + int sumOfWaiting = 0; + List elements = null; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + elements = func.get(); + isKeepWaiting = (expectedElementsCount == elements.size()); + sleep(napPeriodMS); + sumOfWaiting += napPeriodMS; + if (sumOfWaiting > maxWaitingPeriodMS) + return false; + } + return true; + } + + public static String getActionDuration(Runnable func) throws Exception{ + long startTime = System.nanoTime(); + func.run(); + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + String durationString = String.format("%02d:%02d", duration / 60, duration % 60); + return durationString; + } + + public static WebElement clickOnAreaJS(String areaId) { + return clickOnAreaJS(areaId, timeOut); + } + + + public static WebElement clickOnAreaJS(String areaId, int timeout) { + try{ + ultimateWait(); + WebElement area = getWebElementByTestID(areaId); + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + //HighlightMyElement(area); + Object executeScript = javascript.executeScript("arguments[0].click();", area, "color: yellow; border: 4px solid yellow;"); + waitForLoader(timeout); + return area; + } + catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + + + public static WebElement clickOnAreaJS(WebElement areaId) throws InterruptedException { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + //HighlightMyElement(area); + javascript.executeScript("arguments[0].click();", areaId, "color: yellow; border: 4px solid yellow;"); + return areaId; + } + + + + public static void clickSomewhereOnPage() { + getDriver().findElement(By.cssSelector(".asdc-app-title")).click(); + } + + public static void findComponentAndClickInCatalog(String resourceName) throws Exception { + // This method will find element by element name, don't use data-tests-id argument + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + ultimateWait(); + clickOnElementByText(resourceName); + ultimateWait(); + } + + public static void clickOnElementByText(String textInElement) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + HighlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickOnElementByText(String textInElement, int customTimeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); + HighlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickJSOnElementByText(String textInElement) throws Exception { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + clickOnAreaJS(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))); + } + + public static void fluentWaitTestID(String dataTestId, String text) { + FluentWait fluentWait = new FluentWait(getDriver()) + .withTimeout(30, TimeUnit.SECONDS) + .pollingEvery(50, TimeUnit.MILLISECONDS) + .ignoring(NoSuchElementException.class); + + fluentWait.until(ExpectedConditions.refreshed( + ExpectedConditions.textToBePresentInElementValue(By.xpath("//*[@data-tests-id='" + dataTestId + "']"), text))); + } + + public static void regularWait(WebElement element, String text){ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + + wait.until(ExpectedConditions.textToBePresentInElementValue(element, text)); + } + + public static void waitForAngular(){ + WebDriverWait wait = new WebDriverWait(getDriver(), 90, 100); + wait.until(AdditionalConditions.pageLoadWait()); + wait.until(AdditionalConditions.angularHasFinishedProcessing()); + } + + public static Object getAllElementAttributes(WebElement element) { + return ((JavascriptExecutor)getDriver()).executeScript("var s = []; var attrs = arguments[0].attributes; for (var l = 0; l < attrs.length; ++l) { var a = attrs[l]; s.push(a.name + ':' + a.value); } ; return s;", element); + } + + public static boolean isElementReadOnly(WebElement element){ + try { + HighlightMyElement(element).clear(); + return false; + } catch (Exception e) { + return true; + } + } + + public static boolean isElementReadOnly(String dataTestId){ + return isElementReadOnly( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static boolean isElementDisabled(WebElement element){ + return HighlightMyElement(element).getAttribute("class").contains("view-mode") || + element.getAttribute("class").contains("disabled"); + } + + public static boolean isElementDisabled(String dataTestId){ + return isElementDisabled( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static void ultimateWait(){ + long startTime = System.nanoTime(); + + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForBackLoader(); + GeneralUIUtils.waitForAngular(); + + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); +// System.out.println("UltimateWait took: "+ duration); + if(duration > timeOut){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Delays on page, %d seconds", duration)); + } +// waitForUINotification(); + } + + public static WebElement makeElementVisibleWithJS(WebElement element){ + String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement unhideElement(WebElement element, String attributeValue){ + String js = "arguments[0].setAttribute('class','" + attributeValue + "');"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement findByText(String textInElement){ + return getDriver().findElement(searchByTextContaining(textInElement)); + } + public static By searchByTextContaining(String textInElement) { + return By.xpath("//*[contains(text(),'" + textInElement + "')]"); + } + + + public static boolean findAndWaitByText(String textInElement, int timeout){ + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), timeout); + wait.until(ExpectedConditions.presenceOfElementLocated(searchByTextContaining(textInElement))); + return true; + } + catch(Exception e){ + return false; + } + } + + public static WebElement getClickableButtonBy(By by, int timout){ + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), timout); + WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by)); + return element; + } + catch(Exception e){ + return null; + } + } + + + + public static WebElement getButtonWithText(String textInButton){ + try{ + return getDriver().findElement(By.xpath("//button[contains(text(),'" + textInButton + "')]")); + } + catch(Exception e) + { + return null; + } + } + + + public static List getElementsByDataTestsIdStartWith(String startWithString){ + ultimateWait(); + return getDriver().findElements(By.xpath("//*[starts-with(@data-tests-id,'" + startWithString + "')]")); + } + + public static void closeErrorMessage() { + WebElement okWebElement = getButtonWithText("OK"); + if (okWebElement != null){ + okWebElement.click(); + ultimateWait(); + } + } + + public static WebElement getElementByCSS(String cssString) throws InterruptedException { + ultimateWait(); + return getDriver().findElement(By.cssSelector(cssString)); + } + + public static String getDataTestIdAttributeValue(WebElement element) { + return element.getAttribute("data-tests-id"); + } + + public static String getTextContentAttributeValue(WebElement element) { + return element.getAttribute("textContent"); + } + + public static WebElement getElementInsideElementByDataTestsId(WebElement element, String dataTestId) { + try{ + return element.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + } + catch(Exception e){ + return null; + } + } + + public static void clickOnElementByCSS(String cssString) throws Exception { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssString))).click(); + ultimateWait(); + } + public static String getRandomComponentName(String prefix) { + return prefix + GeneralUIUtils.randomNumber(); + } + public static int randomNumber() { + Random r = new Random(); + return r.nextInt(10000); + } + + public static void waitForUINotification() { + List notificationElements = getDriver().findElements(By.className("ui-notification")); + if (!notificationElements.isEmpty()){ + notificationElements.forEach(WebElement::click); + } + } + + public static boolean checkForDisabledAttribute(String dataTestId){ + Object elementAttributes = getAllElementAttributes(waitForElementVisibilityByTestId(dataTestId)); + return elementAttributes.toString().contains("disabled"); + } + + public static void dragAndDropElementByY(WebElement area, int yOffset) { + Actions actions = new Actions(getDriver()); + actions.dragAndDropBy(area, 10, yOffset).perform(); + ultimateWait(); + } + + public static void waitForBackLoader() { + waitForBackLoader(timeOut); + } + + public static void waitForBackLoader(int timeOut) { + sleep(100); + waitForElementInVisibilityBy(By.className("tlv-loader-back"), timeOut); + } + + public static void addStringtoClipboard(String text){ + StringSelection selection = new StringSelection(text); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(selection, selection); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java new file mode 100644 index 0000000000..1bef2ad32c --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java @@ -0,0 +1,117 @@ +/*- + * ============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.ci.tests.utilities; + +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class HomeUtils { + + public static WebElement createAndImportButtons(CreateAndImportButtonsEnum type, WebDriver driver) + throws InterruptedException { + switch (type) { + case IMPORT_CP: + case IMPORT_VFC: + case IMPORT_VL: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.IMPORT_AREA.getValue()); + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.IMPORT_VFC.getValue()); + + case IMPORT_VF: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.IMPORT_AREA.getValue()); + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.IMPORT_VFC.getValue()); + case CREATE_SERVICE: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + ; + break; + + case CREATE_PRODUCT: + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + break; + + default: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + driver.findElement(By.xpath("//*[@data-tests-id='createResourceButton']")).click(); + break; + } + return null; + + } + + public static String checkBoxLifeCyclestate(CheckBoxStatusEnum lifeCycle) { + String Status = "IN DESIGN CHECK OUT"; + switch (lifeCycle) { + case CHECKIN: + Status = "IN DESIGN CHECK IN"; + if (GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).isDisplayed()) { + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + } + break; + case CHECKOUT: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "IN DESIGN CHECK OUT"; + break; + case IN_TESTING: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "IN TESTING"; + break; + case READY_FOR_TESTING: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "READY FOR TESTING"; + break; + case CERTIFIED: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "CERTIFIED"; + break; + } + return Status; + } + + public static void findComponentAndClick(String componentName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "finding component " + componentName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName); + WebElement foundComp = null; + try { + foundComp = GeneralUIUtils.getWebElementByTestID(componentName); + foundComp.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (Exception e) { + String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName); + SetupCDTest.getExtendTest().log(Status.FAIL, msg); + System.out.println(msg); + Assert.fail(msg); + } + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java new file mode 100644 index 0000000000..d1045eab76 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java @@ -0,0 +1,57 @@ +/*- + * ============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.ci.tests.utilities; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; + +public class ImportAssetUIUtils { + + public static final String FILE_PATH = System.getProperty("user.dir") + "\\src\\main\\resources\\Files\\"; + public static String fileName = "JDM_vfc.yml"; + public static final String toscaErrorMessage = "Invalid TOSCA template."; + public static final String yamlError = "Invalid YAML file."; + public static final String allReadyExistErro = "Imported resource already exists in ASDC Catalog."; + + public static void importAsssetAndFillGeneralInfo(String FILE_PATH, String fileName, + ResourceReqDetails resourceDetails, User user, CreateAndImportButtonsEnum type) throws Exception { + ResourceUIUtils.importFileWithSendKey(FILE_PATH, fileName, type); + ResourceUIUtils.fillResourceGeneralInformationPage(resourceDetails, user,true); + } + + public static void importAsssetFillGeneralInfoAndSelectIcon(String FILE_PATH, String fileName, + ResourceReqDetails resourceDetails, User user, CreateAndImportButtonsEnum type) throws Exception { + importAsssetAndFillGeneralInfo(FILE_PATH, fileName, resourceDetails, user, type); + GeneralPageElements.clickCreateButton(); + ResourceUIUtils.selectRandomResourceIcon(); + } + + // checking or unchecking the checkbox on right palette at designer + // workspace + public static void checkbox(String checkBoxname, WebDriver driver) { + driver.findElement(By.xpath("//label[@for='" + checkBoxname + "']")).click(); + } + +} 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 new file mode 100644 index 0000000000..dfb4b74fac --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java @@ -0,0 +1,801 @@ +/*- + * ============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.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.simple.JSONArray; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +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; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.execute.setup.ArtifactsCorrelationManager; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +public class OnboardingUtils { + + public OnboardingUtils() { + } + + private static String vendorId; + private static String vendorLicenseName; + private static String vendorLicenseAgreementId; + private static String featureGroupId; + + public static Pair> createVendorSoftwareProduct(String HeatFileName, String filepath, User user) + throws Exception { + Pair> pair = createVSP(HeatFileName, filepath, user); + + String vspid = pair.right.get("vspId"); + + prepareVspForUse(user, vspid); + + return pair; + } + + public static void prepareVspForUse(User user, String vspid) throws Exception { + RestResponse checkin = checkinVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue()); + + RestResponse submit = submitVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue()); + + SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product"); + } + + public static Pair> createVSP(String HeatFileName, String filepath, User user) throws Exception { + String vspName = handleFilename(HeatFileName); + + SetupCDTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product"); + + Pair> createNewVspPair = createNewVendorSoftwareProduct(vspName, vendorLicenseName, vendorId, vendorLicenseAgreementId, featureGroupId, user); + RestResponse createNewVendorSoftwareProduct = createNewVspPair.left; + assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue()); + String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId"); + String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId"); + + Map vspMeta = createNewVspPair.right; + Map vspObject = new HashMap(); + Iterator iterator = vspMeta.keySet().iterator(); + while(iterator.hasNext()){ + Object key = iterator.next(); + Object value = vspMeta.get(key); + vspObject.put(key.toString(), value.toString()); + } + vspObject.put("vspId", vspid); + vspObject.put("componentId", componentId); + vspObject.put("vendorName", vendorLicenseName); + vspObject.put("attContact", user.getUserId()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspid, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vspid, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + Pair> pair = new Pair>(vspName, vspObject); + + return pair; + } + + public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user) throws Exception{ + RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); + ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL"); + deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_POLL); + ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP"); + deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_TRAP); + addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId); + prepareVspForUse(user, vspId); + } + + public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user) + throws Exception, Throwable { + String vspName = handleFilename(HeatFileName); + SetupCDTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product"); + + RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspId, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vspId, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + RestResponse checkin = checkinVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue()); + + + RestResponse submit = submitVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to update package of VSP ", 200, createPackage.getErrorCode().intValue()); + + SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor software product"); + + return vspName; + } + + public static String handleFilename(String heatFileName) { + final String namePrefix = "ciVFOnboarded-"; + final String nameSuffix = "-" + getShortUUID(); + + String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf(".")); + + if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) { + subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length()); + } + + if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) { + subHeatFileName = subHeatFileName.replace("(", "-"); + subHeatFileName = subHeatFileName.replace(")", "-"); + } + + String vnfName = namePrefix + subHeatFileName + nameSuffix; + return vnfName; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user, String vspComponentId) throws Exception{ + vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId; + if (vspComponentId != null){ + if (snmpPoll != null){ + ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll); + RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vspid, user, vspComponentId); + assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue()); + } + if (snmpTrap != null){ + ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap); + RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vspid, user, vspComponentId); + assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue()); + } + } + + return vspComponentId; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user) throws Exception{ + return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vspid, user, null); + } + + private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, String vspid, User user, + String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { + Config config = Utils.getConfig(); + String snmpPollUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp/upload", + config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); + return uploadFile(filepath, zipArtifact, snmpPollUrl, user); + } + + private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, String vspid, User user, + String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { + Config config = Utils.getConfig(); + String snmpTrapUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp-trap/upload", + config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); + return uploadFile(filepath, zipArtifact, snmpTrapUrl, user); + } + + private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/%s", + config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue()); + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendDelete(url, headersMap); + return response; + } + + + + private static String getVSPComponentId(String vspid, User user) throws Exception, JSONException { + RestResponse components = getVSPComponents(vspid, user); + String response = components.getResponse(); + Map responseMap = (Map) JSONValue.parse(response); + JSONArray results = (JSONArray)responseMap.get("results"); + for (Object res : results){ + Map compMap= (Map) JSONValue.parse(res.toString()); + String componentId = compMap.get("id").toString(); + return componentId; + } + return null; + } + + private static RestResponse getVSPComponents(String vspid, User user) throws Exception{ + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components", config.getCatalogBeHost(),config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + return response; + } + + public static void createVendorLicense(User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license"); + vendorLicenseName = "ciLicense" + getShortUUID(); + RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user); + assertEquals("did not succeed to create vendor license model", 200, + vendorLicenseResponse.getErrorCode().intValue()); + vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value"); + + RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, user); + assertEquals("did not succeed to create vendor key groups", 200, + vendorKeyGroupsResponse.getErrorCode().intValue()); + String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value"); + + RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, user); + assertEquals("did not succeed to create vendor entitlement pool", 200, + vendorEntitlementPool.getErrorCode().intValue()); + String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), + "value"); + + RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, keyGroupId, + entitlementPoolId, user); + assertEquals("did not succeed to create vendor license feature groups", 200, + vendorLicenseFeatureGroups.getErrorCode().intValue()); + featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value"); + + RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, featureGroupId, user); + assertEquals("did not succeed to create vendor license agreement", 200, + vendorLicenseAgreement.getErrorCode().intValue()); + vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), + "value"); + + RestResponse checkinVendorLicense = checkinVendorLicense(vendorId, user); + assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); + + RestResponse submitVendorLicense = submitVendorLicense(vendorId, user); + assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); + + SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license"); + } + + private static String getShortUUID() { + return UUID.randomUUID().toString().split("-")[0]; + } + + private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/" + onboardComponent + "/%s/versions/0.1/actions", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("action", action); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, jObject.toString(), headersMap); + return response; + } + + public static RestResponse checkinVendorLicense(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkin", "vendor-license-models", user); + } + + public static RestResponse submitVendorLicense(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Submit", "vendor-license-models", user); + } + + public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(), + config.getCatalogBePort()); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("vendorName", name); + jObject.put("description", "new vendor license model"); + jObject.put("iconRef", "icon"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-agreements", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject licenseTermpObject = new JSONObject(); + licenseTermpObject.put("choice", "Fixed_Term"); + licenseTermpObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "abc"); + jObjectBody.put("description", "new vendor license agreement"); + jObjectBody.put("requirementsAndConstrains", "abc"); + jObjectBody.put("licenseTerm", licenseTermpObject); + jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray()); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId, + String entitlementPoolId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/feature-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("name", "xyz"); + jObject.put("description", "new vendor license feature groups"); + jObject.put("partNumber", "123abc456"); + jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray()); + jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray()); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/entitlement-pools", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jEntitlementMetricObject = new JSONObject(); + jEntitlementMetricObject.put("choice", "CPU"); + jEntitlementMetricObject.put("other", ""); + + JSONObject jAggregationFunctionObject = new JSONObject(); + jAggregationFunctionObject.put("choice", "Peak"); + jAggregationFunctionObject.put("other", ""); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jTimeObject = new JSONObject(); + jTimeObject.put("choice", "Hour"); + jTimeObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "def"); + jObjectBody.put("description", "new vendor license entitlement pool"); + jObjectBody.put("thresholdValue", "23"); + jObjectBody.put("thresholdUnits", "Absolute"); + jObjectBody.put("entitlementMetric", jEntitlementMetricObject); + jObjectBody.put("increments", "abcd"); + jObjectBody.put("aggregationFunction", jAggregationFunctionObject); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("time", jTimeObject); + jObjectBody.put("manufacturerReferenceNumber", "123aaa"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-key-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Tenant").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "keyGroup"); + jObjectBody.put("description", "new vendor license key group"); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("type", "Universal"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static Pair> createNewVendorSoftwareProduct(String name, String vendorName, String vendorId, + String licenseAgreementId, String featureGroupsId, User user) throws Exception { + + Map vspMetadta = new HashMap(); + + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products", + config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = user.getUserId(); + + JSONObject jlicensingDataObj = new JSONObject(); + jlicensingDataObj.put("licenseAgreement", licenseAgreementId); + jlicensingDataObj.put("featureGroups", Arrays.asList(featureGroupsId).toArray()); + + JSONObject jlicensingVersionObj = new JSONObject(); + jlicensingVersionObj.put("id", "1.0"); + jlicensingVersionObj.put("label", "1.0"); + + JSONObject jObject = new JSONObject(); + jObject.put("name", name); + jObject.put("description", "new VSP description"); + jObject.put("category", "resourceNewCategory.generic"); + jObject.put("subCategory", "resourceNewCategory.generic.database"); + jObject.put("licensingVersion", jlicensingVersionObj); + jObject.put("vendorName", vendorName); + jObject.put("vendorId", vendorId); + jObject.put("icon", "icon"); + jObject.put("licensingData", jlicensingDataObj); + + vspMetadta.put("description", jObject.getString("description")); + vspMetadta.put("category", jObject.getString("category")); + vspMetadta.put("subCategory", jObject.getString("subCategory").split("\\.")[2]); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + + return new Pair>(response, vspMetadta); + } + + public static RestResponse getVendorSoftwareProduct(Map vspObject, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/" + vspObject.get("vspId"), + config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpsSendGet(url, headersMap); + + return response; + } + + public static RestResponse validateUpload(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate/process", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + String body =null; + + RestResponse response = http.httpSendPut(url, body, headersMap); + + return response; + } + + public static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate", config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + return uploadFile(filepath, filename, url, user); + } + + private static RestResponse uploadFile(String filepath, String filename, String url, User user) + throws FileNotFoundException, IOException, ClientProtocolException { + CloseableHttpResponse response = null; + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename))); + + Map headersMap = prepareHeadersMap(user.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data"); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + + Iterator iterator = headersMap.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + String value = headersMap.get(key); + httpPost.addHeader(key, value); + } + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static File getTestZipFile(String filepath, String filename) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); + return filePath.toFile(); + } + + public static RestResponse checkinVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkin", "vendor-software-products", user); + } + + private static RestResponse checkoutVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkout", "vendor-software-products", user); + } + + public static RestResponse submitVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Submit", "vendor-software-products", user); + } + + public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user); + } + + protected static Map prepareHeadersMap(String userId) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + return headersMap; + } + + + private static void importUpdateVSP(Pair> vsp, boolean isUpdate) throws Exception{ + String vspName = vsp.left; + Map vspMetadata = vsp.right; + boolean vspFound = HomePage.searchForVSP(vspName); + + if (vspFound){ + + List elemenetsFromTable = HomePage.getElemenetsFromTable(); +// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30); +// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); +// findElement.click(); + elemenetsFromTable.get(1).click(); + GeneralUIUtils.waitForLoader(); + + if (isUpdate){ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); + + } + else{ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); + } + + String lifeCycleState = ResourceGeneralPage.getLifeCycleState(); + boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue()); + if (needCheckout) + { + try { + ResourceGeneralPage.clickCheckoutButton(); + Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout"); + + } catch (Exception e) { + ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout"); + e.printStackTrace(); + } + GeneralUIUtils.waitForLoader(); + } + + //Metadata verification + VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata); + + ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); + String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated()); + ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration); + } + else{ + Assert.fail("Did not find VSP named " + vspName); + } + } + + private static void waitUntilVnfCreated() { + GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(60*10); + GeneralUIUtils.waitForAngular(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void updateVSP(Pair> vsp) throws Exception{ + ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left); + importUpdateVSP(vsp, true); + } + + public static void importVSP(Pair> vsp) throws Exception{ + ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left); + importUpdateVSP(vsp, false); + } + + public static void updateVnfAndValidate(String filepath, Pair> vsp, String updatedVnfFile, User user) throws Exception, Throwable { + ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); + System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile)); + + Map vspMap = vsp.right; + String vspId = vspMap.get("vspId"); + + updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user); + HomePage.showVspRepository(); + updateVSP(vsp); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile); + } + + public static Pair> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile)); + System.out.println(String.format("Going to onboard the VNF %s", vnfFile)); + + createVendorLicense(user); + Pair> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user); + String vspName = createVendorSoftwareProduct.left; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId")); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + + ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); + HomePage.showVspRepository(); + ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf(".")))); + importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + // Verify deployment artifacts + Map combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); + + LinkedList deploymentArtifacts = ((LinkedList) combinedMap.get("Deployment")); + ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts); + + for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { + if(deploymentArtifact.getType().equals("HEAT_ENV")) { + continue; + } else if(deploymentArtifact.getFileName().contains(".")) { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")), "1", deploymentArtifact.getType()); + } else { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim(), "1", deploymentArtifact.getType()); + } + + } + + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); + return createVendorSoftwareProduct; + } + +} + +enum SnmpTypeEnum{ + SNMP_POLL ("snmp"), + SNMP_TRAP ("snmp-trap"); + + private String value; + + public String getValue() { + return value; + } + + private SnmpTypeEnum(String value) { + this.value = value; + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java new file mode 100644 index 0000000000..9e478c8523 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.awt.AWTException; +import java.util.List; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ProductGeneralPage; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +/** + * @author al714h + * + */ + +public class ProductUIUtils { + + protected static WebDriver driver; + + public ProductUIUtils(TestName name, String className) { + super(); + } + + public static void fillProductGeneralPage(ProductReqDetails product, User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Fill in metadata values in general page.. ")); + ProductGeneralPage.defineName(product.getName()); + ProductGeneralPage.defineFullName(product.getFullName()); + ProductGeneralPage.defineDescription(product.getDescription()); + ProductGeneralPage.defineProjectCode(product.getProjectCode()); + defineTagsList2(product.getTags()); + ProductGeneralPage.defineContactId(product.getContactId()); + GeneralUIUtils.clickSomewhereOnPage(); + } + + public static void createProduct(ProductReqDetails product, User user) throws Exception, AWTException { + clikAddProduct(); + fillProductGeneralPage(product, user); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Product %s created", product.getName())); + } + + public static void defineTagsList2(List productTags){ + WebElement productTagsTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.TAGS.getValue()); + for (String tag : productTags) { + productTagsTextbox.clear(); + productTagsTextbox.sendKeys(tag); + GeneralUIUtils.waitForAngular(); + productTagsTextbox.sendKeys(Keys.ENTER); + } + } + + public static void clikAddProduct(){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking Add Product button")); + try { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_PRODUCT.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exception on catched on Add Product button, retrying ...")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_PRODUCT.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java new file mode 100644 index 0000000000..62b2f832bd --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java @@ -0,0 +1,108 @@ +/*- + * ============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.ci.tests.utilities; + +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.PropertiesPage; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class PropertiesUIUtils { + + // public static void addPropertByType(String type,String name,String + // defaultValue,String description) throws Exception{ + // + // ResourceUIUtils.defineNewSelectList(type); + // ResourceUIUtils.definePropertyName(name); + // ResourceUIUtils.defineDefaultValueByType(defaultValue); + // ResourceUIUtils.defineDescription(description); + // Thread.sleep(2000); + // ResourceUIUtils.clickButton("Add"); + // } + public static Map addProperties(String name, String itemType, String defaultValue, + String description, String schemaType) throws Exception { + Map propertyvalues = new HashMap(); + GeneralUIUtils.getSelectList(itemType, "propertyType"); + ResourceUIUtils.definePropertyName(name); + if (itemType == "boolean") { + ResourceUIUtils.defineBoolenDefaultValue(defaultValue); + GeneralUIUtils.setWebElementByTestId("description","description"); + Thread.sleep(2000); + GeneralUIUtils.getWebElementByTestID("Add").click(); + ; + } else if (itemType == "list" || itemType == "map") { + GeneralUIUtils.getSelectList(schemaType, "schemaType"); + } + if (!(itemType == "boolean")) { + ResourceUIUtils.defineDefaultValueByType(defaultValue); + GeneralUIUtils.setWebElementByTestId("description", "des"); + GeneralUIUtils.getWebElementByTestID("Add").click(); + ; + Thread.sleep(2000); + } + propertyvalues.put("type", itemType); + propertyvalues.put("defaultValue", defaultValue); + propertyvalues.put("description", description); + propertyvalues.put("name", name); + + return propertyvalues; + } + + public static void vlidateProperties(Map propertyValues) throws InterruptedException { + WebElement name = GeneralUIUtils.getWebElementByTestID(propertyValues.get("name")); + name.getText().equalsIgnoreCase(propertyValues.get("name")); + WebElement defaultValue = GeneralUIUtils.getWebElementByTestID(propertyValues.get("name")); + defaultValue.getText().equalsIgnoreCase(propertyValues.get("defaultValue")); + WebElement type = GeneralUIUtils.getWebElementByTestID(propertyValues.get("type")); + type.getText().equalsIgnoreCase(propertyValues.get("type")); + } + + public static void addNewProperty(PropertyTypeEnum property) { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding new %s property", property.name())); + PropertiesPage.clickAddPropertyArtifact(); + PropertiesPage.getPropertyPopup().insertPropertyName(property.getName()); + PropertiesPage.getPropertyPopup().selectPropertyType(property.getType()); + PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getDescription()); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getValue()); + PropertiesPage.getPropertyPopup().clickSave(); + } + + public static void updateProperty(PropertyTypeEnum property) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating property: %s", property.name())); + PropertiesPage.clickOnProperty(property.getName()); + PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getDescription()); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getValue()); + PropertiesPage.getPropertyPopup().clickSave(); + } + + public static void changePropertyDefaultValueInComposition(String propertyName, String defaultValue) { + GeneralUIUtils.clickOnElementByTestId(propertyName); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(defaultValue); + PropertiesPage.getPropertyPopup().clickSave(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java new file mode 100644 index 0000000000..c76bf4b74a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java @@ -0,0 +1,1143 @@ +/*- + * ============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.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.KeyEvent; +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.http.HttpStatus; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.Dashboard; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceCategoriesNameEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openqa.selenium.By; +import org.openqa.selenium.ElementNotVisibleException; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.AssertJUnit; + +import com.aventstack.extentreports.Status; + +public final class ResourceUIUtils { + public static final String RESOURCE_NAME_PREFIX = "ResourceCDTest-"; + protected static final boolean IS_BEFORE_TEST = true; + public static final String INITIAL_VERSION = "0.1"; + public static final String ICON_RESOURCE_NAME = "call_controll"; + protected static final String UPDATED_RESOURCE_ICON_NAME = "objectStorage"; + + private ResourceUIUtils() { + } + + static WebDriver driver = GeneralUIUtils.getDriver(); + + public static void defineResourceName(String resourceName) { + + WebElement resourceNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("componentName")); + resourceNameTextbox.clear(); + resourceNameTextbox.sendKeys(resourceName); + } + + public static void defineResourceCategory(String category, String datatestsid) { + + GeneralUIUtils.getSelectList(category, datatestsid); + } + + // public static void uploadFileWithJavaRobot(String FilePath,String + // FileName) throws Exception{ + // + // StringSelection Path= new StringSelection(FilePath+FileName); + // Thread.sleep(1000); + // java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(Path, + // null); + // Robot robot = new Robot(); + // robot.delay(1000); + // robot.keyPress(KeyEvent.VK_CONTROL); + // robot.keyPress(KeyEvent.VK_V); + // robot.keyRelease(KeyEvent.VK_V); + // robot.keyRelease(KeyEvent.VK_CONTROL); + // robot.delay(1000); + // robot.keyPress(KeyEvent.VK_ENTER); + // robot.keyRelease(KeyEvent.VK_ENTER); + // robot.delay(1000); + // } + // click and upload tosca file //**to be changed. + public static void importFileWithSendKey(String FilePath, String FileName, CreateAndImportButtonsEnum type) + throws Exception { + WebElement importButton = HomeUtils.createAndImportButtons(type, driver).findElement(By.tagName("input")); + importButton.sendKeys(FilePath + FileName); + } + + public static void importFileWithSendKeyBrowse(String FilePath, String FileName) throws Exception { + WebElement browsebutton = GeneralUIUtils.getWebElementByTestID("browseButton"); + browsebutton.sendKeys(FilePath + FileName); + } + + // public static void defineVendorName(String resourceVendorName) { + // + // WebElement resourceVendorNameTextbox = + // GeneralUIUtils.getWebElementByTestID("vendorName"); + // resourceVendorNameTextbox.clear(); + // resourceVendorNameTextbox.sendKeys(resourceVendorName); + // } + + // public static void defineTagsList(ResourceReqDetails resource,String + // []resourceTags) { + // Listtaglist = new ArrayList();; + // WebElement resourceTagsTextbox = + // GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); + // for (String tag : resourceTags) { + // resourceTagsTextbox.clear(); + // resourceTagsTextbox.sendKeys(tag); + // resourceTagsTextbox.sendKeys(Keys.ENTER); + // taglist.add(tag); + // } + // resource.setTags(taglist); + // } + + public static String defineUserId(String userId) { + // + WebElement resourceUserIdTextbox = ResourceGeneralPage.getContactIdField(); + resourceUserIdTextbox.clear(); + resourceUserIdTextbox.sendKeys(userId); + return userId; + } + + public static void defineVendorRelease(String resourceVendorRelease) { + + WebElement resourceVendorReleaseTextbox = GeneralUIUtils.getWebElementByTestID("vendorRelease"); + resourceVendorReleaseTextbox.clear(); + resourceVendorReleaseTextbox.sendKeys(resourceVendorRelease); + } + + public static void selectResourceIcon(String resourceIcon) throws Exception { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 10); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@data-tests-id='" + resourceIcon + "']"))) + .click(); + } + + public static String definePropertyName(String name) { + + WebElement nameProperty = GeneralUIUtils.getDriver().findElement(By.name("propertyName")); + nameProperty.sendKeys(name); + return name; + } + + public static void selectRandomResourceIcon() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ICON); + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 4); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"))); + List iconElement = GeneralUIUtils.getDriver() + .findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")); + iconElement.get(0).click(); + } + + public static List getAllObjectsOnWorkspace(WebDriver driver, ResourceReqDetails resource) + throws Exception { + + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 10); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@*='" + resource.getName() + "']"))); + return GeneralUIUtils.getDriver() + .findElements(By.xpath("//div[@class='" + "w-sdc-dashboard-card-info-name" + "']")); + + } + + public static String getErrorMessageText(String text) throws Exception { + + return GeneralUIUtils.getWebElementByClassName(text).getText(); + + } + + public static WebElement scrollElement(WebDriver driver) throws Exception { + + return GeneralUIUtils.getDriver().findElement(By.className("ps-scrollbar-y")); + } + + public static void scrollDownPage() throws AWTException, InterruptedException { + Robot robot = new Robot(); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + } + + public static void defineNewSelectList(String Text) { + WebElement mySelectElm = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-select")); + Select mySelectString = new Select(mySelectElm); + mySelectString.selectByVisibleText(Text); + } + + public static void defineDefaultValueByType(String Value) { + + WebElement valueString = GeneralUIUtils.getDriver().findElement(By.name("value")); + valueString.clear(); + valueString.sendKeys(Value); + } + + public static void defineBoolenDefaultValue(String Value) { + + WebElement elementBoolean = GeneralUIUtils.getDriver().findElement(By.name("value")); + Select se = new Select(elementBoolean); + se.selectByValue(Value); + } + + public static void clickButtonBlue() { + WebElement clickButtonBlue = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-btn-blue")); + clickButtonBlue.click(); + } + + public static void clickButton(String selectButton) { + + WebElement clickButton = GeneralUIUtils.getDriver() + .findElement(By.xpath("//*[@data-tests-id='" + selectButton + "']")); + clickButton.click(); + } + + public static WebElement Waitfunctionforbuttons(String element, int timeout) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout); + return wait.until(ExpectedConditions.elementToBeClickable(By.xpath(element))); + } + + public static WebElement waitToButtonSubmitForTesting() { + return Waitfunctionforbuttons("//*[@data-tests-id='submitForTesting']", 10); + } + + public static WebElement waitToFinishButtonEnabled() { + return Waitfunctionforbuttons("//button[@data-tests-id='Finish']", 10); + } + + public static WebElement waitToNextButtonEnabled() { + return Waitfunctionforbuttons("//button[@data-tests-id='Next']", 10); + } + + public static WebElement waitToHomeMenu() { + return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-button-home']", 10); + } + + public static WebElement waitToCatalogMenu() { + return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-button-catalog']", 10); + } + + public static WebElement waitSearch() { + return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-input-search']", 10); + } + + public static WebElement waitSubmitforTestingCard() { + return Waitfunctionforbuttons("//*[@data-tests-id='i-sdc-dashboard-card-menu-item-SubmitforTesting']", 10); + } + + public static WebElement waitViewCard() { + return Waitfunctionforbuttons("//*[@data-tests-id='i-sdc-dashboard-card-menu-item-View']", 5); + } + +// public static void waitOpenCard(String requiredElementUniqueId) throws Exception { +// WebElement menu = GeneralUIUtils.getDriver() +// .findElement(By.xpath("//*[@data-tests-id='" + requiredElementUniqueId + "']")); +// GeneralUIUtils.hoverOnAreaByTestId(menu); +// } + + public static void fillResourceGeneralInformationPage(ResourceReqDetails resource, User user, boolean isNewResource) { + try { + ResourceGeneralPage.defineName(resource.getName()); + ResourceGeneralPage.defineDescription(resource.getDescription()); + ResourceGeneralPage.defineCategory(resource.getCategories().get(0).getSubcategories().get(0).getName()); + ResourceGeneralPage.defineVendorName(resource.getVendorName()); + ResourceGeneralPage.defineVendorRelease(resource.getVendorRelease()); + if (isNewResource){ + ResourceGeneralPage.defineTagsList(resource, new String[] { "This-is-tag", "another-tag", "Test-automation-tag" }); + } + else{ + ResourceGeneralPage.defineTagsList(resource, new String[] { "one-more-tag" }); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static void fillMaxValueResourceGeneralInformationPage(ResourceReqDetails resource) { + String stringPattern = "ABCDabcd123456"; + GeneralUIUtils.addStringtoClipboard(buildStringFromPattern(stringPattern, 5000)); + ResourceGeneralPage.defineNameWithPaste(); + ResourceGeneralPage.defineDescriptionWithPaste(); + ResourceGeneralPage.defineVendorNameWithPaste(); + ResourceGeneralPage.defineVendorReleaseWithPaste(); +// ResourceGeneralPage.defineName(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineDescription(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineVendorName(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineVendorRelease(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineTagsList(resource, new String[] { buildStringFromPattern(stringPattern, 5000) }); + ResourceGeneralPage.defineTagsListWithPaste(); + GeneralUIUtils.waitForAngular(); + } + + public static String buildStringFromPattern(String stringPattern, int stringLength){ + char[] chars = stringPattern.toCharArray(); + StringBuilder sb = new StringBuilder(); + Random random = new Random(); + for (int i = 0; i < stringLength; i++) { + char c = chars[random.nextInt(chars.length)]; + sb.append(c); + } + return sb.toString(); + } + + public static void fillNewResourceValues(ResourceReqDetails resource, User user) throws Exception { + fillResourceGeneralInformationPage(resource, user, true); + GeneralPageElements.clickCreateButton(); + // selectIcon(); + } + + // coded by teddy. + + public static WebElement waitfunctionforallelements(String element) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 5); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@*='" + element + "']"))); + } + + public static WebElement waitFunctionForaGetElements(String element, int timeout) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout); + return wait.until( + ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + element + "']"))); + } + + public static void getVFCGeneralInfo(ResourceReqDetails resource, User user) throws InterruptedException { + Thread.sleep(2000); + String version = GeneralUIUtils.getWebElementsListByTestID("versionvalue").get(0).getText().substring(1); + String name = GeneralUIUtils.getWebElementByTestID("name").getAttribute("value"); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption() + .getText(); + String vendorName = GeneralUIUtils.getWebElementByTestID("vendorName").getAttribute("value"); + String vendorRelease = GeneralUIUtils.getWebElementByTestID("vendorRelease").getAttribute("value"); + List tags = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-text"); + String type = GeneralUIUtils.getWebElementsListByTestID("type").get(1).getText(); + int index = type.lastIndexOf(":"); + System.out.println(type.substring(0, index)); + String AttContact = GeneralUIUtils.getWebElementByTestID("attContact").getAttribute("value"); + System.out.println(resource.getVersion()); + assertTrue(resource.getVersion().equals(version)); + assertTrue(resource.getName().equals(name)); + assertTrue(resource.getDescription().equals(description)); + System.out.println(resource.getVendorName()); + System.out.println(resource.getVendorRelease()); + assertTrue(resource.getCategories().get(0).getSubcategories().get(0).getName().equals(category)); + assertTrue(resource.getVendorName().equals(vendorName)); + assertTrue(resource.getVendorRelease().equals(vendorRelease)); + assertTrue(resource.getCreatorUserId().equals(AttContact)); + assertEquals(type.substring(0, index), resource.getResourceType()); + + for (int i = 0; i < tags.size(); i++) { + assertEquals(resource.getTags().get(i), tags.get(i).getText()); + } + } + + public static void getGeneralInfo(ResourceReqDetails resource, User user) { + + // clickMore(); + // String + // componentType=waitFunctionForaGetElements("componentType",3).getText(); + // String version=waitFunctionForaGetElements("version",3).getText(); + // String + // category=waitFunctionForaGetElements("category",3).getText();//get + // right panel Category. + // String + // resourceType=waitFunctionForaGetElements("resourceType",3).getText();//get + // right panel SubCategory. + // String date=waitfunctionforelements("creationDate",3).getText(); + // String aouthor=waitfunctionforallelements("author'",3).getText(); + // String + // vendorName=waitFunctionForaGetElements("vendorName",3).getText(); + // String + // vendorRelease=waitFunctionForaGetElements("vendorRelease",3).getText(); + // String + // AttContact=waitFunctionForaGetElements("attContact",3).getText(); + // String + // Description=waitFunctionForaGetElements("description",3).getText(); + List tags = GeneralUIUtils.getWebElementsListByTestID("tag"); + // // String TagVF=waitFunctionForaGetElements("tag",3).getText(); + // assertTrue(componentType.equals("RESOURCE")); + // assertTrue(version.equals(resource.getVersion())); + // assertTrue(category.equals(resource.getCategories().get(0).getName())); + // assertEquals(resourceType,resource.getResourceType()); + // // assertEquals(Date,resource.getCreationDate()); + // // assertEquals(Aouthor,resource.getCreatorFullName()); + // assertTrue(vendorName.equals(resource.getVendorName())); + // assertTrue(vendorRelease.equals(resource.getVendorRelease())); + // assertTrue(AttContact.equals(resource.getAttContact())); + // assertTrue(Description.equals(resource.getDescription()+"\nLess")); + for (WebElement tag : tags) { + System.out.println(resource.getTags().get(0)); + } + } + + public static void getGeneralInfoForTags(ResourceReqDetails resource, User user) { + + clickMore(); + String componentType = waitFunctionForaGetElements("componentType", 3).getText(); + String version = waitFunctionForaGetElements("version", 3).getText(); + String category = waitFunctionForaGetElements("category", 3).getText();// get + // right + // panel + // Category. + String resourceType = waitFunctionForaGetElements("resourceType", 3).getText();// get + // right + // panel + // SubCategory. + String date = GeneralUIUtils.getWebElementByClassName("creationDate").getText(); + String aouthor = waitfunctionforallelements("author'").getText(); + String vendorName = waitFunctionForaGetElements("vendorName", 3).getText(); + String vendorRelease = waitFunctionForaGetElements("vendorRelease", 3).getText(); + String attContact = waitFunctionForaGetElements("attContact", 3).getText(); + String description = waitFunctionForaGetElements("description", 3).getText(); + List tags = GeneralUIUtils.getWebElementsListByTestID("tag"); + assertTrue(componentType.equals("RESOURCE")); + assertTrue(version.equals(resource.getVersion())); + assertTrue(category.equals(resource.getCategories().get(0).getName())); + assertEquals(resourceType, resource.getResourceType()); + // assertEquals(Date,resource.getCreationDate()); + // assertEquals(Aouthor,resource.getCreatorFullName()); + assertTrue(vendorName.equals(resource.getVendorName())); + assertTrue(vendorRelease.equals(resource.getVendorRelease())); + assertTrue(attContact.equals(resource.getContactId())); + assertTrue(description.equals(resource.getDescription() + "\nLess")); + assertTrue(tags.equals("Tag-150")); + } + + public static WebElement searchVFNameInWorkspace(ResourceReqDetails resource, User user) throws Exception { + + List findElements = GeneralUIUtils.getDriver() + .findElements(By.xpath("//div[@data-tests-id='" + resource.getUniqueId() + "']")); + assertNotNull("did not find any elements", findElements); + for (WebElement webElement : findElements) { + if (webElement.getText().contains(resource.getUniqueId())) { + System.out.println("I find it"); + return webElement; + } + } + return null; + } + + public static Boolean searchCheckOutWorkspace(ResourceReqDetails resource, User user, + CheckBoxStatusEnum checkBoxStatusEnum) throws Exception { + + List findElements = GeneralUIUtils.getDriver() + .findElements(By.xpath("//div[@data-tests-id='component.lifecycleState']")); + assertNotNull("did not find any elements", findElements); + for (WebElement webElement : findElements) { + if (!webElement.getAttribute("class").contains(checkBoxStatusEnum.name())) { + return false; + } + } + return true; + } + + // coded by tedy. + public static void validateWithRightPalett(ResourceReqDetails resource, User user) { + // String + // Type=Waitfunctionforallelements("sharingService.selectedEntity.getTypeForView()",3).getText(); + String ResourceType = waitfunctionforallelements("selectedComponent.resourceType").getText(); + System.out.println(ResourceType); + String Version = waitfunctionforallelements("selectedComponent.version").getText(); + String Category = waitfunctionforallelements("selectedComponent.categories[0].name").getText();// get + // right + // panel + // Category. + String CanvasSubCategory = waitfunctionforallelements("selectedComponent.categories[0].subcategories[0].name") + .getText();// get right panel SubCategory. + // String Date=Waitfunctionforelements("selectedComponent.creationDate | + // date: 'MM/dd/yyyy'").getText(); + // String + // Aouthor=waitfunctionforallelements("selectedComponent.creatorFullName'").getText(); + String VendorName = waitfunctionforallelements("selectedComponent.vendorName").getText(); + String VendorRelease = waitfunctionforallelements("selectedComponent.vendorRelease").getText(); + String AttContact = waitfunctionforallelements("selectedComponent.attContact").getText(); + String Description = waitfunctionforallelements("selectedComponent.description").getText(); + String TagVF = waitfunctionforallelements("tag").getText(); + AssertJUnit.assertEquals(ResourceType, resource.getResourceType()); + AssertJUnit.assertEquals(Version, resource.getVersion()); + AssertJUnit.assertEquals(Category, resource.getCategories().get(0).getName()); + AssertJUnit.assertEquals(CanvasSubCategory, + resource.getCategories().get(0).getSubcategories().get(0).getName()); + // assertEquals(Date,resource.getCreationDate()); + // assertEquals(Aouthor,resource.getCreatorFullName()); + AssertJUnit.assertEquals(VendorName, resource.getVendorName()); + AssertJUnit.assertEquals(VendorRelease, resource.getVendorRelease()); + AssertJUnit.assertEquals(AttContact, resource.getContactId()); + AssertJUnit.assertEquals(Description, resource.getDescription() + "\nLess"); + AssertJUnit.assertEquals(TagVF, "qa123"); + } + + public static void clickMore() { + WebElement clickButtonSubmit = GeneralUIUtils.getDriver() + .findElement(By.className("ellipsis-directive-more-less")); + clickButtonSubmit.click(); + } + + public static RestResponse createResourceInUI(ResourceReqDetails resource, User user) + throws Exception, AWTException { + System.out.println("creating resource..."); + fillNewResourceValues(resource, user); + RestResponse getCreatedResource = RestCDUtils.getResource(resource, user); + AssertJUnit.assertEquals("Did not succeed to get any resource", HttpStatus.SC_OK, + getCreatedResource.getErrorCode().intValue()); + + return getCreatedResource; + } + + public static void createResource(ResourceReqDetails resource, User user) throws Exception { + ExtentTestActions.log(Status.INFO, "Going to create a new VF."); + WebElement addVFButton = null; + try { + GeneralUIUtils.ultimateWait(); + try{ + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + addVFButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + } + catch (Exception e){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resource.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "Add VF button is not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + showButtonsADD(); + addVFButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + } + addVFButton.click(); + GeneralUIUtils.ultimateWait(); + } + catch (Exception e ) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on ADD VF button, retrying ... ")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + fillResourceGeneralInformationPage(resource, user, true); + resource.setVersion("0.1"); + GeneralPageElements.clickCreateButton(); + } + + public static void updateResource(ResourceReqDetails resource, User user){ + ResourceGeneralPage.defineContactId(resource.getContactId()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating General screen fields ...")); + fillResourceGeneralInformationPage(resource, user, false); + ResourceGeneralPage.clickUpdateButton(); + } + + + + public static RestResponse updateResourceInformationPage(ResourceReqDetails resource, User user) + throws Exception, AWTException { + + fillResourceGeneralInformationPage(resource, user, true); + GeneralPageElements.clickCreateButton(); + return null; + + } + + public static RestResponse checkInResourceInUI(ResourceReqDetails resource, User user) throws Exception { + + WebElement ASDCLink = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-header-logo-link")); + ASDCLink.click(); + Thread.sleep(2000); + + List listFormInput = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-left-sidebar-nav-item")); + WebElement addPropertyElement = listFormInput.get(0); + addPropertyElement.click(); + Thread.sleep(2000); + + WebElement searchResource = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-header-catalog-search-input")); + searchResource.sendKeys("newresource4test"); + + Thread.sleep(1000); + + WebElement buttonClickMenu = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-dashboard-card-menu-button")); + buttonClickMenu.click(); + + WebElement clickMenu = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-dashboard-card-menu")); + clickMenu.click(); + + List clickCheckIn = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-dashboard-card-menu-item")); + WebElement clickCheckInMenu = clickCheckIn.get(1); + clickCheckInMenu.click(); + + WebElement descriptionForSubmit = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-modal-body-comment")); + descriptionForSubmit.sendKeys("checkin resource"); + Thread.sleep(2000); + WebElement clickButtonSubmitTwo = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-btn-blue")); + clickButtonSubmitTwo.click(); + Thread.sleep(2000); + + WebElement buttonClickMenu1 = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-dashboard-card-menu-button")); + buttonClickMenu1.click(); + + WebElement clickMenu1 = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-dashboard-card-menu")); + clickMenu1.click(); + + List clickCheckOut = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-dashboard-card-menu-item")); + WebElement clickCheckOutMenu = clickCheckOut.get(0); + clickCheckOutMenu.click(); + + Thread.sleep(3000); + RestResponse getResource = RestCDUtils.getResource(resource, user); + AssertJUnit.assertEquals("Did not succeed to get resource after create", 200, + getResource.getErrorCode().intValue()); + return getResource; + + } + + public static String lifeCycleStateUI() throws InterruptedException { + return GeneralUIUtils.getWebElementByTestID("formlifecyclestate").getText(); + } + + public static List catalogFilterResourceCategoriesChecBox(ResourceCategoriesNameEnum enumName) + throws Exception { + List categories = Arrays.asList(); + switch (enumName) { + case APPLICATIONL4: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("applicationServer", "defaulticon", "vl", "cp", "call_controll", "borderElement", + "network", "firewall", "database", "loadBalancer"); + break; + case APPLICATION_SERVER: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("applicationServer", "vl", "cp", "defaulticon"); + break; + case BORDER_ELEMENT: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("borderElement", "vl", "cp", "defaulticon"); + break; + case CALL_CONTROL: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("call_controll", "vl", "cp", "defaulticon"); + break; + case COMMON_NETWORK_RESOURCES: + GeneralUIUtils.getWebElementByLinkText("Common Network Resources").click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case CONNECTION_POINTS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("cp", "defaulticon"); + break; + case DATABASE: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("database", "vl", "cp", "defaulticon"); + break; + case DATABASE_GENERIC: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("database", "vl", "cp", "defaulticon"); + break; + case FIREWALL: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("firewall", "vl", "cp", "defaulticon"); + break; + case GATEWAY: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("gateway", "vl", "cp", "defaulticon"); + break; + case INFRASTRUCTURE: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("connector", "vl", "cp", "defaulticon"); + break; + case INFRASTRUCTUREL23: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("ucpe", "vl", "cp", "defaulticon"); + break; + case LAN_CONNECTORS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "port", "connector", "vl", "cp", "defaulticon"); + break; + case LOAD_BALANCER: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("loadBalancer", "vl", "cp", "defaulticon"); + break; + case MEDIA_SERVERS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case NETWORKL4: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case NETWORK_ELEMENTS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("port", "defaulticon", "network", "connector", "vl", "cp"); + break; + case NETWORK_L23: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "defaulticon", "cp", "router", "port", "connector", "gateway", + "ucpe"); + break; + case NETWORK_CONNECTIVITY: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case GENERIC: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("database", "port", "loadBalancer", "vl", "cp", "objectStorage", "compute", + "defaulticon", "ucpe", "network", "connector"); + break; + case ABSTRACT: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("objectStorage", "compute", "defaulticon", "cp", "vl"); + break; + case Router: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("router", "vl", "cp", "defaulticon"); + break; + case VIRTUAL_LINKS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("vl", "defaulticon"); + break; + case WAN_Connectors: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "port", "connector", "vl", "cp", "defaulticon"); + break; + case WEB_SERVER: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("applicationServer", "vl", "cp", "defaulticon"); + break; + } + return categories; + } + + public static void deleteVersionInUI() throws Exception { + + waitToDeleteVersion().click(); + ResourceUIUtils.clickButtonBlue(); + } + + public static void selectTabInRightPallete(String className) throws Exception { + WebElement tab = GeneralUIUtils.getWebElementByClassName(className); + tab.click(); + } + + public static WebElement waitToDeleteVersion() { + return Waitfunctionforbuttons("//*[@data-tests-id='deleteVersion']", 10); + } + + public static WebElement rihtPanelAPI() { + return waitFunctionForaGetElements("tab-api", 10); + } + + /** + * Click on HTML element. + * + * @param dataTestId + * @throws Exception + */ + public static void getWebElementByTestID(String dataTestId) throws Exception { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 20); + WebElement element = wait + .until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + element.click(); + // wait.until(ExpectedConditions.elemetto) + // WebElement serviceButton = + // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + // + dataTestId + "']")); + // serviceButton. + // serviceButton.click(); + } + + /** + * Move to HTML element by class name. When moving to the HTML element, it + * will raise hover event. + * + * @param className + */ +// public static void moveToHTMLElementByClassName(String className) { +// Actions actions = new Actions(GeneralUIUtils.getDriver()); +// final WebElement createButtonsArea = GeneralUIUtils +// .retryMethodOnException(() -> GeneralUIUtils.getDriver().findElement(By.className(className))); +// actions.moveToElement(createButtonsArea).perform(); +// } + + /** + * Move to HTML element by element id. When moving to the HTML element, it + * will raise hover event. + * + * @param className + */ +// static void moveToHTMLElementByDataTestId(String dataTestId) { +// // WebElement hoverArea = +// // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" +// // + dataTestId + "']")); +// WebElement hoverArea = GeneralUIUtils.waitForElementVisibility(dataTestId); +// // WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), +// // 30); +// // wait.until(ExpectedConditions.visibilityOf(hoverArea)); +// +// Actions actions = new Actions(GeneralUIUtils.getDriver()); +// actions.moveToElement(hoverArea).perform(); +// } + + // public static ResourceReqDetails createResourceInUI(User user){ + // try{ + // ResourceReqDetails defineResourceDetails = + // defineResourceDetails(ResourceTypeEnum.VF); + // ResourceUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new"); + // ResourceUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + // GeneralUIUtils.waitForLoader(); + //// GeneralUIUtils.sleep(1000); + // fillResourceGeneralInformationPage(defineResourceDetails, user); + // GeneralPageElements.clickCreateButton(); + // return defineResourceDetails; + // } + // catch( Exception e){ + // throw new RuntimeException(e); + // } + // } + + /** + * Import VFC + * + * @param user + * @param filePath + * @param fileName + * @return + * @throws Exception + */ + + public static void importVfc(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VFC resource ", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonVFC = GeneralUIUtils.findByText("Import VFC"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + if (!buttonVFC.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "VFC button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting VFC file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralPageElements.clickCreateButton(); + } + + public static void importVfcNoCreate(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + // Insert file to the browse dialog + WebElement buttonVFC = GeneralUIUtils.findByText("Import VFC"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + if (!buttonVFC.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "VFC button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting VFC file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + } + + + public static void importVfFromCsar(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VF asset resource %s", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonDCAE = GeneralUIUtils.findByText("Import DCAE asset"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + if (!buttonDCAE.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "DCAE button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting DCAE file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralPageElements.clickCreateButton(10*60); +// GeneralUIUtils.ultimateWait(); "don't change import of csar can take longer then 3 minutes" + GeneralUIUtils.waitForLoader(10*60); + } + + public static void importVfFromCsarNoCreate(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VF asset resource %s, Create button will not be clicked", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonDCAE = GeneralUIUtils.findByText("Import DCAE asset"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + if (!buttonDCAE.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "DCAE button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting DCAE file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralUIUtils.waitForLoader(10*60); + } + + public static void updateVfWithCsar(String filePath, String fileName) { + ExtentTestActions.log(Status.INFO, "Updating VF with updated CSAR file named " + fileName); + WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.GeneralElementsEnum.UPLOAD_FILE_INPUT.getValue()); + browseWebElement.sendKeys(filePath + fileName); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickUpdateButton(); + GeneralUIUtils.waitForLoader(); + ExtentTestActions.log(Status.INFO, "VF is updated."); + } + + + + // public static ResourceReqDetails importVfcInUI(User user, String + // filePath, String fileName, ResourceTypeEnum resourceType) { + // ResourceReqDetails defineResourceDetails = + // defineResourceDetails(resourceType); + // ResourceUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue()); + // + // // Insert file to the browse dialog + // final WebElement browseWebElement = + // GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + // browseWebElement.sendKeys(filePath + fileName); + // + // // Fill the general page fields. + // GeneralUIUtils.waitForLoader(); + // fillResourceGeneralInformationPage(defineResourceDetails, user); + // GeneralPageElements.clickCreateButton(); + // return defineResourceDetails; + // } + + /** + * Import VF + * + * @param user + * @param filePath + * @param fileName + * @return + * @throws Exception + */ + // public static ResourceReqDetails importVfInUI(User user, String filePath, + // String fileName) throws Exception { + // ResourceReqDetails defineResourceDetails = + // defineResourceDetails(ResourceTypeEnum.VF); + // ResourceUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue()); + // + // // Insert file to the browse dialog + // final WebElement browseWebElement = + // GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + // browseWebElement.sendKeys(filePath + fileName); + // + // // Fill the general page fields. + // GeneralUIUtils.waitForLoader(); + // fillResourceGeneralInformationPage(defineResourceDetails, user); + // GeneralPageElements.clickCreateButton(); + // return defineResourceDetails; + // } + + // public static ResourceReqDetails defineResourceDetails(ResourceTypeEnum + // resourceType) { + // ResourceReqDetails resource = new ResourceReqDetails(); + // resource = ElementFactory.getDefaultResource(NormativeTypesEnum.ROOT, + // ResourceCategoryEnum.APPLICATION_L4_CALL_CONTROL); + // resource.setVersion(INITIAL_VERSION); + // resource.setIcon(ICON_RESOURCE_NAME); + // resource.setResourceType(resourceType.toString()); + // resource.setName(getRandomComponentName(RESOURCE_NAME_PREFIX)); + // + // SetupCDTest.setCreatedComponents(Arrays.asList(resource)); + // + // return resource; + // } + + protected static String getRandomComponentName(String prefix) { + return prefix + new Random().nextInt(10000); + } + + public static ImmutablePair getFirstRIPos(ResourceReqDetails createResourceInUI, User user) { + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String xPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posX"); + String yPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posY"); + return new ImmutablePair(xPosPostDrag, yPosPostDrag); + + } + + public static WebElement getErrorMessageText(WebDriver driver, String text) throws Exception { + + return GeneralUIUtils.getWebElementByClassName(text); + + } + + public static void fillGeneralInfoValuesAndIcon(ResourceReqDetails resource, User user) throws Exception { + fillResourceGeneralInformationPage(resource, user, true); + + GeneralPageElements.clickCreateButton(); + + selectRandomResourceIcon(); + } + + // coded by teddy. + public static void getVFCGeneralInfoAndValidate(ResourceReqDetails resource, User user) + throws InterruptedException { + Thread.sleep(2000); + WebDriver driver = GeneralUIUtils.getDriver(); + String version = GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText(); + String name = GeneralUIUtils.getWebElementByTestID( "name").getAttribute("value"); + String description = GeneralUIUtils.getWebElementByTestID( "description").getAttribute("value"); + String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption() + .getText(); + String vendorName = GeneralUIUtils.getWebElementByTestID( "vendorName").getAttribute("value"); + String vendorRelease = GeneralUIUtils.getWebElementByTestID( "vendorRelease").getAttribute("value"); + List tags = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-text"); + String type = GeneralUIUtils.getWebElementsListByTestID("type").get(1).getText(); + int index = type.lastIndexOf(":"); + System.out.println(type.substring(0, index)); + String AttContact = GeneralUIUtils.getWebElementByTestID( "attContact").getAttribute("value"); + System.out.println(resource.getVersion()); + assertTrue(resource.getVersion().equals(version.substring(1))); + assertTrue(resource.getName().equals(name)); + assertTrue(resource.getDescription().equals(description)); + System.out.println(resource.getVendorName()); + System.out.println(resource.getVendorRelease()); + assertTrue(resource.getCategories().get(0).getSubcategories().get(0).getName().equals(category)); + assertTrue(resource.getVendorName().equals(vendorName)); + assertTrue(resource.getVendorRelease().equals(vendorRelease)); + assertTrue(resource.getCreatorUserId().equals(AttContact)); + assertEquals(type.substring(0, index), resource.getResourceType()); + + for (int i = 0; i < tags.size(); i++) { + assertEquals(resource.getTags().get(i), tags.get(i).getText()); + } + } + + public static RestResponse createResourceNG(ResourceReqDetails resource, User user) throws Exception, AWTException { + + GeneralUIUtils.hoverOnAreaByTestId("w-sdc-dashboard-card-new"); + ResourceUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + fillResourceGeneralInformationPage(resource, user, true); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue()); + return null; + + } + + public static void showButtons(){ + String parentElementClassAttribute = "sdc-dashboard-import-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Input buttons now visible...")); + } + + public static void showButtonsADD(){ + try { + GeneralUIUtils.ultimateWait(); + String parentElementClassAttribute = "sdc-dashboard-create-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + } catch (Exception e ){ + GeneralUIUtils.ultimateWait(); + String parentElementClassAttribute = "sdc-dashboard-create-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + } + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Input buttons now visible...")); + } + + public static void clickOnElementByText(String textToClick, String customizationFoLog){ + String customizationFoLogLocal = customizationFoLog != null ? customizationFoLog : ""; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s %s", textToClick, customizationFoLogLocal)); + GeneralUIUtils.clickOnElementByText(textToClick); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java new file mode 100644 index 0000000000..b2bad99d2a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java @@ -0,0 +1,344 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +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.rest.UserRestUtils; + +import com.aventstack.extentreports.Status; + +public class RestCDUtils { + + private static void setResourceUniqueIdAndUUID(ComponentReqDetails element, RestResponse getResourceResponse) { + element.setUniqueId(ResponseParser.getUniqueIdFromResponse(getResourceResponse)); + element.setUUID(ResponseParser.getUuidFromResponse(getResourceResponse)); + } + + public static RestResponse getResource(ResourceReqDetails resource, User user) { + final String getResourceMsg = "Trying to get resource named " + resource.getName() + " with version " + resource.getVersion(); + final String succeedGetResourceMsg = "Succeeded to get resource named " + resource.getName() + " with version " + resource.getVersion(); + final String failedGetResourceMsg = "Failed to get resource named " + resource.getName() + " with version " + resource.getVersion(); + try { + ExtentTestActions.log(Status.INFO, getResourceMsg); + System.out.println(getResourceMsg); + GeneralUIUtils.sleep(1000); + RestResponse getResourceResponse = null; + String reourceUniqueId = resource.getUniqueId(); + if (reourceUniqueId != null) { + getResourceResponse = ResourceRestUtils.getResource(reourceUniqueId); + if (getResourceResponse.getErrorCode().intValue() == 200) { + ExtentTestActions.log(Status.INFO, succeedGetResourceMsg); + System.out.println(succeedGetResourceMsg); + } + return getResourceResponse; + } + JSONObject getResourceJSONObject = null; + getResourceResponse = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), resource.getName(), resource.getVersion()); + if (getResourceResponse.getErrorCode().intValue() == 200) { +// JSONArray jArray = new JSONArray(getResourceResponse.getResponse()); +// for (int i = 0; i < jArray.length(); i++) { +// getResourceJSONObject = jArray.getJSONObject(i); +// String resourceType = ResponseParser.getValueFromJsonResponse(getResourceJSONObject.toString(), "resourceType"); +// if (resourceType.equals(resource.getResourceType())) { +// getResourceResponse.setResponse(getResourceJSONObject.toString()); + setResourceUniqueIdAndUUID(resource, getResourceResponse); + ExtentTestActions.log(Status.INFO, succeedGetResourceMsg); + System.out.println(succeedGetResourceMsg); + return getResourceResponse; +// } +// } + } + ExtentTestActions.log(Status.INFO, failedGetResourceMsg); + return getResourceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static RestResponse getService(ServiceReqDetails service, User user) { + try { + Thread.sleep(3500); + RestResponse getServiceResponse = ServiceRestUtils.getServiceByNameAndVersion(user, service.getName(), + service.getVersion()); + if (getServiceResponse.getErrorCode().intValue() == 200) { + setResourceUniqueIdAndUUID(service, getServiceResponse); + } + return getServiceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + + public static RestResponse getProduct(ProductReqDetails product, User user) { + try { + Thread.sleep(3500); + RestResponse getProductResponse = ProductRestUtils.getProductByNameAndVersion(product.getName(), + product.getVersion(), user.getUserId()); + if (getProductResponse.getErrorCode().intValue() == 200) { + setResourceUniqueIdAndUUID(product, getProductResponse); + } + return getProductResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static Map getAllElementVersionsFromResponse(RestResponse getResource) throws Exception { + Map versionsMap = new HashMap(); + try { + ObjectMapper mapper = new ObjectMapper(); + + JSONObject object = new JSONObject(getResource.getResponse()); + versionsMap = mapper.readValue(object.get("allVersions").toString(), Map.class); + + } catch (Exception e) { + e.printStackTrace(); + return versionsMap; + + } + + return versionsMap; + } + + public static void deleteElementVersions(Map elementVersions, boolean isBeforeTest, Object clazz, + User user) throws Exception { + Iterator iterator = elementVersions.keySet().iterator(); + while (iterator.hasNext()) { + String singleVersion = iterator.next(); + String uniqueId = elementVersions.get(singleVersion); + RestResponse deleteResponse = null; + if (clazz instanceof ServiceReqDetails) { + deleteResponse = ServiceRestUtils.deleteServiceById(uniqueId, user.getUserId()); + } else if (clazz instanceof ResourceReqDetails) { + deleteResponse = ResourceRestUtils.deleteResource(uniqueId, user.getUserId()); + } else if (clazz instanceof ProductReqDetails) { + deleteResponse = ProductRestUtils.deleteProduct(uniqueId, user.getUserId()); + } + + if (isBeforeTest) { + assertTrue(deleteResponse.getErrorCode().intValue() == 204 + || deleteResponse.getErrorCode().intValue() == 404); + } else { + assertTrue(deleteResponse.getErrorCode().intValue() == 204); + } + } + } + + public static void deleteAllResourceVersionsAfterTest(ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) { + try { + deleteAllComponentVersion(false, componentDetails, getObjectResponse, user); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void deleteAllResourceVersionsBeforeTest(ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + deleteAllComponentVersion(true, componentDetails, getObjectResponse, user); + } + + public static void deleteAllComponentVersion(boolean isBeforeTest, ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + if (getObjectResponse.getErrorCode().intValue() == 404) + return; + Map componentVersionsMap = getAllElementVersionsFromResponse(getObjectResponse); + System.out.println("deleting..."); + deleteElementVersions(componentVersionsMap, isBeforeTest, componentDetails, user); + componentDetails.setUniqueId(null); + } + + + + public static String getExecutionHostAddress() { + + String computerName = null; + try { + computerName = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "·"); + System.out.println(computerName); + if (computerName.indexOf(".") > -1) + computerName = computerName.substring(0, + computerName.indexOf(".")).toUpperCase(); + } catch (UnknownHostException e) { + System.out.println("Uknown hostAddress"); + } + return computerName != null ? computerName : "Uknown hostAddress"; + } + + public static Map> getCatalogAsMap() throws IOException { + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + RestResponse catalog = CatalogRestUtils.getCatalog(defaultAdminUser.getUserId()); + Map> convertCatalogResponseToJavaObject = ResponseParser + .convertCatalogResponseToJavaObject(catalog.getResponse()); + return convertCatalogResponseToJavaObject; + } + + public static Map> getCategories() throws Exception { + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + Map> map = new HashMap>(); + + + RestResponse allResourceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.RESOURCE_PARAM_NAME); + RestResponse allServiceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.SERVICE_PARAM_NAME); + + List parsedResourceCategories = ResponseParser.parseCategories(allResourceCategories); + List parsedServiceCategories = ResponseParser.parseCategories(allServiceCategories); + + map.put(ComponentTypeEnum.RESOURCE_PARAM_NAME, parsedResourceCategories); + map.put(ComponentTypeEnum.SERVICE_PARAM_NAME, parsedServiceCategories); + + return map; + } + + public static void deleteCreatedComponents(Map> map) throws IOException { + + System.out.println("going to delete all created components..."); + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + final String userId = defaultAdminUser.getUserId(); + + List resourcesArrayList = map.get("products"); + List collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("Ci")).map(e -> e.getUniqueId()) + .collect(Collectors.toList()); + for (String uId : collect) { + ProductRestUtils.deleteProduct(uId, userId); + } + + resourcesArrayList = map.get("services"); + collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")).map(e -> e.getUniqueId()) + .collect(Collectors.toList()); + for (String uId : collect) { + ServiceRestUtils.markServiceToDelete(uId, userId); + } + ServiceRestUtils.deleteMarkedServices(userId); + + resourcesArrayList = map.get("resources"); + collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) + .map(e -> e.getUniqueId()).collect(Collectors.toList()); + for (String uId : collect) { + ResourceRestUtils.markResourceToDelete(uId, userId); + } + ResourceRestUtils.deleteMarkedResources(userId); + + + + + + } + + public static void deleteCategoriesByList(List listCategories, String componentType, User user) throws Exception { + + for (CategoryDefinition categoryDefinition : listCategories) { + if (categoryDefinition.getName().toLowerCase().startsWith("ci")) { + List subcategories = categoryDefinition.getSubcategories(); + if (subcategories != null) { + for (SubCategoryDefinition subCategoryDefinition : subcategories) { + + CategoryRestUtils.deleteSubCategory(subCategoryDefinition.getUniqueId(), + categoryDefinition.getUniqueId(), user.getUserId(), + componentType); + } + } + + CategoryRestUtils.deleteCategory(categoryDefinition.getUniqueId(), user.getUserId(), + componentType); + + } + } + } + + public static String getUserRole(User reqUser, User user){ + try{ + RestResponse getUserRoleResp = UserRestUtils.getUserRole(reqUser, user); + JSONObject jObject = new JSONObject(getUserRoleResp.getResponse()); + return jObject.getString("role"); + } + catch(Exception e){ + return null; + } + } + + public static RestResponse getUser(User reqUser, User user){ + try{ + return UserRestUtils.getUser(reqUser, user); + } + catch(Exception e){ + return null; + } + } + + /*************************************/ + + public static void deleteOnDemand() throws IOException { + Config config = DriverFactory.getConfig(); + if(!config.getSystemUnderDebug()){ + deleteCreatedComponents(getCatalogAsMap()); + }else{ + System.out.println("Accordindig to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ..."); + } + } + + public static void deleteCategories(User user) throws Exception { + Map> categoriesMap = getCategories(); + List listCategories = categoriesMap.get(ComponentTypeEnum.RESOURCE_PARAM_NAME); + deleteCategoriesByList(listCategories, ComponentTypeEnum.RESOURCE_PARAM_NAME, user); + listCategories = categoriesMap.get(ComponentTypeEnum.SERVICE_PARAM_NAME); + deleteCategoriesByList(listCategories, ComponentTypeEnum.SERVICE_PARAM_NAME, user); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java new file mode 100644 index 0000000000..8b07e621d9 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java @@ -0,0 +1,286 @@ +/*- + * ============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.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceCategoriesNameEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openqa.selenium.By; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.aventstack.extentreports.Status; + +public class ServiceUIUtils { + + protected static WebDriver driver; + + public ServiceUIUtils(TestName name, String className) { + super(); + } + + public static String defineServiceName(String Name) { + WebElement serviceName = GeneralUIUtils.getWebElementByTestID("name"); + serviceName.clear(); + serviceName.sendKeys(Name); + return Name; + } + + public void moveResourceInstanceToCanvasUI() throws Exception { + List moveResource = driver.findElements(By.className("sprite-resource-icons")); + WebElement moveResourceToCanvasResourceOne = moveResource.get(0); + // WebElement moveResource = + // driver.findElement(By.className("sprite-resource-icons")); + Actions action = new Actions(driver); + action.moveToElement(moveResourceToCanvasResourceOne); + action.clickAndHold(moveResourceToCanvasResourceOne); + action.moveByOffset(635, 375); + action.release(); + action.perform(); + WebElement moveResourceToCanvasResourceTwo = moveResource.get(1); + action.moveToElement(moveResourceToCanvasResourceTwo); + action.clickAndHold(moveResourceToCanvasResourceTwo); + action.moveByOffset(535, 375); + action.release(); + action.perform(); + WebElement moveResourceToCanvasResourceTree = moveResource.get(2); + action.moveToElement(moveResourceToCanvasResourceTree); + action.clickAndHold(moveResourceToCanvasResourceTree); + action.moveByOffset(435, 375); + action.release(); + action.perform(); + Thread.sleep(2000); + } + + public static String catalogFilterServiceCategoriesChecBox(ServiceCategoriesNameEnum enumName) throws Exception { + String Type = null; + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + return Type; + } + + public static List catalogServiceTypeChecBox(ServiceCategoriesNameEnum enumtype) throws Exception { + List categories = null; + switch (enumtype) { + case NETWORK_L13: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("network_l_1-3"); + break; + case NETWORKL4: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("network_l_4 "); + break; + case MOBILITY: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("mobility"); + break; + case VOIPCALL_CONTROL: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("call_controll "); + break; + } + return categories; + } + + public static WebElement waitToNextButtonEnabled() { + return GeneralUIUtils.getWebElementByTestID("Next"); + } + + public static WebElement waitToFinishButtonEnabled() { + return GeneralUIUtils.getWebElementByTestID("Finish"); + } + + public static WebElement deleteServiceInUI() { + + return GeneralUIUtils.getWebElementByTestID("deleteVersion"); + } + + // get the service view data for validate. + // created by tedy. + public static void getServiceGeneralInfo(ServiceReqDetails service, User user) throws InterruptedException { + Thread.sleep(2000); + String version = GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText() + .substring(1); + String name = GeneralUIUtils.getWebElementByTestID("name").getAttribute("value"); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption() + .getText(); + List tags = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-text"); + String type = GeneralUIUtils.getWebElementsListByTestID("type").get(1).getText(); + int index = type.lastIndexOf(":"); + System.out.println(type.substring(0, index)); + String attContact = GeneralUIUtils.getWebElementByTestID("attContact").getAttribute("value"); + String pmatt = GeneralUIUtils.getWebElementByTestID("pmatt").getAttribute("value"); + System.out.println(service.getVersion()); + assertTrue(service.getVersion().equals(version)); + assertTrue(service.getName().equals(name)); + assertTrue(service.getDescription().equals(description)); + assertTrue(service.getCategories().get(0).getName().equals(category)); + System.out.println(service.getContactId()); + assertTrue(service.getContactId().equals(attContact)); + assertTrue(service.getProjectCode().equals(pmatt)); + for (int i = 0; i < tags.size(); i++) { + assertEquals(service.getTags().get(i), tags.get(i).getText()); + } + + } + +// public static void defineTagsList(ServiceReqDetails service, String[] serviceTags) { +// List taglist = new ArrayList(); +// WebElement serviceTagsTextbox = GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); +// for (String tag : serviceTags) { +// serviceTagsTextbox.clear(); +// serviceTagsTextbox.sendKeys(tag); +// GeneralUIUtils.sleep(1000); +// serviceTagsTextbox.sendKeys(Keys.ENTER); +// taglist.add(tag); +// } +// taglist.add(0, service.getName()); +// service.setTags(taglist); +// } + + public static void defineTagsList2(List serviceTags){ + WebElement serviceTagsTextbox = GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); + for (String tag : serviceTags) { + serviceTagsTextbox.clear(); + serviceTagsTextbox.sendKeys(tag); + GeneralUIUtils.waitForAngular(); + serviceTagsTextbox.sendKeys(Keys.ENTER); + } + } + + public static Select defineServiceCategory(String category) { + + return GeneralUIUtils.getSelectList(category, "selectGeneralCategory"); + } + + public static void defineServicePmatt(String pmatt) { + WebElement attPmattTextbox = GeneralUIUtils.getWebElementByTestID("pmatt"); + attPmattTextbox.clear(); + attPmattTextbox.sendKeys(pmatt); + } + + public static void selectRandomResourceIcon() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ICON); + WebDriverWait wait = new WebDriverWait(driver, 6); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"))); + List iconElement = driver.findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")); + iconElement.get(0).click(); + } + + public static String defineDescription(String description) { + WebElement descriptionTextbox = GeneralUIUtils.getWebElementByTestID("description"); + descriptionTextbox.clear(); + descriptionTextbox.sendKeys(description); + return description; + } + + public static void defineContactId(String userId) { + WebElement attContact = GeneralUIUtils.getWebElementByTestID("attContact"); + attContact.clear(); + attContact.sendKeys(userId); + } + + public static WebElement clickAddArtifact() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking Add Artifact button")); + return GeneralUIUtils.getWebElementByTestID("addArtifactButton"); + } + + public static WebElement getArtifactName() { + return GeneralUIUtils.getWebElementByTestID("artifactName"); + } + + public static WebElement getArtifactDetails() { + return GeneralUIUtils.getWebElementByTestID("artifactDisplayName"); + } + + public static void fillServiceGeneralPage(ServiceReqDetails service, User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Fill in metadata values in general page")); + ServiceGeneralPage.defineName(service.getName()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineProjectCode(service.getProjectCode()); + defineTagsList2(service.getTags()); + ServiceGeneralPage.defineContactId(service.getContactId()); + GeneralUIUtils.clickSomewhereOnPage(); + } + + public static void createService(ServiceReqDetails service, User user) throws Exception, AWTException { + clickAddService(); + fillServiceGeneralPage(service, user); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("The service %s was created", service.getName())); + } + + public static void setServiceCategory(ServiceReqDetails service, ServiceCategoriesEnum category){ + CategoryDefinition categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(category.getValue()); + List categories = new ArrayList<>(); + categories.add(categoryDefinition); + service.setCategories(categories); + } + + public static void createServiceWithDefaultTagAndUserId(ServiceReqDetails service, User user) { + clickAddService(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Defining General Page fields")); + ServiceGeneralPage.defineName(service.getName()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineProjectCode(service.getProjectCode()); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickCreateButton(); + } + + public static void clickAddService(){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking the Add Service button")); + try { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exception on catched on Add Service button, retrying ...")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java new file mode 100644 index 0000000000..25f71eeb0a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java @@ -0,0 +1,168 @@ +/*- + * ============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.ci.tests.verificator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.TypesEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.testng.Assert; +import org.testng.TestNGException; + +import com.aventstack.extentreports.Status; + +public class CatalogVerificator { + + public static int getResourceNumber(ResourceTypeEnum resourceType, Map> catalogAsMap) throws Exception { + List resourcesArrayList = catalogAsMap.get("resources"); + return resourcesArrayList.stream(). + filter(s -> ((Resource)s).getResourceType().equals(resourceType)). + collect(Collectors.toList()).size(); + } + + public static int getTypeNumber(TypesEnum enumtype) throws Exception{ + Map> catalogAsMap = RestCDUtils.getCatalogAsMap(); + switch (enumtype) { + case RESOURCE: + return getResourceNumber(catalogAsMap); + case SERVICE: + return getServiceNumber(catalogAsMap); + case PRODUCT: + return getProductsNumber(catalogAsMap); + default: + return getResourceNumber(ResourceTypeEnum.valueOf(enumtype.name()), catalogAsMap); + } + } + + public static int getResourceNumber(Map> catalogAsMap) throws Exception { + return catalogAsMap.get("resources").size(); + } + + public static int getServiceNumber(Map> catalogAsMap) throws Exception { + return catalogAsMap.get("services").size(); + } + + public static int getProductsNumber(Map> catalogAsMap) throws Exception { + return catalogAsMap.get("products").size(); + } + + public static void validateType(TypesEnum enumtype) throws Exception{ + int numberOfElementsFromBE = getTypeNumber(enumtype); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s elements, should be %s ...", enumtype.name(), numberOfElementsFromBE)); + Assert.assertEquals(numberOfElementsFromBE, numberOfElementsFromUI, String.format("Expected : %s, Actual: %s", numberOfElementsFromBE, numberOfElementsFromUI)); + } + + public static int getStatusNumber(List status) throws Exception { + Map> catalogAsMap = RestCDUtils.getCatalogAsMap(); + return catalogAsMap.entrySet().stream(). + map(s -> s.getValue()). + flatMap(List::stream). + filter(s -> status.contains(mapBeLifecycleToUIStatus(s))). + collect(Collectors.toList()).size(); + } + + public static void validateStatus(List status, String checkboxName) throws Exception{ + int numberOfElementsFromBE = getStatusNumber(status); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s elements , should be %s ...", checkboxName, numberOfElementsFromBE)); + Assert.assertEquals(numberOfElementsFromBE, numberOfElementsFromUI, String.format("Expected : %s, Actual: %s", numberOfElementsFromBE, numberOfElementsFromUI)); + } + + public static int getCategoryNumber(String categoryName) throws Exception { + Map> catalogAsMap = RestCDUtils.getCatalogAsMap(); + List serviceAndResourceList = new ArrayList(); + serviceAndResourceList.addAll(catalogAsMap.get("resources")); + serviceAndResourceList.addAll(catalogAsMap.get("services")); + return serviceAndResourceList.stream(). + filter(s -> s.getCategories().get(0).getName().equals(categoryName)). + collect(Collectors.toList()).size(); + } + + public static void validateCategory(String categoryName) throws Exception{ + int numberOfElementsFromBE = getCategoryNumber(categoryName); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s category elements , should be %s ...", categoryName, numberOfElementsFromBE)); + Assert.assertEquals(numberOfElementsFromBE, numberOfElementsFromUI, String.format("Expected : %s, Actual: %s", numberOfElementsFromBE, numberOfElementsFromUI)); + } + + public static int getSubCategoryNumber(String categoryName , String subCategoryName) throws Exception { + Map> catalogAsMap = RestCDUtils.getCatalogAsMap(); + List resourcesArrayList = catalogAsMap.get("resources"); + return resourcesArrayList.stream(). + filter(s -> s.getCategories().get(0).getName().equals(categoryName) && + s.getCategories().get(0).getSubcategories().get(0).getName().equals(subCategoryName)). + collect(Collectors.toList()).size(); + } + + public static void validateSubCategory(String categoryName, String subCategoryName) throws Exception{ + int numberOfElementsFromBE = getSubCategoryNumber(categoryName, subCategoryName); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s/%s subcategory elements , should be %s ...", categoryName, subCategoryName, numberOfElementsFromBE)); + Assert.assertEquals(numberOfElementsFromBE, numberOfElementsFromUI, String.format("Expected : %s, Actual: %s", numberOfElementsFromBE, numberOfElementsFromUI)); + } + + public static int getNumberOfElementsFromCatalogHeader(){ + String elementsAsString = GeneralUIUtils.getWebElementByClassName("w-sdc-dashboard-catalog-header").getText(); + String numberOfElementsAsString = elementsAsString.split(" ")[0]; + if (numberOfElementsAsString.equals("No")){ + return 0; + } else { + return Integer.parseInt(numberOfElementsAsString); + } + } + + private static LifeCycleStateEnum mapBeLifecycleToUIStatus(Component component){ + boolean isServiceAndDistributed = component.getComponentType().equals(ComponentTypeEnum.SERVICE) && + ((Service) component).getDistributionStatus().equals(DistributionStatusEnum.DISTRIBUTED); + switch (component.getLifecycleState()) { + case CERTIFIED: + if (isServiceAndDistributed){ + return LifeCycleStateEnum.DISTRIBUTED; + } else { + return LifeCycleStateEnum.CERTIFIED; + } + case READY_FOR_CERTIFICATION: + return LifeCycleStateEnum.READY_FOR_TESTING; + case CERTIFICATION_IN_PROGRESS: + return LifeCycleStateEnum.IN_TESTING; + case NOT_CERTIFIED_CHECKIN: + return LifeCycleStateEnum.CHECKIN; //to IN DESIGN + case NOT_CERTIFIED_CHECKOUT: + return LifeCycleStateEnum.CHECKOUT; //to IN DESIGN + default: + throw new TestNGException("Missing enum value in enum converter"); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CustomizationUUIDVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CustomizationUUIDVerificator.java new file mode 100644 index 0000000000..9cb305deae --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CustomizationUUIDVerificator.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.ci.tests.verificator; + +import static org.testng.AssertJUnit.assertTrue; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class CustomizationUUIDVerificator { + + public static void validateCustomizationUUIDuniqueness(List customizationUUIDs) { + boolean hasNoDuplicates = CustomizationUUIDVerificator.containsUnique(customizationUUIDs); + assertTrue("There are duplicate customizationUUIDs in list",hasNoDuplicates==true); + } + + public static boolean containsUnique(List list){ + Set set = new HashSet<>(); + + for (T t: list){ + if (!set.add(t)) + return false; + } + + return true; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/DeploymentViewVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/DeploymentViewVerificator.java new file mode 100644 index 0000000000..0d06d8ef96 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/DeploymentViewVerificator.java @@ -0,0 +1,328 @@ +/*- + * ============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.ci.tests.verificator; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentPage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils; +import org.openqa.selenium.WebElement; +import org.testng.SkipException; +import org.testng.TestException; +import org.testng.TestNGException; + +import com.aventstack.extentreports.Status; + +public class DeploymentViewVerificator { + + private static String[] currentProperties = {"isBase", + "vf_module_label", + "vf_module_description", + "min_vf_module_instances", + "max_vf_module_instances", + "initial_count", + "vf_module_type", + "volume_group", + "vfc_list", + "availability_zone_count"}; + + private static Map>> deploymentViewData = new HashMap>>(){ + { + HashMap> segw_heat_c3_base , segw_heat_c3_VMs1 ; + + segw_heat_c3_base = new HashMap>(); + segw_heat_c3_base.put("members", Arrays.asList("segw_internet_security_group", "segw_security_group", "int_layer2vlan_net")); + segw_heat_c3_base.put("artifacts", Arrays.asList("segw_heat_c3_base.yml", "segw_heat_c3_base.env")); + segw_heat_c3_base.put("properties", Arrays.asList(currentProperties)); + put("segw_heat_c3_base", segw_heat_c3_base); + segw_heat_c3_VMs1 = new HashMap>(); + segw_heat_c3_VMs1.put("members", Arrays.asList("segw_oam_protected_0_port", + "fw_oam_int_layer2vlan_1_port", + "segw_0", "segw_internet_1_port", + "segw_layer2vlan_2_port", + "fw_gn_0", "fw_gn_hsl_direct_3_port", + "fw_oam_oam_mgmt_0_port", + "fw_oam_hsl_direct_3_port", + "fw_gn_oam_mgmt_0_port", + "fw_oam_oam_direct_2_port", + "fw_gn_gn_direct_2_port", + "fw_oam_0", + "fw_gn_int_layer2vlan_1_port")); + segw_heat_c3_VMs1.put("artifacts", Arrays.asList("segw_heat_c3_VMs1.yml", "segw_heat_c3_VMs1.env")); + segw_heat_c3_VMs1.put("properties", Arrays.asList(currentProperties)); + put("segw_heat_c3_VMs1", segw_heat_c3_VMs1); + } + }; + + private static Map>> deploymentViewDataMixedArtefects = new HashMap>>(){ + { + HashMap> module_1_ldsa, module_2_ldsa, base_ldsa; + + module_1_ldsa = new HashMap>(); + module_1_ldsa.put("members", new ArrayList(Arrays.asList("ltm_oam_protected_0_port", "ltm_dmz_direct_0_port", "ltm_server_0"))); + module_1_ldsa.put("artifacts", new ArrayList(Arrays.asList("module_1_ldsa.yaml", "module_1_ldsa.env", "base_ldsa.33.yaml", "module_1_ldsa.11.yaml"))); + module_1_ldsa.put("properties", new ArrayList(Arrays.asList(currentProperties))); + put("module_1_ldsa", module_1_ldsa); + module_2_ldsa = new HashMap>(); + module_2_ldsa.put("members", new ArrayList(Arrays.asList("ltm_server_0"))); + module_2_ldsa.put("artifacts", new ArrayList(Arrays.asList("module_2_ldsa.yaml", "module_2_ldsa.env", "base_ldsa.3.yaml", "module_2_ldsa.22.yaml"))); + module_2_ldsa.put("properties", new ArrayList(Arrays.asList(currentProperties))); + put("module_2_ldsa", module_2_ldsa); + base_ldsa = new HashMap>(); + base_ldsa.put("members", new ArrayList(Arrays.asList("ldsa_sec_grp_1"))); + base_ldsa.put("artifacts", new ArrayList(Arrays.asList("base_ldsa.yaml", "module_2_ldsa.2.yaml", "module_1_ldsa.1.yaml"))); + base_ldsa.put("properties", new ArrayList(Arrays.asList(currentProperties))); + put("base_ldsa", base_ldsa); + } + }; + + private Map>> deploymentViewDataFromFile; + + public DeploymentViewVerificator(String pathToCSAR) throws Exception { + deploymentViewDataFromFile = getDeploymentViewDataFromCSAR(pathToCSAR); + } + + public DeploymentViewVerificator() throws Exception { + deploymentViewDataFromFile = deploymentViewDataMixedArtefects; + } + + + public void verifyDeploymentPageSubElements(String moduleName) throws Exception{ + HashMap> moduleProperties = getDeploymentViewData().get(moduleName); + + // add env placeholder to deployment view data + if (!moduleProperties.get("artifacts").contains(moduleName + ".env")){ + moduleProperties.get("artifacts").add(moduleName + ".env"); + } + + List members, artifacts, properties; + members = DeploymentPage.getGroupMembersList(moduleName); + artifacts = DeploymentPage.getArtifactNames(); + properties = DeploymentPage.getPropertyNames(); + + File imageFilePath = GeneralUIUtils.takeScreenshot(moduleName + UUID.randomUUID(), SetupCDTest.getScreenshotFolder(), null); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating group %s, should be %s members, %s artefacts " + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath), + moduleName, moduleProperties.get("members").size(), moduleProperties.get("artifacts").size())); + + assertTrue(moduleProperties.get("artifacts").size() == artifacts.size(), "Artifacts amount not as expected, expected " + moduleProperties.get("artifacts").size()); + assertTrue(moduleProperties.get("artifacts").containsAll(artifacts.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + assertTrue(moduleProperties.get("members").size() == members.size(), "Members amount not as expected, expected " + moduleProperties.get("members").size()); + assertTrue(moduleProperties.get("members").containsAll(members.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + assertTrue(moduleProperties.get("properties").size() == properties.size(), "Properties amount not as expected, expected " + moduleProperties.get("properties").size()); + assertTrue(moduleProperties.get("properties").containsAll(properties.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + DeploymentPage.clickOnProperties(); + DeploymentPage.clickOnArtifacts(); + } + + public void verifyDeploymentPageModules(List modules){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF groups , should be %s groups ", getDeploymentViewData().size())); + assertFalse(modules.isEmpty(), "No modules found"); + assertTrue(modules.size() == getDeploymentViewData().size(), "Modules amount not as expected, expected " + getDeploymentViewData().size()); + for (WebElement module: modules){ + assertTrue(getDeploymentViewData().containsKey(module.getText().split("\\.\\.")[1])); + } + } + + public static void verifyComponentNameChanged(String oldName, String newName){ + try{ + GeneralUIUtils.clickOnElementByText(oldName, 10); + assertTrue(false, "Element name don't changed"); + } catch(Exception e){ + GeneralUIUtils.clickOnElementByText(newName); + } + } + + public Map>> getDeploymentViewData() { +// return deploymentViewData; + return getDeploymentViewDataFromFile(); + } + + public static Map>> buildDeploymentViewDataFromCSAR(String pathToCSAR, File mainServiceTemplate) throws Exception{ + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(mainServiceTemplate); + Map>> deploymentViewDataFromFile = new HashMap>>(); + Map groups = toscaDefinition.getTopology_template().getGroups(); + List keyList = groups.keySet().stream().collect(Collectors.toList()); + HashMap> groupsToArtefacts = getDeploymentArtefactsMapedToGroupsFromCSAR(pathToCSAR); + for(String groupKey: keyList){ + HashMap> tempGroupMap = new HashMap>(); + tempGroupMap.put("artifacts", groupsToArtefacts.get(groupKey)); + if (groups.get(groupKey).getMembers() == null){ + tempGroupMap.put("members", Arrays.asList()); + } else { + tempGroupMap.put("members", groups.get(groupKey).getMembers()); + } + tempGroupMap.put("properties", Arrays.asList(currentProperties)); + deploymentViewDataFromFile.put(groupKey, tempGroupMap); + } + return deploymentViewDataFromFile; + } + + public static HashMap> getDeploymentArtefactsMapedToGroupsFromCSAR(String pathToFile) throws Exception { + Map combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(pathToFile); + LinkedList deploymentArtifacts = ((LinkedList) combinedMap.get("Deployment")); + HashMap> tempGroupMap = new HashMap>(); + for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { + String groupName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().indexOf(".")); + if(deploymentArtifact.getType().equals("HEAT")) { + tempGroupMap.put(groupName, new ArrayList(Arrays.asList(deploymentArtifact.getFileName().trim()))); + } else { + // update current key + tempGroupMap.get(groupName).add(deploymentArtifact.getFileName().trim()); + tempGroupMap.put(groupName, tempGroupMap.get(groupName)); + } + } + return tempGroupMap; + } + + public static Map>> getDeploymentViewDataFromCSAR(String pathToCsar) throws Exception { + String outputFolder = unzipCsarFile(pathToCsar); + + File pathToMainServiceTemplate = new File(outputFolder + File.separator + "Definitions" + File.separator + "MainServiceTemplate.yaml"); + Map>> deploymentViewData = buildDeploymentViewDataFromCSAR(pathToCsar, pathToMainServiceTemplate); + cleanFolders(outputFolder); + + return deploymentViewData; + } + + public static void cleanFolders(String outputFolder) throws IOException { + System.gc(); + FileUtils.cleanDirectory(new File(outputFolder)); + FileUtils.deleteDirectory(new File(outputFolder)); + } + + public static String unzipCsarFile(String pathToCsar) { + File csarFile = new File(pathToCsar); + + + File dir = new File(csarFile.getParent() + File.separator + "output"+UUID.randomUUID() + File.separator + UUID.randomUUID()); + if(!dir.exists()) { + dir.mkdirs(); + } + + String outputFolder = dir.getPath(); + ArtifactFromCsar.unZip(pathToCsar, outputFolder); + return outputFolder; + } + + public static void validateEditPopoverFields(String expectedVNFName, String expectedHeatName, String expectedModuleName){ + String VNFname = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.RESOURCE_NAME_ON_POPOVER.getValue()).getText(); + String heatName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.NAME_INPUT.getValue()).getAttribute("value"); + String moduleName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.MODULE_NAME_ON_POPOVER.getValue()).getText(); + assertTrue(expectedVNFName.equals(VNFname), String.format("VNF name Expected: %s, Actual: %s ", expectedVNFName, VNFname)); + assertTrue(expectedHeatName.equals(heatName), String.format("HEAT name Expected: %s, Actual: %s ", expectedHeatName, heatName )); + assertTrue(expectedModuleName.equals(moduleName), String.format("Module name Expected: %s, Actual: %s ", expectedModuleName, moduleName)); + } + + public static void validateEditPopoverButtons(String newName, String invalidModuleName, String validModueName ){ + DeploymentPage.updateAndCancel(newName, DataTestIdEnum.DeploymentScreen.X_BUTTON); + verifyComponentNameChanged(invalidModuleName, validModueName); + DeploymentPage.clickOnEditIcon(); + DeploymentPage.updateAndCancel(newName, DataTestIdEnum.DeploymentScreen.CANCEL); + verifyComponentNameChanged(invalidModuleName, validModueName); + } + + public static void validateEditPopover() throws Exception{ + String moduleRowText = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()).get(0).getText(); + DeploymentPage.clickOnModuleName(moduleRowText); + DeploymentPage.clickOnEditIcon(); + String[] splitedModuleName = moduleRowText.split("\\.\\."); + + validateEditPopoverFields(splitedModuleName[0], splitedModuleName[1], splitedModuleName[2]); + + String newName = "kuku"; + String newModuleName = DeploymentPage.reconstructModuleName(splitedModuleName, newName); + validateEditPopoverButtons(newName, newModuleName, moduleRowText); + } + + private Map>> getDeploymentViewDataFromFile() { + return deploymentViewDataFromFile; + } + + public static void validateModuleNameUpadate() throws Exception{ + List moduleRowsFromTable = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()); + int i = 0; + for(WebElement moduleRow :moduleRowsFromTable){ + String moduleRowText = moduleRow.getText(); + String updatedName = "updatedName" + i; + DeploymentPage.updateModuleName(moduleRowText, updatedName); + String updatedModuleName = DeploymentPage.reconstructModuleName(moduleRowText.split("\\.\\."), updatedName); + verifyComponentNameChanged(moduleRowText, updatedModuleName); + // Close module + GeneralUIUtils.clickOnElementByText(updatedModuleName); + i++; + } + } + + public static void regularDepoymentScreenVerificator(Map> metaDataFromUI, DeploymentViewVerificator verificator) throws Exception, InterruptedException { + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + List moduleRowsFromTable = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()); + verificator.verifyDeploymentPageModules(moduleRowsFromTable); + for(WebElement moduleRow :moduleRowsFromTable){ + String moduleRowText = moduleRow.getText(); + String middleName = moduleRowText.split("\\.\\.")[1]; + verificator.verifyDeploymentPageSubElements(middleName); + if (metaDataFromUI != null){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating %s group version, should be %s ", moduleRowText, metaDataFromUI.get(moduleRowText.split("\\.\\.")[1]))); + String groupVersion = DeploymentPage.getGroupVersion().split(":")[1].trim(); + String increasedVersion = String.valueOf(Integer.parseInt(metaDataFromUI.get(middleName).get("version")) + 1); + assertTrue(groupVersion.equals(increasedVersion)); + if ( metaDataFromUI.get(middleName).get("moduleID") != "primary"){ + String moduleID = DeploymentPage.getModuleID(); + assertFalse(moduleID.equals(metaDataFromUI.get(middleName).get("moduleID"))); + } + } + // Close module + GeneralUIUtils.clickOnElementByText(moduleRowText); + } + } + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ErrorMessageUIVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ErrorMessageUIVerificator.java new file mode 100644 index 0000000000..f53bfa4e07 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ErrorMessageUIVerificator.java @@ -0,0 +1,64 @@ +/*- + * ============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.ci.tests.verificator; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.ci.tests.datatypes.ErrorMessageProperties; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public class ErrorMessageUIVerificator { + + private static ErrorMessageProperties getErrorByType(ActionStatus errorType){ + try{ + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorType.name()); + String messageId = errorInfo.getMessageId(); + String code = errorInfo.getCode().toString(); + + return new ErrorMessageProperties(messageId, code); + } + catch(Exception e){ + return null; + } + } + + public static void validateErrorMessage(ActionStatus errorMessage) { + String errorMessageBox = null; + try{ + errorMessageBox = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + } + catch(Exception e){ + ExtentTestActions.log(Status.INFO, "Did not find an error message popup."); + Assert.fail("Did not find an error message popup."); + } + + ExtentTestActions.log(Status.INFO, "An error message raised, validating its content."); + ErrorMessageProperties expectedResponseError = getErrorByType(errorMessage); + Assert.assertTrue(errorMessageBox.contains(expectedResponseError.getCode()), "Error message code is not " + expectedResponseError.getCode()); + Assert.assertTrue(errorMessageBox.contains(expectedResponseError.getMessageId()), "Error message ID is not " + expectedResponseError.getMessageId()); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java new file mode 100644 index 0000000000..2c1f59fe9f --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java @@ -0,0 +1,335 @@ +/*- + * ============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.ci.tests.verificator; + +import static org.testng.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.function.Predicate; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; +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.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.PropertiesPopupEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.DeploymentPage; +import org.openecomp.sdc.ci.tests.pages.PropertyPopup; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +import com.aventstack.extentreports.Status; + +public class ServiceVerificator { + + private ServiceVerificator() { + } + + public static void verifyNumOfComponentInstances(ComponentReqDetails component, String version, int numOfVFC, + User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing the number of components on the canvas; should be %s", numOfVFC)); + String responseAfterDrag = null; + component.setVersion(version); + if (component instanceof ServiceReqDetails) { + responseAfterDrag = RestCDUtils.getService((ServiceReqDetails) component, user).getResponse(); + } else if (component instanceof ResourceReqDetails) { + responseAfterDrag = RestCDUtils.getResource((ResourceReqDetails) component, user).getResponse(); + } + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + int size = ((JSONArray) jsonResource.get("componentInstances")).size(); + assertTrue(size == numOfVFC); + ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified."); + } + + public static void verifyServiceUpdatedInUI(ServiceReqDetails service) { + assertTrue(service.getName().equals(ResourceGeneralPage.getNameText())); + assertTrue(service.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertTrue(service.getCategory().equals(ServiceGeneralPage.getCategoryText())); + assertTrue(service.getProjectCode().equals(ServiceGeneralPage.getProjectCodeText())); + for(String tag: ServiceGeneralPage.getTags()){ + assertTrue(service.getTags().contains(tag)); + } + assertTrue(service.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public static void verifyServiceDeletedInUI(ServiceReqDetails service) throws InterruptedException { + Thread.sleep(1000); + List cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.DASHBOARD_CARD.getValue()); + if (!(cardElements.isEmpty())){ + for (WebElement cardElement: cardElements){ + WebElement componentName = GeneralUIUtils.getElementfromElementByCSS(cardElement, + DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + WebElement componentType = GeneralUIUtils.getElementfromElementByCSS(cardElement, + DataTestIdEnum.DashboardCardEnum.ASSET_TYPE_CSS.getValue()); + + String componentNameStr = componentName.getAttribute("textContent").trim(), + componentTypeStr = componentType.getAttribute("class"); + + if(componentTypeStr.equals("S")){ + assertTrue( !(componentNameStr.equals(service.getName())), "Deleted service was found !!!"); + } + } + } + } + + public static void verifyServiceLifecycle(ServiceReqDetails service, User user, LifecycleStateEnum expectedLifecycleState) { + String responseAfterDrag = RestCDUtils.getService(service, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String actualLifecycleState = jsonResource.get("lifecycleState").toString(); + assertTrue(expectedLifecycleState.name().equals(actualLifecycleState), "actual: " + actualLifecycleState + "-- expected: " + expectedLifecycleState); + } + + public static void verifyLinkCreated(ServiceReqDetails createServiceInUI, User user, int expectedRelationsSize) { + String responseAfterDrag = RestCDUtils.getService(createServiceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + assertTrue(((JSONArray) jsonResource.get("componentInstancesRelations")).size() == expectedRelationsSize); + + } + + public static void verifyManagmentWorkflow(String expectedName, String expectedDescription){ + String actualName = GeneralUIUtils.getWebElementBy(By.cssSelector("div[class='text name']")).getText(); + String actualDescription = GeneralUIUtils.getWebElementBy(By.cssSelector("div[class='text description']")).getText(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing name ( should be %s ) and description ( should be %s ) ", expectedName, expectedDescription)); + assertTrue(actualName.equals(expectedName) && actualDescription.equals(expectedDescription)); + } + + public static void verifyVersionUI(String expected){ + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()).getText().replace("V", ""); + assertTrue(actualVersion.equals(expected), String.format( "Expected version: %s, Actual version: %s", expected, actualVersion)); + } + + public static void verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum currentTab) throws Exception{ + List expectedTitles = new ArrayList(); + for(String expectedTitle: currentTab.getTitle()){ + expectedTitles.add(expectedTitle); + } + for (WebElement actualTitle: CompositionPage.getOpenTabTitle()){ + int indexOfTitle = expectedTitles.indexOf(actualTitle.getText()); + assertTrue(indexOfTitle >= 0, "Wrong title"); + expectedTitles.remove(indexOfTitle); + } + assertTrue(expectedTitles.size() == 0, "Missing titles in " + currentTab.getValue()); + } + + public static void verifyDeploymentPageSubElements(String moduleName, DeploymentViewVerificator verificatorObj) throws Exception{ + HashMap> moduleProperties = verificatorObj.getDeploymentViewData().get(moduleName); + + ServiceVerificator.moveMetadataPropertiesArtifactSection(-700); + + List artifacts, properties; + artifacts = DeploymentPage.getArtifactNames(); + properties = DeploymentPage.getPropertyNames(); + assertTrue(moduleProperties.get("artifacts").size() == artifacts.size(), "Artifacts amount not as expected, expected " + moduleProperties.get("artifacts").size()); + assertTrue(moduleProperties.get("artifacts").containsAll(artifacts.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + assertTrue(moduleProperties.get("properties").size() == properties.size(), "Properties amount not as expected, expected " + moduleProperties.get("properties").size()); + assertTrue(moduleProperties.get("properties").containsAll(properties.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + + DeploymentPage.clickOnProperties(); + DeploymentPage.clickOnArtifacts(); + ServiceVerificator.moveMetadataPropertiesArtifactSection(700); + } + + public static void verifyVFModuleCustomizationUUID(ServiceReqDetails service) throws Exception { + Predicate componentInstancePredicate = e -> e.length() > 35; + List customizationUUIDList = getAllVFModuleCustomizationUUIDs(service); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating vfModuleCustomizationUUID uniqness ... ")); + assertTrue(customizationUUIDList.stream().allMatch(componentInstancePredicate), "vfModuleCustomizationUUID is less then 35 chars"); + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDList); + } + + public static List getAllVFModuleCustomizationUUIDs(ServiceReqDetails service) throws Exception { + Service serviceObj = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service.getName(), service.getVersion()); + List customizationUUIDList = serviceObj.getComponentInstances().get(0).getGroupInstances().stream(). + map(e -> e.getCustomizationUUID()). + collect(Collectors.toList()); + + return customizationUUIDList; + } + + public static String getVFModulePropertieValue(ServiceReqDetails service, String propertyName, String moduleName) throws Exception { + Service serviceObj = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service.getName(), service.getVersion()); + List groupInstances = serviceObj.getComponentInstances().get(0).getGroupInstances(); + List groupInstancesProperties = groupInstances.stream(). + filter(e -> e.getName().equals(moduleName)). + findFirst(). + get(). + convertToGroupInstancesProperties(); + String propertieValue = groupInstancesProperties.stream(). + filter(e -> e.getName().equals(propertyName)). + findFirst(). + get(). + getValue(); + return propertieValue; + } + + public static boolean isEqualCustomizationUUIDsAfterChanges(List listBefore, List listAfter){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating if vfModuleCustomizationUUID changed after certification ... ")); + return (listBefore.size() == listAfter.size()) && (listBefore.containsAll(listAfter)); + } + + public static void verifyDisabledServiceProperties() throws Exception{ + List propertiesForCheck = Arrays.asList("isBase", "vf_module_type", "vf_module_label", "vf_module_description"); + List popupElementsForCheck = Arrays.asList(PropertiesPopupEnum.PROPERTY_NAME, + PropertiesPopupEnum.PROPERTY_DESCRIPTION, + PropertiesPopupEnum.PROPERTY_TYPE, + PropertiesPopupEnum.PROPERTY_VALUE); + ServiceVerificator.moveMetadataPropertiesArtifactSection(-700); + List properties = DeploymentPage.getPropertyNames(); + + for(WebElement property : properties){ + if (propertiesForCheck.contains(property.getAttribute("textContent"))){ + DeploymentPage.clickOnProperty(property); + Select propertTypeElement = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_TYPE.getValue())); + boolean isTypeBoolean = propertTypeElement.getFirstSelectedOption().getText().contains("boolean"); + for (PropertiesPopupEnum popupElement: popupElementsForCheck){ + if (isTypeBoolean && popupElement == PropertiesPopupEnum.PROPERTY_VALUE){ + assertTrue(GeneralUIUtils.checkForDisabledAttribute(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_BOOLEAN_VALUE.getValue()), String.format("Element %s not disabled ", property.getText())); + } else { + assertTrue(GeneralUIUtils.checkForDisabledAttribute(popupElement.getValue()), String.format("Element %s not disabled ", property.getText())); + } + } + new PropertyPopup().clickCancel(); + } + } + + DeploymentPage.clickOnProperties(); + ServiceVerificator.moveMetadataPropertiesArtifactSection(700); + } + + public static void verifyEnabledServiceProperties() throws Exception{ + List propertiesForCheck = Arrays.asList("initial_count", "max_vf_module_instances", "min_vf_module_instances"); + + ServiceVerificator.moveMetadataPropertiesArtifactSection(-700); + List properties = DeploymentPage.getPropertyNames(); + + ServiceVerificator.positiveFlow(propertiesForCheck, properties); + ServiceVerificator.negativeFlow(propertiesForCheck, properties); + + DeploymentPage.clickOnProperties(); + ServiceVerificator.moveMetadataPropertiesArtifactSection(700); + } + + public static void positiveFlow(List propertiesForCheck, List properties) + throws InterruptedException { + int baseNumber = new Random().nextInt(100) + 2; + for(WebElement property : properties){ + String propertyName = property.getAttribute("textContent"); + if (propertiesForCheck.contains(propertyName)){ + DeploymentPage.clickOnProperty(property); + int actualNumber = 0; + if (propertyName.equals("initial_count")){ + actualNumber = baseNumber; + } else if (propertyName.equals("max_vf_module_instances")) { + actualNumber = baseNumber + 1; + } else if (propertyName.equals("min_vf_module_instances")){ + actualNumber = baseNumber - 1; + } + + new PropertyPopup().insertPropertyDefaultValue(String.valueOf(actualNumber)); + new PropertyPopup().clickSave(); + assertTrue(DeploymentPage.getPropertyValueFromPropertiesList(propertyName).equals(String.valueOf(actualNumber))); + } + } + } + + public static void negativeFlow(List propertiesForCheck, List properties) + throws Exception { + int currentMaxValue = Integer.valueOf(DeploymentPage.getPropertyValueFromPropertiesList("max_vf_module_instances")); + int currentMinValue = Integer.valueOf(DeploymentPage.getPropertyValueFromPropertiesList("min_vf_module_instances")); + int currentInitialValue = Integer.valueOf(DeploymentPage.getPropertyValueFromPropertiesList("initial_count")); + PropertyPopup propertyPopupObj = new PropertyPopup(); + + for(WebElement property : properties){ + String propertyName = property.getAttribute("textContent"); + if (propertiesForCheck.contains(propertyName)){ + DeploymentPage.clickOnProperty(property); + if (propertyName.equals("initial_count")){ + + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMaxValue + 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMinValue - 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(0)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + + } else if (propertyName.equals("max_vf_module_instances")) { + + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentInitialValue - 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMinValue - 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(0)); + verifyErrorPresentAndSaveDisabled(); + + } else if (propertyName.equals("min_vf_module_instances")){ + + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentInitialValue + 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMaxValue + 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + } + + new PropertyPopup().clickCancel(); + } + } + } + + public static void verifyErrorPresentAndSaveDisabled() throws Exception{ + assertTrue(DeploymentPage.isPropertySaveButtonDisabled()); + assertTrue(DeploymentPage.getPropertyErrorValidationMessdge().size() == 1); + } + + public static void moveMetadataPropertiesArtifactSection(int offset) throws InterruptedException { + WebElement dragLineElement = GeneralUIUtils.getElementByCSS("div.rg-top"); + GeneralUIUtils.dragAndDropElementByY(dragLineElement, offset); + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/UserManagementVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/UserManagementVerificator.java new file mode 100644 index 0000000000..3b0b458f1e --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/UserManagementVerificator.java @@ -0,0 +1,152 @@ +/*- + * ============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.ci.tests.verificator; + +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang3.text.WordUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.pages.AdminGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public class UserManagementVerificator { + + + + public static void validateUserCreated(String userId, UserRoleEnum role){ + + ExtentTestActions.log(Status.INFO, "Validating that a new user is created and displayed in the first row in the table."); + + final int firstRow = 0; + + WebElement actualFirstName = AdminGeneralPage.getUserManagementTab().getFirstName(firstRow); + WebElement actualLastName = AdminGeneralPage.getUserManagementTab().getLastName(firstRow); + WebElement actualUserId = AdminGeneralPage.getUserManagementTab().getUserId(firstRow); + WebElement actualEmail = AdminGeneralPage.getUserManagementTab().getEmail(firstRow); + WebElement actualRole = AdminGeneralPage.getUserManagementTab().getRole(firstRow); + WebElement actualLastActive = AdminGeneralPage.getUserManagementTab().getLastActive(firstRow); + + + String actualFirstNameText = actualFirstName.getText(); + String actualLastNameText = actualLastName.getText(); + String actualUserIdText = actualUserId.getText(); + String actualEmailText = actualEmail.getText(); + String actualRoleText = actualRole.getText(); + String actualLastActiveText = actualLastActive.getText(); + + Assert.assertTrue(actualFirstNameText.equals("---"), "Actual first name is not '---'."); + Assert.assertTrue(actualLastNameText.equals("---"), "Actual last name is not '---'."); + Assert.assertTrue(actualUserIdText.equals(userId), "Actual user id is not " + userId); + Assert.assertTrue(actualEmailText.equals("---"), "Actual email is not '---'."); + Assert.assertTrue(actualRoleText.equals(WordUtils.capitalize(role.name().toLowerCase())), "Actual role is not " + role.name()); + Assert.assertTrue(actualLastActiveText.equals("Waiting"), "Actual role is not 'Waiting'."); + } + + + public static void validateUserRoleUpdated(int rowIndx, UserRoleEnum updatedRole){ + ExtentTestActions.log(Status.INFO, "Validating role is updated to " + updatedRole.name() + " in UI."); + WebElement actualRole = AdminGeneralPage.getUserManagementTab().getRole(rowIndx); + String actualRoleText = actualRole.getText(); + Assert.assertTrue(actualRoleText.equals(WordUtils.capitalize(updatedRole.name().toLowerCase())), "Actual role is not " + updatedRole.name()); + } + + public static void validateUserRoleUpdatedViaRest(User reqUser, User user, UserRoleEnum expectedUserRole){ + try{ + ExtentTestActions.log(Status.INFO, "Validating role is updated to " + expectedUserRole.name() + " in BE."); + String actualUserRole = RestCDUtils.getUserRole(reqUser, user); + Assert.assertTrue(expectedUserRole.name().toLowerCase().equals(actualUserRole.toLowerCase()), "User role is not updated."); + } + catch(Exception e){ + Assert.fail("The actual user role is null"); + } + } + + public static void validateUserNotFoundViaRest(User reqUser, User user){ + try{ + ExtentTestActions.log(Status.INFO, "Validating user " + reqUser.getUserId() + " is not found in BE."); + RestResponse getUserResp = RestCDUtils.getUser(reqUser, user); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), Arrays.asList(reqUser.getUserId()), getUserResp.getResponse()); + } + catch(Exception e){ + Assert.fail("The response message does not describe the user is not found."); + } + } + + public static void validateUserIdNotFound(String userId){ + ExtentTestActions.log(Status.INFO, "Validating that user " + userId + " is not found."); + AdminGeneralPage.getUserManagementTab().searchUser(userId); + List rows = AdminGeneralPage.getUserManagementTab().getAllRowsDisplayed(); + Assert.assertEquals(rows.size(), 0, String.format("There are %s rows instead of none.", rows.size())); + } + + public static void validateOnlySingleRowDisplayed(){ + ExtentTestActions.log(Status.INFO, "Validating that only a single row is displayed in table."); + List rows = AdminGeneralPage.getUserManagementTab().getAllRowsDisplayed(); + Assert.assertEquals(rows.size(), 1, String.format("There are %s rows instead of %s.", rows.size(), 1)); + } + + public static void validateRowDisplayedCorrectly(User user, int rowindex){ + String role = user.getRole(); + String userId = user.getUserId(); + String firstName = user.getFirstName(); + String lastName = user.getLastName(); + String email = user.getEmail(); + + ExtentTestActions.log(Status.INFO, "Validating that the row is properly displayed."); + + WebElement actualFirstName = AdminGeneralPage.getUserManagementTab().getFirstName(rowindex); + WebElement actualLastName = AdminGeneralPage.getUserManagementTab().getLastName(rowindex); + WebElement actualUserId = AdminGeneralPage.getUserManagementTab().getUserId(rowindex); + WebElement actualEmail = AdminGeneralPage.getUserManagementTab().getEmail(rowindex); + WebElement actualRole = AdminGeneralPage.getUserManagementTab().getRole(rowindex); + + + String actualFirstNameText = actualFirstName.getText(); + String actualLastNameText = actualLastName.getText(); + String actualUserIdText = actualUserId.getText(); + String actualEmailText = actualEmail.getText(); + String actualRoleText = actualRole.getText(); + + Assert.assertTrue(actualFirstNameText.equals(firstName), "Actual first name is not " + firstName); + Assert.assertTrue(actualLastNameText.equals(lastName), "Actual last name is not " + lastName); + Assert.assertTrue(actualUserIdText.equals(userId), "Actual user id is not " + userId); + Assert.assertTrue(actualEmailText.contains(email), "Actual email does not contain " + email); + Assert.assertTrue(actualRoleText.equals(WordUtils.capitalize(role.toLowerCase())), "Actual role is not " + role); + } + + public static void validateFirstRowDisplayedCorrectly(User user){ + validateRowDisplayedCorrectly(user, 0); + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCArtifactVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCArtifactVerificator.java new file mode 100644 index 0000000000..ac009c6327 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCArtifactVerificator.java @@ -0,0 +1,347 @@ +/*- + * ============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.ci.tests.verificator; + +import static org.testng.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VFCArtifact; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public class VFCArtifactVerificator { + + private static final String ARTIFACTS = "artifacts"; + private static final String DEPLOYMENT_ARTIFACTS = "deploymentArtifacts"; + private static List vfcArtifactList = new ArrayList(); + private static JSONObject jsonResource; + + public static void verifyVFCArtifactsNotInVFArtifactList(ResourceReqDetails resource , User user, RestResponse optionalGetResponse, Map> expectedArtifactMap){ + ExtentTestActions.log(Status.INFO, "Verifying that VFC artifacts are not as part of VF artifacts."); + LinkedList expectedDeploymentArtifacts = expectedArtifactMap.get(DEPLOYMENT_ARTIFACTS); + LinkedList expectedInformationalArtifacts = expectedArtifactMap.get(ARTIFACTS); + + Map vfDepArtifacts = getVFDeploymentArtifacts(resource, user, optionalGetResponse); + for (Object artifact : vfDepArtifacts.values()){ + JSONObject acArtifact = ((JSONObject) JSONValue.parse(artifact.toString())); + String acArtifactName = acArtifact.get("artifactName").toString(); + + for(HeatMetaFirstLevelDefinition exDepArtifact : expectedDeploymentArtifacts){ + assertTrue(!exDepArtifact.getType().equals(acArtifactName)); + } + } + + Map vfInfoArtifacts = getVFInforamtionalArtifacts(resource, user, optionalGetResponse); + for (Object artifact : vfInfoArtifacts.values()){ + JSONObject acArtifact = ((JSONObject) JSONValue.parse(artifact.toString())); + if (acArtifact.containsKey("artifactName")){ + String acArtifactName = acArtifact.get("artifactName").toString(); + + for(HeatMetaFirstLevelDefinition exInfoArtifact : expectedInformationalArtifacts){ + assertTrue(!exInfoArtifact.getType().equals(acArtifactName)); + } + } + + + } + + + + } + + public static void verifyVfcArtifactUpdated(String instanceName, ResourceReqDetails resource, User user){ + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts are updated."); + List vfcArtifactsBeforeUpdate = getVfcArtifactList(); + + setVfcArtifactList(new ArrayList()); + setActualVfcArtifactList(instanceName, resource, user); + + for (VFCArtifact artifact : vfcArtifactsBeforeUpdate){ + String artifactnameBeforeUpdate = artifact.getArtifactname(); + for (VFCArtifact newArtifact : vfcArtifactList){ + String artifactnameAfterUpdate = newArtifact.getArtifactname(); + if (artifactnameBeforeUpdate.equals(artifactnameAfterUpdate)){ + String artifactUUIDAfterUpdate = newArtifact.getArtifactUUID(); + assertTrue(!artifactUUIDAfterUpdate.equals(artifact.getArtifactUUID())); + + int artifactVersionAfterUpdate = Integer.parseInt(newArtifact.getArtifactVersion()); + int artifactVersionBeforeUpdate = Integer.parseInt(artifact.getArtifactVersion()); + assertTrue(artifactVersionAfterUpdate == artifactVersionBeforeUpdate + 1); + + + vfcArtifactList.remove(newArtifact); + + ExtentTestActions.log(Status.INFO, "VFC artifacts are updated and verified."); + + break; + } + } + } + + + assertTrue(vfcArtifactList.size() == 0); + + } + + public static void verifyVFCArtifactNotChanged(String instanceName, ResourceReqDetails resource, User user){ + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts are not chaned after update."); + List vfcArtifactsBeforeUpdate = getVfcArtifactList(); + + setVfcArtifactList(new ArrayList()); + setActualVfcArtifactList(instanceName, resource, user); + + for (VFCArtifact artifact : vfcArtifactsBeforeUpdate){ + String artifactnameBeforeUpdate = artifact.getArtifactname(); + for (VFCArtifact newArtifact : vfcArtifactList){ + String artifactnameAfterUpdate = newArtifact.getArtifactname(); + if (artifactnameBeforeUpdate.equals(artifactnameAfterUpdate)){ + String artifactUUIDAfterUpdate = newArtifact.getArtifactUUID(); + assertTrue(artifactUUIDAfterUpdate.equals(artifact.getArtifactUUID())); + + int artifactVersionAfterUpdate = Integer.parseInt(newArtifact.getArtifactVersion()); + int artifactVersionBeforeUpdate = Integer.parseInt(artifact.getArtifactVersion()); + assertTrue(artifactVersionAfterUpdate == artifactVersionBeforeUpdate); + + vfcArtifactList.remove(newArtifact); + break; + } + } + } + + + assertTrue(vfcArtifactList.size() == 0); + + } + + public static void verifyNoVfcArtifacts(ResourceReqDetails resource , User user, RestResponse optionalGetResponse){ + ExtentTestActions.log(Status.INFO, "Verifying that there are no VFC artifacts at all."); + JSONArray jArr = getVFInstances(resource, user, optionalGetResponse); + for (Object instanceObj : jArr){ + JSONObject instance = (JSONObject) JSONValue.parse(instanceObj.toString()); + List actualDeploymentArtifacts = getActualVfcInstanceArtifactsFromJson(DEPLOYMENT_ARTIFACTS, instance); + + assertTrue(actualDeploymentArtifacts == null || actualDeploymentArtifacts.size() == 0); + } + } + + public static void verifyVfcArtifacts(ResourceReqDetails resource , User user, String instanceName, Map> expectedArtifactMap, + RestResponse optionalGetResponse){ + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts for instance named " + instanceName); + + String exCompName = instanceName.split(".vfc.")[1].toLowerCase(); + String exName = instanceName.split(".heat.")[1].toLowerCase(); + + JSONArray jArr = getVFInstances(resource, user, optionalGetResponse); + int jArrSize = jArr.size(); + + for (Object instanceObj : jArr){ + JSONObject instance = (JSONObject) JSONValue.parse(instanceObj.toString()); + String componentName = instance.get("componentName").toString().toLowerCase(); + String name = instance.get("name").toString().toLowerCase(); + + if (componentName.contains(exCompName) || name.toLowerCase().equals(exName)){ + + List actualDeploymentArtifacts = getActualVfcInstanceArtifactsFromJson(DEPLOYMENT_ARTIFACTS, instance); + LinkedList expectedDeploymentArtifacts = expectedArtifactMap.get(DEPLOYMENT_ARTIFACTS); + checkVFCArtifactsExist(expectedDeploymentArtifacts, actualDeploymentArtifacts); + + + List actualInformationalArtifacts = getActualVfcInstanceArtifactsFromJson(ARTIFACTS, instance); + LinkedList expectedInformationalArtifacts = expectedArtifactMap.get(ARTIFACTS); + checkVFCArtifactsExist(expectedInformationalArtifacts, actualInformationalArtifacts); + + jArr.remove(instanceObj); + + ExtentTestActions.log(Status.INFO, "VFC artifacts for instance named " + instanceName + "are verified."); + + break; + } + } + + assertTrue(jArr.size() == jArrSize - 1, "Instance " + instanceName + " was not found and tested"); + + } + + + + private static JSONArray getVFInstances(ResourceReqDetails resource, User user, RestResponse response) { + + jsonResource = getVFAsJsonObject(resource, user, response); + JSONArray jArr = (JSONArray) jsonResource.get("componentInstances"); + return jArr; + } + + private static Map getVFDeploymentArtifacts(ResourceReqDetails resource, User user, RestResponse response) { + + jsonResource = getVFAsJsonObject(resource, user, response); + Map jArr = (Map) jsonResource.get(DEPLOYMENT_ARTIFACTS); + return jArr; + } + + private static Map getVFInforamtionalArtifacts(ResourceReqDetails resource, User user, RestResponse response) { + + jsonResource = getVFAsJsonObject(resource, user, response); + Map jArr = (Map) jsonResource.get(ARTIFACTS); + return jArr; + } + + private static JSONObject getVFAsJsonObject(ResourceReqDetails resource, User user, RestResponse response) { + if (response == null){ + resource.setUniqueId(null); + response = RestCDUtils.getResource(resource, user); + assertTrue(response.getErrorCode().intValue() == 200); + getVFAsJsonObject(resource, user, response); + } + + String responseAfterDrag = response.getResponse(); + jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + return jsonResource; + } + + + + private static List getActualVfcInstanceArtifactsFromJson(String artifactKind, JSONObject instanceFromJson){ + Object actualtObject = instanceFromJson.get(artifactKind); + if (actualtObject != null){ + JSONObject actualJsonObject = (JSONObject) JSONValue.parse(actualtObject.toString()); + List actualArtifacts = (List) actualJsonObject.keySet().stream().map(e -> actualJsonObject.get(e).toString()).collect(Collectors.toList()); + return actualArtifacts; + } + return null; + } + + private static void checkVFCArtifactsExist(LinkedList expectedArtifacts, List actualArtifacts) { + if (expectedArtifacts == null){ + return; + } + + if (expectedArtifacts.size() != actualArtifacts.size()){ + ExtentTestActions.log(Status.FAIL, "Expected and actual VFC artifacts lists size are not the same. Expected size: " + expectedArtifacts.size() + " , actual size: " + actualArtifacts.size()); + Assert.fail("Expected and actual VFC artifacts lists size are not the same. Expected size: " + expectedArtifacts.size() + " , actual size: " + actualArtifacts.size()); + } + + List types = new ArrayList(); + List fileNames = new ArrayList(); + for (HeatMetaFirstLevelDefinition exArtifact : expectedArtifacts){ + + fileNames.add(exArtifact.getFileName()); + types.add(exArtifact.getType()); + + } + + for (int i = 0 ; i < actualArtifacts.size() ; i++){ + String actualArtifactsString = actualArtifacts.get(i); + JSONObject acArtifact = ((JSONObject) JSONValue.parse(actualArtifactsString)); + + String acArtifactFileName = acArtifact.get("artifactName").toString(); + String acArtifactType = acArtifact.get("artifactType").toString(); + + assertTrue(types.contains(acArtifactType), "List does not contain " + acArtifactType); + assertTrue(fileNames.contains(acArtifactFileName), "List does not contain " + acArtifactFileName); + + types.remove(acArtifactType); + fileNames.remove(acArtifactFileName); + + } + + assertTrue(types.size() == 0); + assertTrue(fileNames.size() == 0); + + } + + public static List getVfcArtifactList(){ + return vfcArtifactList; + } + + + public static void setVfcArtifactList(List vfcArtifactList) { + VFCArtifactVerificator.vfcArtifactList = vfcArtifactList; + } + + public static void setActualVfcArtifactList(String instanceName, ResourceReqDetails resource , User user) { + String exCompName = instanceName.split(".vfc.")[1].toLowerCase(); + String exName = instanceName.split(".heat.")[1].toLowerCase(); + + JSONArray jArr = getVFInstances(resource, user, null); + + for (Object instanceObj : jArr){ + JSONObject instance = (JSONObject) JSONValue.parse(instanceObj.toString()); + String componentName = instance.get("componentName").toString().toLowerCase(); + String name = instance.get("name").toString().toLowerCase(); + + if (componentName.contains(exCompName) || name.toLowerCase().equals(exName)){ + List actualDeploymentArtifacts = getActualVfcInstanceArtifactsFromJson(DEPLOYMENT_ARTIFACTS, instance); + List actualInformationalArtifacts = getActualVfcInstanceArtifactsFromJson(ARTIFACTS, instance); + + if (actualDeploymentArtifacts != null){ + for (int i = 0 ; i < actualDeploymentArtifacts.size() ; i++){ + String actualArtifactsString = actualDeploymentArtifacts.get(i); + JSONObject acArtifact = ((JSONObject) JSONValue.parse(actualArtifactsString)); + + if (acArtifact.containsKey("artifactName")){ + String acArtifactType = acArtifact.get("artifactName").toString(); + String acArtifactFileName = acArtifact.get("artifactType").toString(); + String acArtifactUUID = acArtifact.get("artifactUUID").toString(); + String acArtifactVersion = acArtifact.get("artifactVersion").toString(); + + vfcArtifactList.add(new VFCArtifact(acArtifactType, acArtifactFileName, acArtifactUUID, acArtifactVersion)); + } + } + } + if (actualInformationalArtifacts != null){ + for (int i = 0 ; i < actualInformationalArtifacts.size() ; i++){ + String actualArtifactsString = actualInformationalArtifacts.get(i); + JSONObject acArtifact = ((JSONObject) JSONValue.parse(actualArtifactsString)); + + if (acArtifact.containsKey("artifactName")){ + String acArtifactType = acArtifact.get("artifactName").toString(); + String acArtifactFileName = acArtifact.get("artifactType").toString(); + String acArtifactUUID = acArtifact.get("artifactUUID").toString(); + String acArtifactVersion = acArtifact.get("artifactVersion").toString(); + vfcArtifactList.add(new VFCArtifact(acArtifactType, acArtifactFileName, acArtifactUUID, acArtifactVersion)); + } + + + } + } + } + } + } + +} + + + diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCverificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCverificator.java new file mode 100644 index 0000000000..0872a3a5c3 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VFCverificator.java @@ -0,0 +1,37 @@ +/*- + * ============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.ci.tests.verificator; + +import static org.testng.AssertJUnit.assertFalse; + +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; + + +public class VFCverificator { + + public static void verifyVFCUpdatedInUI(ResourceReqDetails vf) { + assertFalse(vf.getName().equals(ResourceGeneralPage.getNameText())); + assertFalse(vf.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertFalse(vf.getVendorName().equals(ResourceGeneralPage.getVendorNameText())); + assertFalse(vf.getVendorRelease().equals(ResourceGeneralPage.getVendorReleaseText())); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfModuleVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfModuleVerificator.java new file mode 100644 index 0000000000..7f01b86eaf --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfModuleVerificator.java @@ -0,0 +1,156 @@ +/*- + * ============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.ci.tests.verificator; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupProperty; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaGroupsMetadataDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils; + +import com.aventstack.extentreports.Status; + +public class VfModuleVerificator { + + private static final String [] PROPERTY_TYPES = {"vf_module_label", "min_vf_module_instances", "max_vf_module_instances", "initial_count"}; + private static final String VF_MODULE_TYPE = "org.openecomp.groups.VfModule"; + + /** + * compare number of groups from HEAT.meta file vs TOSCA yaml groups generated by ASDC + * @param listTypeHeatMetaDefinition - java object created from HEAT.meta file + * @param toscaDefinition - java object created from TOSCA yaml + */ + public static void compareNumberOfVfModules(List listTypeHeatMetaDefinition, ToscaDefinition toscaDefinition) { + + int heatMetaGroupCount = 0; + int toscaDefinitionGroupCount = 0; + for (TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition) { + heatMetaGroupCount = typeHeatMetaDefinition.getGroupHeatMetaDefinition().size(); + } + toscaDefinitionGroupCount = toscaDefinition.getTopology_template().getGroups().size(); + assertEquals("Expected num of groups in HEAT.meta file is " + heatMetaGroupCount + ", but was in TOSCA yaml file " + toscaDefinitionGroupCount, heatMetaGroupCount, toscaDefinitionGroupCount); + } + + /** + * check group structure and "metadata" parameters vs data on the service object + * @param toscaDefinition + */ + public static void verifyGroupMetadata(ToscaDefinition toscaDefinition, Service service) { + + Map groups = toscaDefinition.getTopology_template().getGroups(); + for (Map.Entry groupTopologyTemplateDefinition : groups.entrySet()) { + String key = groupTopologyTemplateDefinition.getKey(); + GroupInstance groupInstanceObject = getGroupInstanceByKey(key, service); + ToscaGroupsMetadataDefinition metadata = groupTopologyTemplateDefinition.getValue().getMetadata(); + assertNotNull("groupInstanceObject is null", groupInstanceObject); + assertTrue("expected vfModuleModelName " + groupInstanceObject.getGroupName() + ", actual " + metadata.getVfModuleModelName(), groupInstanceObject.getGroupName().equals(metadata.getVfModuleModelName())); + assertTrue("expected vfModuleModelInvariantUUID " + groupInstanceObject.getInvariantUUID() + ", actual " + metadata.getVfModuleModelInvariantUUID(), groupInstanceObject.getInvariantUUID().equals(metadata.getVfModuleModelInvariantUUID())); + assertTrue("expected vfModuleModelCustomizationUUID " + groupInstanceObject.getCustomizationUUID() + ", actual " + metadata.getVfModuleModelCustomizationUUID(), groupInstanceObject.getCustomizationUUID().equals(metadata.getVfModuleModelCustomizationUUID())); + assertTrue("expected vfModuleModelUUID " + groupInstanceObject.getGroupUUID() + ", actual " + metadata.getVfModuleModelUUID(), groupInstanceObject.getGroupUUID().equals(metadata.getVfModuleModelUUID())); + assertTrue("expected vfModuleModelVersion " + groupInstanceObject.getVersion() + ", actual " + metadata.getVfModuleModelVersion(), groupInstanceObject.getVersion().equals(metadata.getVfModuleModelVersion())); + } + } + + + /** + * @param key + * @param service + * @return + */ + public static GroupInstance getGroupInstanceByKey(String key, Service service) { + for(ComponentInstance componentInstance : service.getComponentInstances()){ + for(GroupInstance groupInstance : componentInstance.getGroupInstances()){ + if( key.equals(groupInstance.getName())){ + return groupInstance; + } + } + } + return null; + } + + public static void validateSpecificModulePropertiesFromRequest(Resource resource) { + List> allProperties = resource.getGroups().stream(). + filter(e -> e.getType().equals(VF_MODULE_TYPE)). + map(e -> e.getProperties()). + collect(Collectors.toList()); + for(String propertyType :PROPERTY_TYPES){ + int numberOfTypes = getPropertyType(allProperties, propertyType).size(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF property %s exist, Expected: %s, Actual: %s ", propertyType, allProperties.size(), numberOfTypes)); + assertTrue(numberOfTypes == allProperties.size()); + } + } + + public static List getPropertyType(List> allProperties, String propertyType) { + return allProperties.stream(). + flatMap(List::stream). + filter(e -> e.getName().equals(propertyType)). + collect(Collectors.toList()); + } + + public static void validateSpecificModulePropertiesFromFile(ToscaDefinition toscaDefinition){ + List vfModules = toscaDefinition.getTopology_template().getGroups().values().stream(). + filter(e -> e.getType().equals(VF_MODULE_TYPE)). + collect(Collectors.toList()); + + for(String propertyType :PROPERTY_TYPES){ + int numberOfTypes = (int) vfModules.stream(). + filter(e -> e.getProperties().containsKey(propertyType)). + count(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF property %s exist, Expected: %s, Actual: %s ", propertyType, vfModules.size(), numberOfTypes)); + assertTrue(numberOfTypes == vfModules.size()); + } + } + + public static ToscaDefinition getToscaTemplate(String pathToCsar) throws Exception { + String outputFolder = DeploymentViewVerificator.unzipCsarFile(pathToCsar); + String templateFileName = VfModuleVerificator.getTemplateFilenname(pathToCsar); + + File pathToMainServiceTemplate = new File(outputFolder + File.separator + "Definitions" + File.separator + templateFileName); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(pathToMainServiceTemplate); + + DeploymentViewVerificator.cleanFolders(new File(outputFolder).getParent()); + + return toscaDefinition; + } + + public static String getTemplateFilenname(String pathToCsar) { + File csarFile = new File(pathToCsar); + String templateFileName = csarFile.getName().replaceAll("-csar.csar", "-template.yml"); + return templateFileName; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.java new file mode 100644 index 0000000000..e877146256 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.java @@ -0,0 +1,245 @@ +/*- + * ============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.ci.tests.verificator; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils; +import org.openecomp.sdc.ci.tests.utilities.RestCDUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class VfVerificator { + + public static void verifyNumOfComponentInstances(ResourceReqDetails createResourceInUI, int numOfVFC, User user) { + ServiceVerificator.verifyNumOfComponentInstances(createResourceInUI, createResourceInUI.getVersion(), numOfVFC, user); + } + + public static void verifyRILocationChanged(ResourceReqDetails createResourceInUI, + ImmutablePair prevRIPos, User user) { + + ImmutablePair currRIPos = ResourceUIUtils.getFirstRIPos(createResourceInUI, user); + assertTrue(!prevRIPos.left.equals(currRIPos.left) || !prevRIPos.right.equals(currRIPos.right)); + } + + public static void verifyLinkCreated(ResourceReqDetails createResourceInUI, User user, int expectedRelationsSize) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing that a link was created on canvas")); + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + assertTrue(((JSONArray) jsonResource.get("componentInstancesRelations")).size() == expectedRelationsSize); + ExtentTestActions.log(Status.INFO, "The link was verified."); + + } + + public static void verifyVFMetadataInUI(ResourceReqDetails vf) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying fields on General screen through UI ...")); + assertTrue(vf.getName().equals(ResourceGeneralPage.getNameText())); + assertTrue(vf.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertTrue(vf.getCategories().get(0).getSubcategories().get(0).getName().equals(GeneralUIUtils.getSelectedElementFromDropDown(ResourceGeneralPage.getCategoryDataTestsIdAttribute()).getText())); + assertTrue(vf.getVendorName().equals(ResourceGeneralPage.getVendorNameText())); + assertTrue(vf.getVendorRelease().equals(ResourceGeneralPage.getVendorReleaseText())); + assertTrue(vf.getContactId().equals(ResourceGeneralPage.getContactIdText())); + List tagsList = ResourceGeneralPage.getElementsFromTagsTable(); + assertTrue(vf.getTags().size() == tagsList.size()); + for (int i = 0 ; i < vf.getTags().size(); i ++ ){ + assertTrue(vf.getTags().contains(tagsList.get(i).getText())); + } + assertTrue(vf.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public static void verifyVFUpdated(ResourceReqDetails vf, User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying fields on General screen through Backend ...")); + String response = RestCDUtils.getResource(vf, user).getResponse(); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response); + assertTrue(vf.getName().equals(resource.getName())); + assertTrue(vf.getDescription().equals(resource.getDescription())); + assertTrue(vf.getVendorName().equals(resource.getVendorName())); + assertTrue(vf.getVendorRelease().equals(resource.getVendorRelease())); + assertTrue(vf.getContactId().equals(resource.getContactId())); + + assertTrue(vf.getCategories().size() == (resource.getCategories().size())); + for (int i = 0 ; i < vf.getCategories().size() ; i ++) + { + CategoryDefinition expectedCategoryDefinition = vf.getCategories().get(i); + CategoryDefinition actualCategoryDefinition = resource.getCategories().get(i); + assertTrue(expectedCategoryDefinition.getName().equals(actualCategoryDefinition.getName())); + assertTrue(expectedCategoryDefinition.getSubcategories().get(i).getName().equals(actualCategoryDefinition.getSubcategories().get(i).getName())); + } + + assertTrue(vf.getTags().size() == (resource.getTags().size())); + for (int i = 0 ; i < vf.getTags().size() ; i ++){ + List expectedTags = vf.getTags(); + List actualTags = resource.getTags(); + + assertTrue(actualTags.contains(expectedTags.get(i))); + + } + } + + public static void verifyVFLifecycle(ResourceReqDetails vf, User user, LifecycleStateEnum expectedLifecycleState) { + String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String actualLifecycleState = jsonResource.get("lifecycleState").toString(); + assertTrue(expectedLifecycleState.name().equals(actualLifecycleState), "actual: " + actualLifecycleState + "-- expected: " + expectedLifecycleState); + } + + public static void verifyVfLifecycleInUI(LifeCycleStateEnum lifecycleState){ + GeneralUIUtils.ultimateWait(); + assertTrue(ResourceGeneralPage.getLifeCycleState().equals(lifecycleState.getValue())); + } + + public static void verifyInstanceVersion(ResourceReqDetails vf, User user, String instanceName, String instanceVersion){ + String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + JSONArray jsonArrayResource = (JSONArray) jsonResource.get("componentInstances"); + for (int i = 0; i < jsonArrayResource.size(); i++){ + Object object = jsonArrayResource.get(i); + try{ + JSONObject jRes = (JSONObject) JSONValue.parse(object.toString()); + String componentName = jRes.get("componentName").toString(); + if (componentName.equals(instanceName)){ + String componentVersion = jRes.get("componentVersion").toString(); + assertTrue(componentVersion.equals(instanceVersion)); + } + } + catch(Exception e){ + System.out.println("Can't test object in componentInstances array"); + Assert.fail("Can't test object in componentInstances array"); + } + } + } + + public static void verifyVfDeleted(ResourceReqDetails vf, User user){ + RestResponse response = RestCDUtils.getResource(vf, user); + assertTrue(response.getErrorCode().intValue() == 404); + } + + public static void verifyPropertiesInUI(List propertyList){ + + for (PropertyTypeEnum prop : propertyList){ + String propName = prop.getName(); + + String actualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propName).getText(); + String actualType = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_TYPE.getValue() + propName).getText(); + String actualDesciprtion = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_DESCRIPTION.getValue() + propName).getText(); + + assertTrue(propName.equals(actualName), String.format("Property name is not correct. expected:%s ; actual %s", propName, actualName)); + assertTrue(prop.getType().equals(actualType), String.format("Property type is not correct. expected:%s ; actual %s", prop.getType(), actualType)); + assertTrue(prop.getDescription().equals(actualDesciprtion), String.format("Property description is not correct. expected:%s ; actual %s", prop.getDescription(), actualDesciprtion)); + + if (prop.getSchemaDefinition() != null){ + String actualSchema = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.ENTRY_SCHEMA.getValue() + propName).getText(); + assertTrue(prop.getSchemaDefinition().equals(actualSchema), String.format("Property schema is not correct. expected:%s ; actual %s", prop.getSchemaDefinition(), actualSchema)); + } + } + } + + public static void verifyToscaArtifactsInfo(ResourceReqDetails vf, User user){ + String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + JSONObject toscaArtifacts = (JSONObject) jsonResource.get("toscaArtifacts"); + + assertEquals(2, toscaArtifacts.size()); + for (Object artifactObj : toscaArtifacts.keySet()){ + JSONObject artifact = (JSONObject) JSONValue.parse(toscaArtifacts.get(artifactObj).toString()); + assertFalse(artifact.get("artifactUUID").toString().isEmpty(), "artifactUUID field is empty"); + assertFalse(artifact.get("artifactChecksum").toString().isEmpty(), "artifactChecksum filed is empty"); + assertFalse(artifact.get("payloadUpdateDate").toString().isEmpty(), "payloadUpdateDate field is empty"); + assertFalse(artifact.get("artifactVersion").toString().equals("0"), "artifactVersion field is 0"); + } + } + + public static void verifyVfInputs(String instanceName, Map instancePropertiesMapFromJson,List propertyRowsFromTable) { + + for (int i = 0 ; i < propertyRowsFromTable.size() ; i++){ + WebElement row = propertyRowsFromTable.get(i); + String propertyNameFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "propertyName']")).getText(); + String propertyTypeFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "propertyType']")).getText(); + String instanceNameFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "instanceName']")).getText(); + String propertySchemaFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "propertySchema']")).getText(); + + assertTrue(instancePropertiesMapFromJson.containsKey(propertyNameFromTable), "No property named : " + propertyNameFromTable + "for instance " + instanceName); + String expectedType = instancePropertiesMapFromJson.get(propertyNameFromTable); + assertTrue(expectedType.equals(propertyTypeFromTable.toLowerCase()), propertyNameFromTable + "type is incorrect"); + assertTrue(instanceName.equals(instanceNameFromTable), "Instance name of property named " + propertyNameFromTable + "is incorrect"); + } + } + + public static void verifyOnboardedVnfMetadata(String vspName, Map vspMetadata) { + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying metadata"); + assertTrue(vspName.equals(ResourceGeneralPage.getNameText()), "VSP name is not valid."); + assertTrue(vspMetadata.get("description").equals(ResourceGeneralPage.getDescriptionText()), "VSP description is not valid."); + assertTrue(vspMetadata.get("subCategory").equals(GeneralUIUtils.getSelectedElementFromDropDown(ResourceGeneralPage.getCategoryDataTestsIdAttribute()).getText().toLowerCase().trim()), "VSP category is not valid."); + assertTrue(vspMetadata.get("vendorName").equals(ResourceGeneralPage.getVendorNameText()), "VSP vendor name is not valid."); + assertTrue("1.0".equals(ResourceGeneralPage.getVendorReleaseText()), "VSP version is not valid."); + List tagsList = ResourceGeneralPage.getElementsFromTagsTable(); + assertTrue(tagsList.size() == 1, "VSP tags size is not equal to 1."); + assertTrue(vspName.equals(tagsList.get(0).getText()), "VSP tag is not its name."); + assertTrue(vspMetadata.get("attContact").equals(ResourceGeneralPage.getContactIdText()), "VSP attContact is not valid."); + } + + public static void verifyIsElementDisabled(String elementLocator, String elementName){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Checking if %s is disabled", elementName)); + assertTrue(GeneralUIUtils.isElementReadOnly(elementLocator)); + } + + public static void verifyFilesChecksum(File actual, File expected){ + try { + String actualMd5OfFile = FileHandling.getMD5OfFile(actual); + String expectedMd5OfFile = FileHandling.getMD5OfFile(expected); + Assert.assertEquals(expectedMd5OfFile, actualMd5OfFile, "File does not exist"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/ui-ci/src/main/resources/Downloads/CP_WAN.yml b/ui-ci/src/main/resources/Downloads/CP_WAN.yml new file mode 100644 index 0000000000..eeabbb8490 --- /dev/null +++ b/ui-ci/src/main/resources/Downloads/CP_WAN.yml @@ -0,0 +1,23 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + org.openecomp.resource.cp.WANTedy: derived_from: org.openecomp.resource.cp.CPTedy + properties: + type: + type: string + required: false + requirements: + - virtualLink_in: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualLink_out: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualLink_in1: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualLink_out1: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualLink_in2: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualLink_out2: + capability: tosca.capabilities.network.Linkable relationship: tosca.relationships.network.LinksTo + - virtualbinding: + capability: tosca.capabilities.network.Bindable relationship: tosca.relationships.network.BindsTo \ No newline at end of file diff --git a/ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml b/ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml new file mode 100644 index 0000000000..a24d004929 --- /dev/null +++ b/ui-ci/src/main/resources/Downloads/Fortigate02_vFW_VFC.yml @@ -0,0 +1,63 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 + +node_types: + + org.openecomp.resource.vfc.vFW.Fortigate02Tedy: + derived_from: org.openecomp.resource.vfc.vFWTedy + + properties: + att-part-number: + type: string + default: "ATT-FortiGate-VM02" + vendor-name: + type: string + default: “FORTINET” + vendor-model: + type: string + default: "VM02" + vendor-model-description: + type: string + vcpu-default: + type: integer + default: 2 + vcpu-min: + type: integer + default: 1 + vcpu-max: + type: integer + default: 2 + vmemory-default: + default: 4 + type: integer + vmemory-units: + type: string + default: "GB" + vmemory-min: + type: integer + default: 1 + vmemory-max: + type: integer + default: 4 + vdisk-default: + type: integer + default: 20 + vdisk-units: + type: string + default: "GB" + vdisk-min: + type: integer + default: 2 + vdisk-max: + type: integer + default: 20 + vnf-type: + type: string + default: “Advanced FW” + software-version: + type: string + default: “5.2.4” + software-file-name: + type: string + vnf-feature: + type: string + default: “IPS, AntiVirus, URL Filter, APPID” \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/attsdc-packages.yaml b/ui-ci/src/main/resources/ci/conf/attsdc-packages.yaml new file mode 100644 index 0000000000..dcb78eefc1 --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/attsdc-packages.yaml @@ -0,0 +1,2 @@ +packages: + - org.openecomp.sdc.ci.tests.execute.resourceui \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/attsdc.yaml b/ui-ci/src/main/resources/ci/conf/attsdc.yaml new file mode 100644 index 0000000000..c5ed3db724 --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/attsdc.yaml @@ -0,0 +1,63 @@ +outputFolder: target +reportName: index.html +catalogBeHost: 127.0.0.1 +catalogFeHost: fehost +esHost: eshost +disributionClientHost: disClient +catalogFePort: 8181 +catalogBePort: 8080 +disributionClientPort: 8181 +esPort: 9200 +neoHost: neoHost +neoPort: 7474 +neoDBusername: neo4j +neoDBpassword: 123456 +url: http://localhost:8285/sdc1 +remoteTestingMachineIP: 0.0.0.0 +remoteTestingMachinePort: 5566 +remoteTesting: false +resourceConfigDir: src/test/resources/CI/tests +componentsConfigDir: src/test/resources/CI/components +importResourceConfigDir: src/test/resources/CI/importResource +importResourceTestsConfigDir: src/test/resources/CI/importResourceTests +errorConfigurationFile: ../catalog-be/src/main/resources/config/error-configuration.yaml +configurationFile: ../catalog-be/src/main/resources/config/configuration.yaml +importTypesConfigDir: src/test/resources/CI/importTypesTest +browser: FireFox +windowsDownloadDirectory: "c:\\apache-ftpserver-1.1.0\\res\\home\\" +systemUnderDebug: false +reportDBhost: dbhost +reportDBport: 27017 + +useBrowserMobProxy: false +captureTraffic: false + +titanPropertiesFile: src/main/resources/ci/conf/titan.properties + +stopOnClassFailure: false + +#List of non-abstract resources to keep during titan cleanup between tests +#Only 1.0 version will be kept +resourcesNotToDelete: + - tosca.nodes.Compute + - tosca.nodes.Database + - tosca.nodes.ObjectStorage + - tosca.nodes.BlockStorage + - tosca.nodes.LoadBalancer + - org.openecomp.resource.cp.Port + - org.openecomp.resource.vl.Network + +#Resource categories to keep (including all their subcategories) +resourceCategoriesNotToDelete: + - Generic + - Network L2-3 + - Network L4+ + - Application L4+ + - Network Connectivity + +#Service categories to keep +serviceCategoriesNotToDelete: + - Mobility + - Network L1-3 + - Network L4 + - VoIP Call Control \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/credentials.yaml b/ui-ci/src/main/resources/ci/conf/credentials.yaml new file mode 100644 index 0000000000..481b12b1e0 --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/credentials.yaml @@ -0,0 +1,48 @@ + designer: { + username: m08740, + password: 272v!suAL37, + firstname: ASDC, + lastname: VITI + } + admin: { + username: m08741, + password: 863B@rroN27, + firstname: ASDC, + lastname: VITI + } + ops: { + username: m08742, + password: 364K!NDRed63, + firstname: ASDC, + lastname: VITI + } + tester: { + username: m08743, + password: 373m@rBLE28, + firstname: ASDC, + lastname: VITI + } + governor: { + username: m08744, + password: 742M!DDLE44, + firstname: ASDC, + lastname: VITI + } + product_strategist1: { + username: m08745, + password: 824S@Nder35, + firstname: ASDC, + lastname: VITI + } + product_manager1: { + username: m08746, + password: 747ICK!Y99, + firstname: ASDC, + lastname: VITI + } + product_local: { + username: m08747, + password: 623z!Ggy75, + firstname: ASDC, + lastname: VITI + } \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/credentials.yaml_prod b/ui-ci/src/main/resources/ci/conf/credentials.yaml_prod new file mode 100644 index 0000000000..481b12b1e0 --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/credentials.yaml_prod @@ -0,0 +1,48 @@ + designer: { + username: m08740, + password: 272v!suAL37, + firstname: ASDC, + lastname: VITI + } + admin: { + username: m08741, + password: 863B@rroN27, + firstname: ASDC, + lastname: VITI + } + ops: { + username: m08742, + password: 364K!NDRed63, + firstname: ASDC, + lastname: VITI + } + tester: { + username: m08743, + password: 373m@rBLE28, + firstname: ASDC, + lastname: VITI + } + governor: { + username: m08744, + password: 742M!DDLE44, + firstname: ASDC, + lastname: VITI + } + product_strategist1: { + username: m08745, + password: 824S@Nder35, + firstname: ASDC, + lastname: VITI + } + product_manager1: { + username: m08746, + password: 747ICK!Y99, + firstname: ASDC, + lastname: VITI + } + product_local: { + username: m08747, + password: 623z!Ggy75, + firstname: ASDC, + lastname: VITI + } \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/credentials.yaml_webtest b/ui-ci/src/main/resources/ci/conf/credentials.yaml_webtest new file mode 100644 index 0000000000..ab37f7bee8 --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/credentials.yaml_webtest @@ -0,0 +1,48 @@ + designer: { + username: cs0008, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } + admin: { + username: jh0003, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } + ops: { + username: af0006, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } + tester: { + username: kb0004, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } + governor: { + username: ah0002, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } + product_strategist: { + username: m99126, + password: 1910-FruitGum, + firstname: ASDC, + lastname: KASPIN + } + product_manager: { + username: m99127, + password: 747-Airplane, + firstname: ASDC, + lastname: KASPIN + } + product_local: { + username: pm0001, + password: 123123a, + firstname: ASDC, + lastname: KASPIN + } \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/extent-config.xml b/ui-ci/src/main/resources/ci/conf/extent-config.xml new file mode 100644 index 0000000000..ab04b2678a --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/extent-config.xml @@ -0,0 +1,51 @@ + + + + + + standard + + + + UTF-8 + + + + https + + + ASDC Automation Report + + + ASDC Automation Report + + + + + + + yyyy-MM-dd + + + + HH:mm:ss + + + + "); + $('.logo-content' ).remove(); + $('.charts div:nth-child(2)').remove(); + }); + ]]> + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/log4j.properties b/ui-ci/src/main/resources/ci/conf/log4j.properties new file mode 100644 index 0000000000..3e159ec8df --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/log4j.properties @@ -0,0 +1,34 @@ +# Define the root logger with appender file +log4j.rootLogger = DEBUG, FILE, stdout + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender +log4j.appender.FILE.File=${targetlog}logs/ci-log.out + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%10c] : %m%n + +# Set the maximum file size before rollover +log4j.appender.FILE.maxFileSize=5MB + +# Set the the backup index +log4j.appender.FILE.maxBackupIndex=10 + + +############################################################# + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n + +log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG +log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout + +log4j.logger.org.openecomp.sdc.ci.tests.utils=TRACE, FILE, stdout +log4j.additivity.org.openecomp.sdc.ci.tests.utils=false + + diff --git a/ui-ci/src/main/resources/ci/conf/titan.properties b/ui-ci/src/main/resources/ci/conf/titan.properties new file mode 100644 index 0000000000..94d12cfba0 --- /dev/null +++ b/ui-ci/src/main/resources/ci/conf/titan.properties @@ -0,0 +1,7 @@ +storage.backend=cassandra +storage.hostname=cassandrahost +storage.port=9160 + +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/drivers/chromedriver.exe b/ui-ci/src/main/resources/ci/drivers/chromedriver.exe new file mode 100644 index 0000000000..97464543e7 Binary files /dev/null and b/ui-ci/src/main/resources/ci/drivers/chromedriver.exe differ diff --git a/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh b/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh new file mode 100644 index 0000000000..0d494d919d --- /dev/null +++ b/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh @@ -0,0 +1,75 @@ +#!/bin/bash + +function help_usage () +{ + echo "$0 -ip -f " + echo "for example: -ip 127.0.0.1 -f /var/tmp/userToAdd.txt" + exit +} + +function check_file_existance () +{ +echo "check_file_existance $1" +if [ $1 == "" ]; then + echo "Please provide full path to user file" + exit; +elif [ -f $1 ]; then + source $1 + USERS=("${USER_LIST[@]}") + echo "file exist" $1 +else + echo "Provided user file does not exist" + exit +fi +} + +function check_ip_existance () +{ +if [ $1 == "" ]; then + echo "Please provide ip address" + exit; +fi +} + +function addUser () +{ + #for user in "${USER_LIST[@]}"; do + for user in "${USERS[@]}"; do + PING=`ping -c 1 $IP > /var/tmp/ping.log` + pattern1='100% packet loss' + pattern2='Host Unreachable' + COUNT=`egrep -c "$pattern1|$pattern2" /var/tmp/ping.log` + if [ $COUNT -eq 0 ]; then + # curl -i -X post -d '{ "userId" : "kk1123", "role" : "ADMIN" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" http://192.168.111.9:8080/sdc2/rest/v1/user + userId=`echo $user|awk '{print $1}'` + role=`echo $user|awk '{print $2}'` + curl -i -X post -d '{ "userId" : "'${userId}'", "role" : "'${role}'" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" http://${IP}:8080/sdc2/rest/v1/user + else + echo "Host" $IP "Is Unreachable" + fi + done +} + +#main +[ $# -eq 0 ] && help_usage +while [ $# -ne 0 ]; do + case $1 in + "-f") + USER_FILE=$2 + shift 1 + shift 1 + ;; + -ip) + IP=$2 + shift 1 + shift 1 + ;; + *) +# help_usage + ;; + esac +done + +check_file_existance $USER_FILE +check_ip_existance $IP +addUser diff --git a/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh b/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh new file mode 100644 index 0000000000..396c1aa0ac --- /dev/null +++ b/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +REPORT_NAME=$1 +VERSION=$2 +ENV=$3 +IP=$3 + +if [ -z "$REPORT_NAME" ] + then + source ExtentReport/versions.info + now=$(date +'%Y-%m-%d_%H_%M') + REPORT_NAME="${now}" + VERSION="${osVersion}" + if [[ $env == *"DEV20"* ]] + then + ENV="Nightly" + else + ENV="" + fi + + fi + +/usr/bin/expect << EOF +spawn ssh admin@${IP} mkdir -p -m 775 /home/admin/reports/${ENV}/${VERSION}/UI/ + +expect { + -re ".*es.*o.*" { + exp_send "yes\r" + exp_continue + } + -re ".*sword.*" { + exp_send "Aa123456\r" + } +} + +expect eof + +spawn scp -pr ExtentReport admin@{IP}:/home/admin/reports/${ENV}/${VERSION}/UI/${REPORT_NAME}/ + +expect { + -re ".*es.*o.*" { + exp_send "yes\r" + exp_continue + } + -re ".*sword.*" { + exp_send "Aa123456\r" + } +} + +expect eof +EOF diff --git a/ui-ci/src/main/resources/ci/scripts/sendMail.sh b/ui-ci/src/main/resources/ci/scripts/sendMail.sh new file mode 100644 index 0000000000..794534fc8a --- /dev/null +++ b/ui-ci/src/main/resources/ci/scripts/sendMail.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +now=$(date +'%Y%-m%d%H%M') + +REPORT_NAME=$1 +VERSION=$2 +ENV=$3 + +RECIPIENTS1="dl-sdcqa@intl.att.com,ml636r@intl.att.com,bl5783intl.att.com,ak314p@intl.att.com,el489u@intl.att.com,hk096q@intl.att.com,bs5719@intl.att.com" +RECIPIENTS2="dl-asdcqa@intl.att.com" + +source ExtentReport/versions.info +if [ -z "$REPORT_NAME" ] + then + source ExtentReport/versions.info + now=$(date +'%Y-%m-%d_%H_%M') + REPORT_NAME="${now}" + VERSION="${osVersion}" + + +fi + +if [[ $env == *"DEV20"* ]] + then + ENV="Nightly" + RECIPIENTS=$RECIPIENTS1 + else + ENV="" + RECIPIENTS=$RECIPIENTS2 +fi + +#REPORT_ZIP_FILE=ExtentReport_${now}.zip +REPORT_FOLDER='ExtentReport' +REPORT_HTML_FILE=${REPORT_FOLDER}/*Report.html +BODY_MESSAGE='Hello, \n\n Please find automation results on following link: \n\n http://asdc-srv-210-45.tlv.intl.att.com/'${ENV}'/'${VERSION}'/UI/'${REPORT_NAME}'/SDC_UI_Extent_Report.html \n\nThanks, \nASDC QA Team\n\n ' + +#OLD_FILE=$(find ./ -type f -name ${REPORT_ZIP_FILE} -print) +#if [ ! -z ${OLD_FILE} ] +#then +# rm -f ${REPORT_ZIP_FILE} +# echo "Removing old zip file............" +#fi + +#echo "Creating new zip file" +#zip -r ${REPORT_ZIP_FILE} ./${REPORT_FOLDER} + + + +echo -e ${BODY_MESSAGE} | mail -s 'E2E Automation '$ENV' results - SDC '$VERSION -r 'ASDC@Automation.team' $RECIPIENTS diff --git a/ui-ci/src/main/resources/ci/scripts/startTest.sh b/ui-ci/src/main/resources/ci/scripts/startTest.sh new file mode 100644 index 0000000000..737b538b01 --- /dev/null +++ b/ui-ci/src/main/resources/ci/scripts/startTest.sh @@ -0,0 +1,155 @@ +#!/bin/bash +REMOTE_DEBUG=false +RERUN=true +JAVA_OPTION="" +debug_port=8000 +TEST_SUITES=testSuites +fileName=testng-failed.xml + +function help_usage () +{ + echo + echo "$0 ( ) [-r/rerun -d/debug ]" + echo "nohup ./startTest.sh ui-ci-1707.0.5-SNAPSHOT-jar-with-dependencies.jar extendedSanity.xml -r false -d true &" + echo "by default rerun is true and remote debug is false." + echo + exit 2 +} + +function isBoolean () +{ + PARAM_NAME=$1 + VALUE=$2 + if [[ ${VALUE} != "true" ]] && [[ ${VALUE} != "false" ]]; then + echo "Valid parameter" ${PARAM_NAME} "values are: true/false" + help_usage + fi +} + +function prepareFailedXmlFile () +{ + echo "1="$1 "2="$2 "fileName="${fileName} + PATTERN=`grep -w "test name=" ${FULL_PATH}/${TEST_SUITES}/$2 | awk -F'"' '{print $2}'` + sed '/ ${FULL_PATH}/${TEST_SUITES}/${fileName} + sed -i 's/thread-count="[0-9]\+"/thread-count="1"/g' ${FULL_PATH}/${TEST_SUITES}/${fileName} +} + +#main +[ $# -lt 2 ] && help_usage + +JAR_FILE=$1 +SUITE_FILE=$2 + +while [ $# -ne 0 ]; do + case $1 in + -r|rerun) + RERUN=$2 + isBoolean $1 ${RERUN} + shift 1 + shift 1 + ;; + -d|debug) + REMOTE_DEBUG=$2 + isBoolean $1 ${REMOTE_DEBUG} + shift 1 + shift 1 + ;; + *) + shift 1 + ;; + esac +done + +CURRENT_DIR=`pwd` +BASEDIR=$(dirname $0) + +if [ ${BASEDIR:0:1} = "/" ] +then + FULL_PATH=$BASEDIR +else + FULL_PATH=$CURRENT_DIR/$BASEDIR +fi +LOGS_PROP_FILE=file:${FULL_PATH}/conf/log4j.properties +############################################# +TARGET_DIR=${FULL_PATH}/target +CONF_FILE=${FULL_PATH}/conf/attsdc.yaml + +DEBUG=true +MainClass=org.openecomp.sdc.ci.tests.run.StartTest + +TESTS_DIR=/opt/app/sdc/ci/resources/tests +COMPONENTS_DIR=/opt/app/sdc/ci/resources/components + + +TARGET_LOG_DIR="${TARGET_DIR}/" + + +######ADD USERS################ + +BE_IP=`cat conf/attsdc.yaml | grep catalogBeHost| awk '{print $2}'` + +ADD_USERS_SCRIPT="addUsersFromList_new.sh" +USER_LIST="userList.txt" +chmod +x ${ADD_USERS_SCRIPT} +echo "add users..." +`./${ADD_USERS_SCRIPT} -ip ${BE_IP} -f ${USER_LIST}` + + + + +if [ ${REMOTE_DEBUG} == "true" ]; then + echo "Debug mode, Listen on port $debug_port"; + JAVA_OPTION="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${debug_port}" ; +fi + +cmd="java -Xmx2048m -Xms1024m $JAVA_OPTION -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dfilepath=${FILES_TEST} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass} $SUITE_FILE &" + + +if [ $DEBUG == "true" ] +then + $cmd +else + $cmd >> /dev/null +fi + +if [ ${RERUN} == "true" ]; then + if [ -f ${TARGET_DIR}/${fileName} ]; then + echo "Prepare" ${TARGET_DIR}/${fileName} "file to rerun all failed tests ..."; + prepareFailedXmlFile ${TARGET_DIR}/${fileName} $SUITE_FILE; + SUITE_FILE=${fileName}; + cmd="java -Xmx2048m -Xms1024m $JAVA_OPTION -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dfilepath=${FILES_TEST} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass} $SUITE_FILE &" + $cmd; + fi +fi + +status=`echo $?` + +source ExtentReport/versions.info +now=$(date +'%Y-%m-%d_%H_%M') +REPORT_NAME=${now} +VERSION=${osVersion} + +if [[ $env == *"DEV20"* ]] +then + MYENV="Nightly" +else + MYENV="" +fi + +COPY_REPORT_SCRIPT="copyToStorage.sh" +chmod +x ${COPY_REPORT_SCRIPT} +echo "copy report to storage..." +sh ./${COPY_REPORT_SCRIPT} ${REPORT_NAME} ${VERSION} ${MYENV} + + +MAILING_SCRIPT_NAME="sendMail.sh" +chmod +x ${MAILING_SCRIPT_NAME} +echo "Sending report via mail..." +`./${MAILING_SCRIPT_NAME} ${REPORT_NAME} ${VERSION} ${MYENV}` + + +echo "##################################################" +echo "################# status is ${status} #################" +echo "##################################################" + +exit $status diff --git a/ui-ci/src/main/resources/ci/scripts/userList.txt b/ui-ci/src/main/resources/ci/scripts/userList.txt new file mode 100644 index 0000000000..a1326599dc --- /dev/null +++ b/ui-ci/src/main/resources/ci/scripts/userList.txt @@ -0,0 +1 @@ +export USER_LIST=( "m99121 DESIGNER" "cs0008 DESIGNER" "kb0004 TESTER" "af0006 OPS" "ah0002 GOVERNOR" "m08740 DESIGNER" "m99124 TESTER" "m08743 TESTER" "m99123 OPS" "m08742 OPS" "m99125 GOVERNOR" "m08744 GOVERNOR" "m99122 ADMIN" "m08741 ADMIN" "m99126 PRODUCT_STRATEGIST" "m08745 PRODUCT_STRATEGIST" "m99127 PRODUCT_MANAGER" "m08746 PRODUCT_MANAGER" "md9897 DESIGNER" "m08748 DESIGNER" "m08749 TESTER" "be0695 DESIGNER" "er434w DESIGNER" "ya107f DESIGNER" "ds200p DESIGNER" "ak0333 ADMIN" "th0695 DESIGNER" "al714h DESIGNER" "ys9693 DESIGNER" "ss8214 DESIGNER" "bt750h DESIGNER" "rp955r DESIGNER" "ez6451 DESIGNER" "ia901h DESIGNER" "ah7840 DESIGNER" "ea394r DESIGNER" "ms656r DESIGNER" "ml636r DESIGNER" "it1721 DESIGNER" "sg473v DESIGNER" "sa997j DESIGNER" "az2497 DESIGNER" "ys189e DESIGNER" "ig642y DESIGNER" ) diff --git a/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml b/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml new file mode 100644 index 0000000000..f4f99db3a1 --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/testSuites/devOnboardSanity.xml b/ui-ci/src/main/resources/ci/testSuites/devOnboardSanity.xml new file mode 100644 index 0000000000..5b44e68375 --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/devOnboardSanity.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/testSuites/devSanity.xml b/ui-ci/src/main/resources/ci/testSuites/devSanity.xml new file mode 100644 index 0000000000..6c4ba547b1 --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/devSanity.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml b/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml new file mode 100644 index 0000000000..a8dcf84c73 --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/testSuites/fullCI.xml b/ui-ci/src/main/resources/ci/testSuites/fullCI.xml new file mode 100644 index 0000000000..940026d30c --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/fullCI.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml b/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml new file mode 100644 index 0000000000..e263a4a3f4 --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/testSuites/sanity.xml b/ui-ci/src/main/resources/ci/testSuites/sanity.xml new file mode 100644 index 0000000000..c8fd8f14b1 --- /dev/null +++ b/ui-ci/src/main/resources/ci/testSuites/sanity.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ui-ci/src/main/resources/images/gizmorambo.jpg b/ui-ci/src/main/resources/images/gizmorambo.jpg new file mode 100644 index 0000000000..c9a8fe8a64 Binary files /dev/null and b/ui-ci/src/main/resources/images/gizmorambo.jpg differ diff --git a/ui-ci/src/test/Completetheform.js b/ui-ci/src/test/Completetheform.js new file mode 100644 index 0000000000..7e8b7572cc --- /dev/null +++ b/ui-ci/src/test/Completetheform.js @@ -0,0 +1,3 @@ +/** + * New node file + */ diff --git a/ui-ci/tarball.xml b/ui-ci/tarball.xml new file mode 100644 index 0000000000..9d7d4c1022 --- /dev/null +++ b/ui-ci/tarball.xml @@ -0,0 +1,70 @@ + + bin + + tar + + + + ${project.build.directory}/${project.artifactId}-${project.version}-jar-with-dependencies.jar + ./ + ${project.artifactId}-${project.version}-jar-with-dependencies.jar + + + src/main/resources/ci/scripts/startTest.sh + ./ + startTest.sh + + + + src/main/resources/ci/conf/attsdc.yaml + conf + attsdc.yaml + + + src/main/resources/ci/conf/attsdc-packages.yaml + conf + attsdc-packages.yaml + + + ../catalog-be/src/main/resources/config/error-configuration.yaml + conf + error-configuration.yaml + + + ../asdc-tests/src/main/resources/ci/conf/log4j.properties + conf + log4j.properties + + + src/main/resources/ci/conf/credentials.yaml + conf + credentials.yaml + + + src/main/resources/ci/drivers/chromedriver.exe/ + drivers + chromedriver.exe + + + + + + + src/test/resources + ./ + + + src/main/resources/ci/testSuites + ./testSuites + + + src/main/resources/Files + ./Files + + + + diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java index bc6dee0ce4..db4853a8f1 100644 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java +++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java @@ -12,6 +12,7 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.openecomp.sdc.webseal.simulator.User; import org.openecomp.sdc.webseal.simulator.conf.Conf; public class Login extends HttpServlet { @@ -94,11 +95,12 @@ public class Login extends HttpServlet { } writer.println(""); - writer.println("
"); + writer.println("Create All"); + writer.println("
"); writer.println(""); writer.println(""); - + } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java index 5f4cfa93d2..a5e4a8a0eb 100644 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java +++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/RequestsClient.java @@ -17,29 +17,51 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; +import org.openecomp.sdc.webseal.simulator.conf.Conf; public class RequestsClient extends HttpServlet { private static final long serialVersionUID = 1L; @Override - protected void doGet(final HttpServletRequest request, final HttpServletResponse response) - throws ServletException, IOException { + protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { + + String hostname = request.getParameter("hostname") != null ? request.getParameter("hostname") : "127.0.0.1"; + String port = request.getParameter("port") != null ? request.getParameter("port") : "8080"; + String adminId = request.getParameter("adminId") != null ? request.getParameter("adminId") : "jh0003"; + + String createAll = request.getParameter("all"); - String userId = request.getParameter("userId"); - String role = request.getParameter("role"); - String firstName = request.getParameter("firstName"); - String lastName = request.getParameter("lastName"); - String email = request.getParameter("email"); + PrintWriter writer = response.getWriter(); - String hostname = request.getParameter("hostname") != null?request.getParameter("hostname"):"127.0.0.1"; - String port = request.getParameter("port") != null?request.getParameter("port"):"8080"; - String adminId = request.getParameter("adminId") != null?request.getParameter("adminId"):"jh0003"; + int resultCode; + + if ("true".equals(createAll)) { + Map users = Conf.getInstance().getUsers(); + for (User user : users.values()) { + resultCode = createUser(response, user.getUserId(), user.getRole().toUpperCase(), user.getFirstName(), user.getLastName(), user.getEmail(), hostname, port, adminId); + writer.println("User "+ user.getFirstName() + " " + user.getLastName() + getResultMessage(resultCode) + "
"); + } + } else { + String userId = request.getParameter("userId"); + String role = request.getParameter("role").toUpperCase(); + String firstName = request.getParameter("firstName"); + String lastName = request.getParameter("lastName"); + String email = request.getParameter("email"); + resultCode = createUser(response, userId, role, firstName, lastName, email, hostname, port, adminId); + writer.println("User "+ firstName + " " + lastName +getResultMessage(resultCode)); + } + + + } + + private String getResultMessage(int resultCode){ + return 201 == resultCode? " created successfuly":" not created ("+ resultCode +")"; + } + + private int createUser(final HttpServletResponse response, String userId, String role, String firstName, String lastName, String email, String hostname, String port, String adminId) throws IOException { response.setContentType("text/html"); - PrintWriter writer = response.getWriter(); - writer.println("userId: " + userId); - writer.println("role: " + role); // Fill the data of the request String url = "http://" + hostname + ":" + port + "/sdc2/rest/v1/user"; @@ -47,13 +69,12 @@ public class RequestsClient extends HttpServlet { HashMap headers = new HashMap(); headers.put("Content-Type", "application/json"); headers.put("USER_ID", adminId); - sendHttpPost(url, body, headers); - + return sendHttpPost(url, body, headers); } - - private String sendHttpPost(String url, String body, Map headers) throws IOException { - - String responseString=""; + + private int sendHttpPost(String url, String body, Map headers) throws IOException { + + String responseString = ""; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); @@ -79,8 +100,8 @@ public class RequestsClient extends HttpServlet { } int responseCode = con.getResponseCode(); - //logger.debug("Send POST http request, url: {}", url); - //logger.debug("Response Code: {}", responseCode); + // logger.debug("Send POST http request, url: {}", url); + // logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { @@ -91,7 +112,7 @@ public class RequestsClient extends HttpServlet { } in.close(); } catch (Exception e) { - //logger.debug("response body is null"); + // logger.debug("response body is null"); } String result; @@ -103,18 +124,18 @@ public class RequestsClient extends HttpServlet { } catch (Exception e2) { result = null; } - //logger.debug("Response body: {}", response); + // logger.debug("Response body: {}", response); if (response != null) { responseString = response.toString(); } - //Map> headerFields = con.getHeaderFields(); - //String responseMessage = con.getResponseMessage(); + // Map> headerFields = con.getHeaderFields(); + // String responseMessage = con.getResponseMessage(); con.disconnect(); - return responseString; + return responseCode; } - + } diff --git a/utils/webseal-simulator/src/main/resources/webseal.conf b/utils/webseal-simulator/src/main/resources/webseal.conf index 869b17bebc..a7026e39fa 100644 --- a/utils/webseal-simulator/src/main/resources/webseal.conf +++ b/utils/webseal-simulator/src/main/resources/webseal.conf @@ -7,7 +7,7 @@ password="123123a" firstName="Carlos" lastName="Santana" - role="Desiner" + role="Designer" email="csantana@sdc.com" }, { @@ -41,22 +41,6 @@ lastName="Shadmi" role="Governor" email="governor@sdc.com" - }, - { - userId="pm0001" - password="123123a" - firstName="Teddy" - lastName="Isashar" - role="Product Manager" - email="pm1@sdc.com" - }, - { - userId="ps0001" - password="123123a" - firstName="Eden" - lastName="Rozin" - role="Product Strategist" - email="ps1@sdc.com" } ] } -- cgit 1.2.3-korg